clang API Documentation
00001 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for statements. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/Sema/Scope.h" 00016 #include "clang/Sema/ScopeInfo.h" 00017 #include "clang/Sema/Initialization.h" 00018 #include "clang/Sema/Lookup.h" 00019 #include "clang/AST/ASTContext.h" 00020 #include "clang/AST/CharUnits.h" 00021 #include "clang/AST/DeclObjC.h" 00022 #include "clang/AST/EvaluatedExprVisitor.h" 00023 #include "clang/AST/ExprCXX.h" 00024 #include "clang/AST/ExprObjC.h" 00025 #include "clang/AST/StmtObjC.h" 00026 #include "clang/AST/StmtCXX.h" 00027 #include "clang/AST/TypeLoc.h" 00028 #include "clang/Lex/Preprocessor.h" 00029 #include "clang/Basic/TargetInfo.h" 00030 #include "llvm/ADT/ArrayRef.h" 00031 #include "llvm/ADT/STLExtras.h" 00032 #include "llvm/ADT/SmallPtrSet.h" 00033 #include "llvm/ADT/SmallString.h" 00034 #include "llvm/ADT/SmallVector.h" 00035 using namespace clang; 00036 using namespace sema; 00037 00038 StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 00039 Expr *E = expr.get(); 00040 if (!E) // FIXME: FullExprArg has no error state? 00041 return StmtError(); 00042 00043 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 00044 // void expression for its side effects. Conversion to void allows any 00045 // operand, even incomplete types. 00046 00047 // Same thing in for stmt first clause (when expr) and third clause. 00048 return Owned(static_cast<Stmt*>(E)); 00049 } 00050 00051 00052 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 00053 bool HasLeadingEmptyMacro) { 00054 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro)); 00055 } 00056 00057 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 00058 SourceLocation EndLoc) { 00059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 00060 00061 // If we have an invalid decl, just return an error. 00062 if (DG.isNull()) return StmtError(); 00063 00064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 00065 } 00066 00067 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 00068 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 00069 00070 // If we have an invalid decl, just return. 00071 if (DG.isNull() || !DG.isSingleDecl()) return; 00072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl()); 00073 00074 // suppress any potential 'unused variable' warning. 00075 var->setUsed(); 00076 00077 // foreach variables are never actually initialized in the way that 00078 // the parser came up with. 00079 var->setInit(0); 00080 00081 // In ARC, we don't need to retain the iteration variable of a fast 00082 // enumeration loop. Rather than actually trying to catch that 00083 // during declaration processing, we remove the consequences here. 00084 if (getLangOpts().ObjCAutoRefCount) { 00085 QualType type = var->getType(); 00086 00087 // Only do this if we inferred the lifetime. Inferred lifetime 00088 // will show up as a local qualifier because explicit lifetime 00089 // should have shown up as an AttributedType instead. 00090 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 00091 // Add 'const' and mark the variable as pseudo-strong. 00092 var->setType(type.withConst()); 00093 var->setARCPseudoStrong(true); 00094 } 00095 } 00096 } 00097 00098 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='. 00099 /// 00100 /// Adding a cast to void (or other expression wrappers) will prevent the 00101 /// warning from firing. 00102 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 00103 SourceLocation Loc; 00104 bool IsNotEqual, CanAssign; 00105 00106 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 00107 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE) 00108 return false; 00109 00110 Loc = Op->getOperatorLoc(); 00111 IsNotEqual = Op->getOpcode() == BO_NE; 00112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 00113 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 00114 if (Op->getOperator() != OO_EqualEqual && 00115 Op->getOperator() != OO_ExclaimEqual) 00116 return false; 00117 00118 Loc = Op->getOperatorLoc(); 00119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 00120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 00121 } else { 00122 // Not a typo-prone comparison. 00123 return false; 00124 } 00125 00126 // Suppress warnings when the operator, suspicious as it may be, comes from 00127 // a macro expansion. 00128 if (Loc.isMacroID()) 00129 return false; 00130 00131 S.Diag(Loc, diag::warn_unused_comparison) 00132 << (unsigned)IsNotEqual << E->getSourceRange(); 00133 00134 // If the LHS is a plausible entity to assign to, provide a fixit hint to 00135 // correct common typos. 00136 if (CanAssign) { 00137 if (IsNotEqual) 00138 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 00139 << FixItHint::CreateReplacement(Loc, "|="); 00140 else 00141 S.Diag(Loc, diag::note_equality_comparison_to_assign) 00142 << FixItHint::CreateReplacement(Loc, "="); 00143 } 00144 00145 return true; 00146 } 00147 00148 void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 00149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 00150 return DiagnoseUnusedExprResult(Label->getSubStmt()); 00151 00152 const Expr *E = dyn_cast_or_null<Expr>(S); 00153 if (!E) 00154 return; 00155 00156 SourceLocation Loc; 00157 SourceRange R1, R2; 00158 if (SourceMgr.isInSystemMacro(E->getExprLoc()) || 00159 !E->isUnusedResultAWarning(Loc, R1, R2, Context)) 00160 return; 00161 00162 // Okay, we have an unused result. Depending on what the base expression is, 00163 // we might want to make a more specific diagnostic. Check for one of these 00164 // cases now. 00165 unsigned DiagID = diag::warn_unused_expr; 00166 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 00167 E = Temps->getSubExpr(); 00168 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 00169 E = TempExpr->getSubExpr(); 00170 00171 if (DiagnoseUnusedComparison(*this, E)) 00172 return; 00173 00174 E = E->IgnoreParenImpCasts(); 00175 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 00176 if (E->getType()->isVoidType()) 00177 return; 00178 00179 // If the callee has attribute pure, const, or warn_unused_result, warn with 00180 // a more specific message to make it clear what is happening. 00181 if (const Decl *FD = CE->getCalleeDecl()) { 00182 if (FD->getAttr<WarnUnusedResultAttr>()) { 00183 Diag(Loc, diag::warn_unused_result) << R1 << R2; 00184 return; 00185 } 00186 if (FD->getAttr<PureAttr>()) { 00187 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 00188 return; 00189 } 00190 if (FD->getAttr<ConstAttr>()) { 00191 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 00192 return; 00193 } 00194 } 00195 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 00196 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { 00197 Diag(Loc, diag::err_arc_unused_init_message) << R1; 00198 return; 00199 } 00200 const ObjCMethodDecl *MD = ME->getMethodDecl(); 00201 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 00202 Diag(Loc, diag::warn_unused_result) << R1 << R2; 00203 return; 00204 } 00205 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 00206 const Expr *Source = POE->getSyntacticForm(); 00207 if (isa<ObjCSubscriptRefExpr>(Source)) 00208 DiagID = diag::warn_unused_container_subscript_expr; 00209 else 00210 DiagID = diag::warn_unused_property_expr; 00211 } else if (const CXXFunctionalCastExpr *FC 00212 = dyn_cast<CXXFunctionalCastExpr>(E)) { 00213 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 00214 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 00215 return; 00216 } 00217 // Diagnose "(void*) blah" as a typo for "(void) blah". 00218 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 00219 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 00220 QualType T = TI->getType(); 00221 00222 // We really do want to use the non-canonical type here. 00223 if (T == Context.VoidPtrTy) { 00224 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 00225 00226 Diag(Loc, diag::warn_unused_voidptr) 00227 << FixItHint::CreateRemoval(TL.getStarLoc()); 00228 return; 00229 } 00230 } 00231 00232 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 00233 } 00234 00235 void Sema::ActOnStartOfCompoundStmt() { 00236 PushCompoundScope(); 00237 } 00238 00239 void Sema::ActOnFinishOfCompoundStmt() { 00240 PopCompoundScope(); 00241 } 00242 00243 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { 00244 return getCurFunction()->CompoundScopes.back(); 00245 } 00246 00247 StmtResult 00248 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 00249 MultiStmtArg elts, bool isStmtExpr) { 00250 unsigned NumElts = elts.size(); 00251 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 00252 // If we're in C89 mode, check that we don't have any decls after stmts. If 00253 // so, emit an extension diagnostic. 00254 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { 00255 // Note that __extension__ can be around a decl. 00256 unsigned i = 0; 00257 // Skip over all declarations. 00258 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 00259 /*empty*/; 00260 00261 // We found the end of the list or a statement. Scan for another declstmt. 00262 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 00263 /*empty*/; 00264 00265 if (i != NumElts) { 00266 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 00267 Diag(D->getLocation(), diag::ext_mixed_decls_code); 00268 } 00269 } 00270 // Warn about unused expressions in statements. 00271 for (unsigned i = 0; i != NumElts; ++i) { 00272 // Ignore statements that are last in a statement expression. 00273 if (isStmtExpr && i == NumElts - 1) 00274 continue; 00275 00276 DiagnoseUnusedExprResult(Elts[i]); 00277 } 00278 00279 // Check for suspicious empty body (null statement) in `for' and `while' 00280 // statements. Don't do anything for template instantiations, this just adds 00281 // noise. 00282 if (NumElts != 0 && !CurrentInstantiationScope && 00283 getCurCompoundScope().HasEmptyLoopBodies) { 00284 for (unsigned i = 0; i != NumElts - 1; ++i) 00285 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); 00286 } 00287 00288 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 00289 } 00290 00291 StmtResult 00292 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 00293 SourceLocation DotDotDotLoc, Expr *RHSVal, 00294 SourceLocation ColonLoc) { 00295 assert((LHSVal != 0) && "missing expression in case statement"); 00296 00297 if (getCurFunction()->SwitchStack.empty()) { 00298 Diag(CaseLoc, diag::err_case_not_in_switch); 00299 return StmtError(); 00300 } 00301 00302 if (!getLangOpts().CPlusPlus0x) { 00303 // C99 6.8.4.2p3: The expression shall be an integer constant. 00304 // However, GCC allows any evaluatable integer expression. 00305 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) { 00306 LHSVal = VerifyIntegerConstantExpression(LHSVal).take(); 00307 if (!LHSVal) 00308 return StmtError(); 00309 } 00310 00311 // GCC extension: The expression shall be an integer constant. 00312 00313 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) { 00314 RHSVal = VerifyIntegerConstantExpression(RHSVal).take(); 00315 // Recover from an error by just forgetting about it. 00316 } 00317 } 00318 00319 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 00320 ColonLoc); 00321 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 00322 return Owned(CS); 00323 } 00324 00325 /// ActOnCaseStmtBody - This installs a statement as the body of a case. 00326 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 00327 DiagnoseUnusedExprResult(SubStmt); 00328 00329 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 00330 CS->setSubStmt(SubStmt); 00331 } 00332 00333 StmtResult 00334 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 00335 Stmt *SubStmt, Scope *CurScope) { 00336 DiagnoseUnusedExprResult(SubStmt); 00337 00338 if (getCurFunction()->SwitchStack.empty()) { 00339 Diag(DefaultLoc, diag::err_default_not_in_switch); 00340 return Owned(SubStmt); 00341 } 00342 00343 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 00344 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 00345 return Owned(DS); 00346 } 00347 00348 StmtResult 00349 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 00350 SourceLocation ColonLoc, Stmt *SubStmt) { 00351 // If the label was multiply defined, reject it now. 00352 if (TheDecl->getStmt()) { 00353 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 00354 Diag(TheDecl->getLocation(), diag::note_previous_definition); 00355 return Owned(SubStmt); 00356 } 00357 00358 // Otherwise, things are good. Fill in the declaration and return it. 00359 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 00360 TheDecl->setStmt(LS); 00361 if (!TheDecl->isGnuLocal()) 00362 TheDecl->setLocation(IdentLoc); 00363 return Owned(LS); 00364 } 00365 00366 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc, 00367 const AttrVec &Attrs, 00368 Stmt *SubStmt) { 00369 // Fill in the declaration and return it. Variable length will require to 00370 // change this to AttributedStmt::Create(Context, ....); 00371 // and probably using ArrayRef 00372 AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt); 00373 return Owned(LS); 00374 } 00375 00376 StmtResult 00377 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 00378 Stmt *thenStmt, SourceLocation ElseLoc, 00379 Stmt *elseStmt) { 00380 ExprResult CondResult(CondVal.release()); 00381 00382 VarDecl *ConditionVar = 0; 00383 if (CondVar) { 00384 ConditionVar = cast<VarDecl>(CondVar); 00385 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 00386 if (CondResult.isInvalid()) 00387 return StmtError(); 00388 } 00389 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 00390 if (!ConditionExpr) 00391 return StmtError(); 00392 00393 DiagnoseUnusedExprResult(thenStmt); 00394 00395 if (!elseStmt) { 00396 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt, 00397 diag::warn_empty_if_body); 00398 } 00399 00400 DiagnoseUnusedExprResult(elseStmt); 00401 00402 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 00403 thenStmt, ElseLoc, elseStmt)); 00404 } 00405 00406 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 00407 /// the specified width and sign. If an overflow occurs, detect it and emit 00408 /// the specified diagnostic. 00409 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 00410 unsigned NewWidth, bool NewSign, 00411 SourceLocation Loc, 00412 unsigned DiagID) { 00413 // Perform a conversion to the promoted condition type if needed. 00414 if (NewWidth > Val.getBitWidth()) { 00415 // If this is an extension, just do it. 00416 Val = Val.extend(NewWidth); 00417 Val.setIsSigned(NewSign); 00418 00419 // If the input was signed and negative and the output is 00420 // unsigned, don't bother to warn: this is implementation-defined 00421 // behavior. 00422 // FIXME: Introduce a second, default-ignored warning for this case? 00423 } else if (NewWidth < Val.getBitWidth()) { 00424 // If this is a truncation, check for overflow. 00425 llvm::APSInt ConvVal(Val); 00426 ConvVal = ConvVal.trunc(NewWidth); 00427 ConvVal.setIsSigned(NewSign); 00428 ConvVal = ConvVal.extend(Val.getBitWidth()); 00429 ConvVal.setIsSigned(Val.isSigned()); 00430 if (ConvVal != Val) 00431 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 00432 00433 // Regardless of whether a diagnostic was emitted, really do the 00434 // truncation. 00435 Val = Val.trunc(NewWidth); 00436 Val.setIsSigned(NewSign); 00437 } else if (NewSign != Val.isSigned()) { 00438 // Convert the sign to match the sign of the condition. This can cause 00439 // overflow as well: unsigned(INTMIN) 00440 // We don't diagnose this overflow, because it is implementation-defined 00441 // behavior. 00442 // FIXME: Introduce a second, default-ignored warning for this case? 00443 llvm::APSInt OldVal(Val); 00444 Val.setIsSigned(NewSign); 00445 } 00446 } 00447 00448 namespace { 00449 struct CaseCompareFunctor { 00450 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 00451 const llvm::APSInt &RHS) { 00452 return LHS.first < RHS; 00453 } 00454 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 00455 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 00456 return LHS.first < RHS.first; 00457 } 00458 bool operator()(const llvm::APSInt &LHS, 00459 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 00460 return LHS < RHS.first; 00461 } 00462 }; 00463 } 00464 00465 /// CmpCaseVals - Comparison predicate for sorting case values. 00466 /// 00467 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 00468 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 00469 if (lhs.first < rhs.first) 00470 return true; 00471 00472 if (lhs.first == rhs.first && 00473 lhs.second->getCaseLoc().getRawEncoding() 00474 < rhs.second->getCaseLoc().getRawEncoding()) 00475 return true; 00476 return false; 00477 } 00478 00479 /// CmpEnumVals - Comparison predicate for sorting enumeration values. 00480 /// 00481 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 00482 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 00483 { 00484 return lhs.first < rhs.first; 00485 } 00486 00487 /// EqEnumVals - Comparison preficate for uniqing enumeration values. 00488 /// 00489 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 00490 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 00491 { 00492 return lhs.first == rhs.first; 00493 } 00494 00495 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 00496 /// potentially integral-promoted expression @p expr. 00497 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 00498 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 00499 expr = cleanups->getSubExpr(); 00500 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 00501 if (impcast->getCastKind() != CK_IntegralCast) break; 00502 expr = impcast->getSubExpr(); 00503 } 00504 return expr->getType(); 00505 } 00506 00507 StmtResult 00508 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 00509 Decl *CondVar) { 00510 ExprResult CondResult; 00511 00512 VarDecl *ConditionVar = 0; 00513 if (CondVar) { 00514 ConditionVar = cast<VarDecl>(CondVar); 00515 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 00516 if (CondResult.isInvalid()) 00517 return StmtError(); 00518 00519 Cond = CondResult.release(); 00520 } 00521 00522 if (!Cond) 00523 return StmtError(); 00524 00525 class SwitchConvertDiagnoser : public ICEConvertDiagnoser { 00526 Expr *Cond; 00527 00528 public: 00529 SwitchConvertDiagnoser(Expr *Cond) 00530 : ICEConvertDiagnoser(false, true), Cond(Cond) { } 00531 00532 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 00533 QualType T) { 00534 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; 00535 } 00536 00537 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 00538 QualType T) { 00539 return S.Diag(Loc, diag::err_switch_incomplete_class_type) 00540 << T << Cond->getSourceRange(); 00541 } 00542 00543 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 00544 QualType T, 00545 QualType ConvTy) { 00546 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; 00547 } 00548 00549 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 00550 QualType ConvTy) { 00551 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 00552 << ConvTy->isEnumeralType() << ConvTy; 00553 } 00554 00555 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 00556 QualType T) { 00557 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; 00558 } 00559 00560 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 00561 QualType ConvTy) { 00562 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 00563 << ConvTy->isEnumeralType() << ConvTy; 00564 } 00565 00566 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 00567 QualType T, 00568 QualType ConvTy) { 00569 return DiagnosticBuilder::getEmpty(); 00570 } 00571 } SwitchDiagnoser(Cond); 00572 00573 CondResult 00574 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser, 00575 /*AllowScopedEnumerations*/ true); 00576 if (CondResult.isInvalid()) return StmtError(); 00577 Cond = CondResult.take(); 00578 00579 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 00580 CondResult = UsualUnaryConversions(Cond); 00581 if (CondResult.isInvalid()) return StmtError(); 00582 Cond = CondResult.take(); 00583 00584 if (!CondVar) { 00585 CheckImplicitConversions(Cond, SwitchLoc); 00586 CondResult = MaybeCreateExprWithCleanups(Cond); 00587 if (CondResult.isInvalid()) 00588 return StmtError(); 00589 Cond = CondResult.take(); 00590 } 00591 00592 getCurFunction()->setHasBranchIntoScope(); 00593 00594 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 00595 getCurFunction()->SwitchStack.push_back(SS); 00596 return Owned(SS); 00597 } 00598 00599 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 00600 if (Val.getBitWidth() < BitWidth) 00601 Val = Val.extend(BitWidth); 00602 else if (Val.getBitWidth() > BitWidth) 00603 Val = Val.trunc(BitWidth); 00604 Val.setIsSigned(IsSigned); 00605 } 00606 00607 StmtResult 00608 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 00609 Stmt *BodyStmt) { 00610 SwitchStmt *SS = cast<SwitchStmt>(Switch); 00611 assert(SS == getCurFunction()->SwitchStack.back() && 00612 "switch stack missing push/pop!"); 00613 00614 SS->setBody(BodyStmt, SwitchLoc); 00615 getCurFunction()->SwitchStack.pop_back(); 00616 00617 Expr *CondExpr = SS->getCond(); 00618 if (!CondExpr) return StmtError(); 00619 00620 QualType CondType = CondExpr->getType(); 00621 00622 Expr *CondExprBeforePromotion = CondExpr; 00623 QualType CondTypeBeforePromotion = 00624 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 00625 00626 // C++ 6.4.2.p2: 00627 // Integral promotions are performed (on the switch condition). 00628 // 00629 // A case value unrepresentable by the original switch condition 00630 // type (before the promotion) doesn't make sense, even when it can 00631 // be represented by the promoted type. Therefore we need to find 00632 // the pre-promotion type of the switch condition. 00633 if (!CondExpr->isTypeDependent()) { 00634 // We have already converted the expression to an integral or enumeration 00635 // type, when we started the switch statement. If we don't have an 00636 // appropriate type now, just return an error. 00637 if (!CondType->isIntegralOrEnumerationType()) 00638 return StmtError(); 00639 00640 if (CondExpr->isKnownToHaveBooleanValue()) { 00641 // switch(bool_expr) {...} is often a programmer error, e.g. 00642 // switch(n && mask) { ... } // Doh - should be "n & mask". 00643 // One can always use an if statement instead of switch(bool_expr). 00644 Diag(SwitchLoc, diag::warn_bool_switch_condition) 00645 << CondExpr->getSourceRange(); 00646 } 00647 } 00648 00649 // Get the bitwidth of the switched-on value before promotions. We must 00650 // convert the integer case values to this width before comparison. 00651 bool HasDependentValue 00652 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 00653 unsigned CondWidth 00654 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 00655 bool CondIsSigned 00656 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 00657 00658 // Accumulate all of the case values in a vector so that we can sort them 00659 // and detect duplicates. This vector contains the APInt for the case after 00660 // it has been converted to the condition type. 00661 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 00662 CaseValsTy CaseVals; 00663 00664 // Keep track of any GNU case ranges we see. The APSInt is the low value. 00665 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 00666 CaseRangesTy CaseRanges; 00667 00668 DefaultStmt *TheDefaultStmt = 0; 00669 00670 bool CaseListIsErroneous = false; 00671 00672 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 00673 SC = SC->getNextSwitchCase()) { 00674 00675 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 00676 if (TheDefaultStmt) { 00677 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 00678 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 00679 00680 // FIXME: Remove the default statement from the switch block so that 00681 // we'll return a valid AST. This requires recursing down the AST and 00682 // finding it, not something we are set up to do right now. For now, 00683 // just lop the entire switch stmt out of the AST. 00684 CaseListIsErroneous = true; 00685 } 00686 TheDefaultStmt = DS; 00687 00688 } else { 00689 CaseStmt *CS = cast<CaseStmt>(SC); 00690 00691 Expr *Lo = CS->getLHS(); 00692 00693 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 00694 HasDependentValue = true; 00695 break; 00696 } 00697 00698 llvm::APSInt LoVal; 00699 00700 if (getLangOpts().CPlusPlus0x) { 00701 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 00702 // constant expression of the promoted type of the switch condition. 00703 ExprResult ConvLo = 00704 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue); 00705 if (ConvLo.isInvalid()) { 00706 CaseListIsErroneous = true; 00707 continue; 00708 } 00709 Lo = ConvLo.take(); 00710 } else { 00711 // We already verified that the expression has a i-c-e value (C99 00712 // 6.8.4.2p3) - get that value now. 00713 LoVal = Lo->EvaluateKnownConstInt(Context); 00714 00715 // If the LHS is not the same type as the condition, insert an implicit 00716 // cast. 00717 Lo = DefaultLvalueConversion(Lo).take(); 00718 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 00719 } 00720 00721 // Convert the value to the same width/sign as the condition had prior to 00722 // integral promotions. 00723 // 00724 // FIXME: This causes us to reject valid code: 00725 // switch ((char)c) { case 256: case 0: return 0; } 00726 // Here we claim there is a duplicated condition value, but there is not. 00727 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 00728 Lo->getLocStart(), 00729 diag::warn_case_value_overflow); 00730 00731 CS->setLHS(Lo); 00732 00733 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 00734 if (CS->getRHS()) { 00735 if (CS->getRHS()->isTypeDependent() || 00736 CS->getRHS()->isValueDependent()) { 00737 HasDependentValue = true; 00738 break; 00739 } 00740 CaseRanges.push_back(std::make_pair(LoVal, CS)); 00741 } else 00742 CaseVals.push_back(std::make_pair(LoVal, CS)); 00743 } 00744 } 00745 00746 if (!HasDependentValue) { 00747 // If we don't have a default statement, check whether the 00748 // condition is constant. 00749 llvm::APSInt ConstantCondValue; 00750 bool HasConstantCond = false; 00751 if (!HasDependentValue && !TheDefaultStmt) { 00752 HasConstantCond 00753 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context, 00754 Expr::SE_AllowSideEffects); 00755 assert(!HasConstantCond || 00756 (ConstantCondValue.getBitWidth() == CondWidth && 00757 ConstantCondValue.isSigned() == CondIsSigned)); 00758 } 00759 bool ShouldCheckConstantCond = HasConstantCond; 00760 00761 // Sort all the scalar case values so we can easily detect duplicates. 00762 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 00763 00764 if (!CaseVals.empty()) { 00765 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 00766 if (ShouldCheckConstantCond && 00767 CaseVals[i].first == ConstantCondValue) 00768 ShouldCheckConstantCond = false; 00769 00770 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 00771 // If we have a duplicate, report it. 00772 // First, determine if either case value has a name 00773 StringRef PrevString, CurrString; 00774 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); 00775 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); 00776 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { 00777 PrevString = DeclRef->getDecl()->getName(); 00778 } 00779 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { 00780 CurrString = DeclRef->getDecl()->getName(); 00781 } 00782 llvm::SmallString<16> CaseValStr; 00783 CaseVals[i-1].first.toString(CaseValStr); 00784 00785 if (PrevString == CurrString) 00786 Diag(CaseVals[i].second->getLHS()->getLocStart(), 00787 diag::err_duplicate_case) << 00788 (PrevString.empty() ? CaseValStr.str() : PrevString); 00789 else 00790 Diag(CaseVals[i].second->getLHS()->getLocStart(), 00791 diag::err_duplicate_case_differing_expr) << 00792 (PrevString.empty() ? CaseValStr.str() : PrevString) << 00793 (CurrString.empty() ? CaseValStr.str() : CurrString) << 00794 CaseValStr; 00795 00796 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 00797 diag::note_duplicate_case_prev); 00798 // FIXME: We really want to remove the bogus case stmt from the 00799 // substmt, but we have no way to do this right now. 00800 CaseListIsErroneous = true; 00801 } 00802 } 00803 } 00804 00805 // Detect duplicate case ranges, which usually don't exist at all in 00806 // the first place. 00807 if (!CaseRanges.empty()) { 00808 // Sort all the case ranges by their low value so we can easily detect 00809 // overlaps between ranges. 00810 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 00811 00812 // Scan the ranges, computing the high values and removing empty ranges. 00813 std::vector<llvm::APSInt> HiVals; 00814 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 00815 llvm::APSInt &LoVal = CaseRanges[i].first; 00816 CaseStmt *CR = CaseRanges[i].second; 00817 Expr *Hi = CR->getRHS(); 00818 llvm::APSInt HiVal; 00819 00820 if (getLangOpts().CPlusPlus0x) { 00821 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 00822 // constant expression of the promoted type of the switch condition. 00823 ExprResult ConvHi = 00824 CheckConvertedConstantExpression(Hi, CondType, HiVal, 00825 CCEK_CaseValue); 00826 if (ConvHi.isInvalid()) { 00827 CaseListIsErroneous = true; 00828 continue; 00829 } 00830 Hi = ConvHi.take(); 00831 } else { 00832 HiVal = Hi->EvaluateKnownConstInt(Context); 00833 00834 // If the RHS is not the same type as the condition, insert an 00835 // implicit cast. 00836 Hi = DefaultLvalueConversion(Hi).take(); 00837 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 00838 } 00839 00840 // Convert the value to the same width/sign as the condition. 00841 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 00842 Hi->getLocStart(), 00843 diag::warn_case_value_overflow); 00844 00845 CR->setRHS(Hi); 00846 00847 // If the low value is bigger than the high value, the case is empty. 00848 if (LoVal > HiVal) { 00849 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 00850 << SourceRange(CR->getLHS()->getLocStart(), 00851 Hi->getLocEnd()); 00852 CaseRanges.erase(CaseRanges.begin()+i); 00853 --i, --e; 00854 continue; 00855 } 00856 00857 if (ShouldCheckConstantCond && 00858 LoVal <= ConstantCondValue && 00859 ConstantCondValue <= HiVal) 00860 ShouldCheckConstantCond = false; 00861 00862 HiVals.push_back(HiVal); 00863 } 00864 00865 // Rescan the ranges, looking for overlap with singleton values and other 00866 // ranges. Since the range list is sorted, we only need to compare case 00867 // ranges with their neighbors. 00868 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 00869 llvm::APSInt &CRLo = CaseRanges[i].first; 00870 llvm::APSInt &CRHi = HiVals[i]; 00871 CaseStmt *CR = CaseRanges[i].second; 00872 00873 // Check to see whether the case range overlaps with any 00874 // singleton cases. 00875 CaseStmt *OverlapStmt = 0; 00876 llvm::APSInt OverlapVal(32); 00877 00878 // Find the smallest value >= the lower bound. If I is in the 00879 // case range, then we have overlap. 00880 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 00881 CaseVals.end(), CRLo, 00882 CaseCompareFunctor()); 00883 if (I != CaseVals.end() && I->first < CRHi) { 00884 OverlapVal = I->first; // Found overlap with scalar. 00885 OverlapStmt = I->second; 00886 } 00887 00888 // Find the smallest value bigger than the upper bound. 00889 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 00890 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 00891 OverlapVal = (I-1)->first; // Found overlap with scalar. 00892 OverlapStmt = (I-1)->second; 00893 } 00894 00895 // Check to see if this case stmt overlaps with the subsequent 00896 // case range. 00897 if (i && CRLo <= HiVals[i-1]) { 00898 OverlapVal = HiVals[i-1]; // Found overlap with range. 00899 OverlapStmt = CaseRanges[i-1].second; 00900 } 00901 00902 if (OverlapStmt) { 00903 // If we have a duplicate, report it. 00904 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 00905 << OverlapVal.toString(10); 00906 Diag(OverlapStmt->getLHS()->getLocStart(), 00907 diag::note_duplicate_case_prev); 00908 // FIXME: We really want to remove the bogus case stmt from the 00909 // substmt, but we have no way to do this right now. 00910 CaseListIsErroneous = true; 00911 } 00912 } 00913 } 00914 00915 // Complain if we have a constant condition and we didn't find a match. 00916 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 00917 // TODO: it would be nice if we printed enums as enums, chars as 00918 // chars, etc. 00919 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 00920 << ConstantCondValue.toString(10) 00921 << CondExpr->getSourceRange(); 00922 } 00923 00924 // Check to see if switch is over an Enum and handles all of its 00925 // values. We only issue a warning if there is not 'default:', but 00926 // we still do the analysis to preserve this information in the AST 00927 // (which can be used by flow-based analyes). 00928 // 00929 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 00930 00931 // If switch has default case, then ignore it. 00932 if (!CaseListIsErroneous && !HasConstantCond && ET) { 00933 const EnumDecl *ED = ET->getDecl(); 00934 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 00935 EnumValsTy; 00936 EnumValsTy EnumVals; 00937 00938 // Gather all enum values, set their type and sort them, 00939 // allowing easier comparison with CaseVals. 00940 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 00941 EDI != ED->enumerator_end(); ++EDI) { 00942 llvm::APSInt Val = EDI->getInitVal(); 00943 AdjustAPSInt(Val, CondWidth, CondIsSigned); 00944 EnumVals.push_back(std::make_pair(Val, &*EDI)); 00945 } 00946 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 00947 EnumValsTy::iterator EIend = 00948 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 00949 00950 // See which case values aren't in enum. 00951 EnumValsTy::const_iterator EI = EnumVals.begin(); 00952 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 00953 CI != CaseVals.end(); CI++) { 00954 while (EI != EIend && EI->first < CI->first) 00955 EI++; 00956 if (EI == EIend || EI->first > CI->first) 00957 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 00958 << CondTypeBeforePromotion; 00959 } 00960 // See which of case ranges aren't in enum 00961 EI = EnumVals.begin(); 00962 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 00963 RI != CaseRanges.end() && EI != EIend; RI++) { 00964 while (EI != EIend && EI->first < RI->first) 00965 EI++; 00966 00967 if (EI == EIend || EI->first != RI->first) { 00968 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 00969 << CondTypeBeforePromotion; 00970 } 00971 00972 llvm::APSInt Hi = 00973 RI->second->getRHS()->EvaluateKnownConstInt(Context); 00974 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 00975 while (EI != EIend && EI->first < Hi) 00976 EI++; 00977 if (EI == EIend || EI->first != Hi) 00978 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 00979 << CondTypeBeforePromotion; 00980 } 00981 00982 // Check which enum vals aren't in switch 00983 CaseValsTy::const_iterator CI = CaseVals.begin(); 00984 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 00985 bool hasCasesNotInSwitch = false; 00986 00987 SmallVector<DeclarationName,8> UnhandledNames; 00988 00989 for (EI = EnumVals.begin(); EI != EIend; EI++){ 00990 // Drop unneeded case values 00991 llvm::APSInt CIVal; 00992 while (CI != CaseVals.end() && CI->first < EI->first) 00993 CI++; 00994 00995 if (CI != CaseVals.end() && CI->first == EI->first) 00996 continue; 00997 00998 // Drop unneeded case ranges 00999 for (; RI != CaseRanges.end(); RI++) { 01000 llvm::APSInt Hi = 01001 RI->second->getRHS()->EvaluateKnownConstInt(Context); 01002 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 01003 if (EI->first <= Hi) 01004 break; 01005 } 01006 01007 if (RI == CaseRanges.end() || EI->first < RI->first) { 01008 hasCasesNotInSwitch = true; 01009 UnhandledNames.push_back(EI->second->getDeclName()); 01010 } 01011 } 01012 01013 if (TheDefaultStmt && UnhandledNames.empty()) 01014 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); 01015 01016 // Produce a nice diagnostic if multiple values aren't handled. 01017 switch (UnhandledNames.size()) { 01018 case 0: break; 01019 case 1: 01020 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01021 ? diag::warn_def_missing_case1 : diag::warn_missing_case1) 01022 << UnhandledNames[0]; 01023 break; 01024 case 2: 01025 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01026 ? diag::warn_def_missing_case2 : diag::warn_missing_case2) 01027 << UnhandledNames[0] << UnhandledNames[1]; 01028 break; 01029 case 3: 01030 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01031 ? diag::warn_def_missing_case3 : diag::warn_missing_case3) 01032 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 01033 break; 01034 default: 01035 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01036 ? diag::warn_def_missing_cases : diag::warn_missing_cases) 01037 << (unsigned)UnhandledNames.size() 01038 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 01039 break; 01040 } 01041 01042 if (!hasCasesNotInSwitch) 01043 SS->setAllEnumCasesCovered(); 01044 } 01045 } 01046 01047 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt, 01048 diag::warn_empty_switch_body); 01049 01050 // FIXME: If the case list was broken is some way, we don't have a good system 01051 // to patch it up. Instead, just return the whole substmt as broken. 01052 if (CaseListIsErroneous) 01053 return StmtError(); 01054 01055 return Owned(SS); 01056 } 01057 01058 StmtResult 01059 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 01060 Decl *CondVar, Stmt *Body) { 01061 ExprResult CondResult(Cond.release()); 01062 01063 VarDecl *ConditionVar = 0; 01064 if (CondVar) { 01065 ConditionVar = cast<VarDecl>(CondVar); 01066 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 01067 if (CondResult.isInvalid()) 01068 return StmtError(); 01069 } 01070 Expr *ConditionExpr = CondResult.take(); 01071 if (!ConditionExpr) 01072 return StmtError(); 01073 01074 DiagnoseUnusedExprResult(Body); 01075 01076 if (isa<NullStmt>(Body)) 01077 getCurCompoundScope().setHasEmptyLoopBodies(); 01078 01079 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 01080 Body, WhileLoc)); 01081 } 01082 01083 StmtResult 01084 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 01085 SourceLocation WhileLoc, SourceLocation CondLParen, 01086 Expr *Cond, SourceLocation CondRParen) { 01087 assert(Cond && "ActOnDoStmt(): missing expression"); 01088 01089 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 01090 if (CondResult.isInvalid() || CondResult.isInvalid()) 01091 return StmtError(); 01092 Cond = CondResult.take(); 01093 01094 CheckImplicitConversions(Cond, DoLoc); 01095 CondResult = MaybeCreateExprWithCleanups(Cond); 01096 if (CondResult.isInvalid()) 01097 return StmtError(); 01098 Cond = CondResult.take(); 01099 01100 DiagnoseUnusedExprResult(Body); 01101 01102 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 01103 } 01104 01105 namespace { 01106 // This visitor will traverse a conditional statement and store all 01107 // the evaluated decls into a vector. Simple is set to true if none 01108 // of the excluded constructs are used. 01109 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { 01110 llvm::SmallPtrSet<VarDecl*, 8> &Decls; 01111 llvm::SmallVector<SourceRange, 10> &Ranges; 01112 bool Simple; 01113 PartialDiagnostic &PDiag; 01114 public: 01115 typedef EvaluatedExprVisitor<DeclExtractor> Inherited; 01116 01117 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, 01118 llvm::SmallVector<SourceRange, 10> &Ranges, 01119 PartialDiagnostic &PDiag) : 01120 Inherited(S.Context), 01121 Decls(Decls), 01122 Ranges(Ranges), 01123 Simple(true), 01124 PDiag(PDiag) {} 01125 01126 bool isSimple() { return Simple; } 01127 01128 // Replaces the method in EvaluatedExprVisitor. 01129 void VisitMemberExpr(MemberExpr* E) { 01130 Simple = false; 01131 } 01132 01133 // Any Stmt not whitelisted will cause the condition to be marked complex. 01134 void VisitStmt(Stmt *S) { 01135 Simple = false; 01136 } 01137 01138 void VisitBinaryOperator(BinaryOperator *E) { 01139 Visit(E->getLHS()); 01140 Visit(E->getRHS()); 01141 } 01142 01143 void VisitCastExpr(CastExpr *E) { 01144 Visit(E->getSubExpr()); 01145 } 01146 01147 void VisitUnaryOperator(UnaryOperator *E) { 01148 // Skip checking conditionals with derefernces. 01149 if (E->getOpcode() == UO_Deref) 01150 Simple = false; 01151 else 01152 Visit(E->getSubExpr()); 01153 } 01154 01155 void VisitConditionalOperator(ConditionalOperator *E) { 01156 Visit(E->getCond()); 01157 Visit(E->getTrueExpr()); 01158 Visit(E->getFalseExpr()); 01159 } 01160 01161 void VisitParenExpr(ParenExpr *E) { 01162 Visit(E->getSubExpr()); 01163 } 01164 01165 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 01166 Visit(E->getOpaqueValue()->getSourceExpr()); 01167 Visit(E->getFalseExpr()); 01168 } 01169 01170 void VisitIntegerLiteral(IntegerLiteral *E) { } 01171 void VisitFloatingLiteral(FloatingLiteral *E) { } 01172 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } 01173 void VisitCharacterLiteral(CharacterLiteral *E) { } 01174 void VisitGNUNullExpr(GNUNullExpr *E) { } 01175 void VisitImaginaryLiteral(ImaginaryLiteral *E) { } 01176 01177 void VisitDeclRefExpr(DeclRefExpr *E) { 01178 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 01179 if (!VD) return; 01180 01181 Ranges.push_back(E->getSourceRange()); 01182 01183 Decls.insert(VD); 01184 } 01185 01186 }; // end class DeclExtractor 01187 01188 // DeclMatcher checks to see if the decls are used in a non-evauluated 01189 // context. 01190 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { 01191 llvm::SmallPtrSet<VarDecl*, 8> &Decls; 01192 bool FoundDecl; 01193 //bool EvalDecl; 01194 01195 public: 01196 typedef EvaluatedExprVisitor<DeclMatcher> Inherited; 01197 01198 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) : 01199 Inherited(S.Context), Decls(Decls), FoundDecl(false) { 01200 if (!Statement) return; 01201 01202 Visit(Statement); 01203 } 01204 01205 void VisitReturnStmt(ReturnStmt *S) { 01206 FoundDecl = true; 01207 } 01208 01209 void VisitBreakStmt(BreakStmt *S) { 01210 FoundDecl = true; 01211 } 01212 01213 void VisitGotoStmt(GotoStmt *S) { 01214 FoundDecl = true; 01215 } 01216 01217 void VisitCastExpr(CastExpr *E) { 01218 if (E->getCastKind() == CK_LValueToRValue) 01219 CheckLValueToRValueCast(E->getSubExpr()); 01220 else 01221 Visit(E->getSubExpr()); 01222 } 01223 01224 void CheckLValueToRValueCast(Expr *E) { 01225 E = E->IgnoreParenImpCasts(); 01226 01227 if (isa<DeclRefExpr>(E)) { 01228 return; 01229 } 01230 01231 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 01232 Visit(CO->getCond()); 01233 CheckLValueToRValueCast(CO->getTrueExpr()); 01234 CheckLValueToRValueCast(CO->getFalseExpr()); 01235 return; 01236 } 01237 01238 if (BinaryConditionalOperator *BCO = 01239 dyn_cast<BinaryConditionalOperator>(E)) { 01240 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); 01241 CheckLValueToRValueCast(BCO->getFalseExpr()); 01242 return; 01243 } 01244 01245 Visit(E); 01246 } 01247 01248 void VisitDeclRefExpr(DeclRefExpr *E) { 01249 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 01250 if (Decls.count(VD)) 01251 FoundDecl = true; 01252 } 01253 01254 bool FoundDeclInUse() { return FoundDecl; } 01255 01256 }; // end class DeclMatcher 01257 01258 void CheckForLoopConditionalStatement(Sema &S, Expr *Second, 01259 Expr *Third, Stmt *Body) { 01260 // Condition is empty 01261 if (!Second) return; 01262 01263 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body, 01264 Second->getLocStart()) 01265 == DiagnosticsEngine::Ignored) 01266 return; 01267 01268 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); 01269 llvm::SmallPtrSet<VarDecl*, 8> Decls; 01270 llvm::SmallVector<SourceRange, 10> Ranges; 01271 DeclExtractor DE(S, Decls, Ranges, PDiag); 01272 DE.Visit(Second); 01273 01274 // Don't analyze complex conditionals. 01275 if (!DE.isSimple()) return; 01276 01277 // No decls found. 01278 if (Decls.size() == 0) return; 01279 01280 // Don't warn on volatile, static, or global variables. 01281 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(), 01282 E = Decls.end(); 01283 I != E; ++I) 01284 if ((*I)->getType().isVolatileQualified() || 01285 (*I)->hasGlobalStorage()) return; 01286 01287 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || 01288 DeclMatcher(S, Decls, Third).FoundDeclInUse() || 01289 DeclMatcher(S, Decls, Body).FoundDeclInUse()) 01290 return; 01291 01292 // Load decl names into diagnostic. 01293 if (Decls.size() > 4) 01294 PDiag << 0; 01295 else { 01296 PDiag << Decls.size(); 01297 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(), 01298 E = Decls.end(); 01299 I != E; ++I) 01300 PDiag << (*I)->getDeclName(); 01301 } 01302 01303 // Load SourceRanges into diagnostic if there is room. 01304 // Otherwise, load the SourceRange of the conditional expression. 01305 if (Ranges.size() <= PartialDiagnostic::MaxArguments) 01306 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(), 01307 E = Ranges.end(); 01308 I != E; ++I) 01309 PDiag << *I; 01310 else 01311 PDiag << Second->getSourceRange(); 01312 01313 S.Diag(Ranges.begin()->getBegin(), PDiag); 01314 } 01315 01316 } // end namespace 01317 01318 StmtResult 01319 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 01320 Stmt *First, FullExprArg second, Decl *secondVar, 01321 FullExprArg third, 01322 SourceLocation RParenLoc, Stmt *Body) { 01323 if (!getLangOpts().CPlusPlus) { 01324 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 01325 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 01326 // declare identifiers for objects having storage class 'auto' or 01327 // 'register'. 01328 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 01329 DI!=DE; ++DI) { 01330 VarDecl *VD = dyn_cast<VarDecl>(*DI); 01331 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 01332 VD = 0; 01333 if (VD == 0) 01334 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 01335 // FIXME: mark decl erroneous! 01336 } 01337 } 01338 } 01339 01340 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body); 01341 01342 ExprResult SecondResult(second.release()); 01343 VarDecl *ConditionVar = 0; 01344 if (secondVar) { 01345 ConditionVar = cast<VarDecl>(secondVar); 01346 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 01347 if (SecondResult.isInvalid()) 01348 return StmtError(); 01349 } 01350 01351 Expr *Third = third.release().takeAs<Expr>(); 01352 01353 DiagnoseUnusedExprResult(First); 01354 DiagnoseUnusedExprResult(Third); 01355 DiagnoseUnusedExprResult(Body); 01356 01357 if (isa<NullStmt>(Body)) 01358 getCurCompoundScope().setHasEmptyLoopBodies(); 01359 01360 return Owned(new (Context) ForStmt(Context, First, 01361 SecondResult.take(), ConditionVar, 01362 Third, Body, ForLoc, LParenLoc, 01363 RParenLoc)); 01364 } 01365 01366 /// In an Objective C collection iteration statement: 01367 /// for (x in y) 01368 /// x can be an arbitrary l-value expression. Bind it up as a 01369 /// full-expression. 01370 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 01371 // Reduce placeholder expressions here. Note that this rejects the 01372 // use of pseudo-object l-values in this position. 01373 ExprResult result = CheckPlaceholderExpr(E); 01374 if (result.isInvalid()) return StmtError(); 01375 E = result.take(); 01376 01377 CheckImplicitConversions(E); 01378 01379 result = MaybeCreateExprWithCleanups(E); 01380 if (result.isInvalid()) return StmtError(); 01381 01382 return Owned(static_cast<Stmt*>(result.take())); 01383 } 01384 01385 ExprResult 01386 Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 01387 assert(collection); 01388 01389 // Bail out early if we've got a type-dependent expression. 01390 if (collection->isTypeDependent()) return Owned(collection); 01391 01392 // Perform normal l-value conversion. 01393 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 01394 if (result.isInvalid()) 01395 return ExprError(); 01396 collection = result.take(); 01397 01398 // The operand needs to have object-pointer type. 01399 // TODO: should we do a contextual conversion? 01400 const ObjCObjectPointerType *pointerType = 01401 collection->getType()->getAs<ObjCObjectPointerType>(); 01402 if (!pointerType) 01403 return Diag(forLoc, diag::err_collection_expr_type) 01404 << collection->getType() << collection->getSourceRange(); 01405 01406 // Check that the operand provides 01407 // - countByEnumeratingWithState:objects:count: 01408 const ObjCObjectType *objectType = pointerType->getObjectType(); 01409 ObjCInterfaceDecl *iface = objectType->getInterface(); 01410 01411 // If we have a forward-declared type, we can't do this check. 01412 // Under ARC, it is an error not to have a forward-declared class. 01413 if (iface && 01414 RequireCompleteType(forLoc, QualType(objectType, 0), 01415 getLangOpts().ObjCAutoRefCount 01416 ? diag::err_arc_collection_forward 01417 : 0, 01418 collection)) { 01419 // Otherwise, if we have any useful type information, check that 01420 // the type declares the appropriate method. 01421 } else if (iface || !objectType->qual_empty()) { 01422 IdentifierInfo *selectorIdents[] = { 01423 &Context.Idents.get("countByEnumeratingWithState"), 01424 &Context.Idents.get("objects"), 01425 &Context.Idents.get("count") 01426 }; 01427 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 01428 01429 ObjCMethodDecl *method = 0; 01430 01431 // If there's an interface, look in both the public and private APIs. 01432 if (iface) { 01433 method = iface->lookupInstanceMethod(selector); 01434 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 01435 } 01436 01437 // Also check protocol qualifiers. 01438 if (!method) 01439 method = LookupMethodInQualifiedType(selector, pointerType, 01440 /*instance*/ true); 01441 01442 // If we didn't find it anywhere, give up. 01443 if (!method) { 01444 Diag(forLoc, diag::warn_collection_expr_type) 01445 << collection->getType() << selector << collection->getSourceRange(); 01446 } 01447 01448 // TODO: check for an incompatible signature? 01449 } 01450 01451 // Wrap up any cleanups in the expression. 01452 return Owned(MaybeCreateExprWithCleanups(collection)); 01453 } 01454 01455 StmtResult 01456 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 01457 SourceLocation LParenLoc, 01458 Stmt *First, Expr *Second, 01459 SourceLocation RParenLoc, Stmt *Body) { 01460 if (First) { 01461 QualType FirstType; 01462 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 01463 if (!DS->isSingleDecl()) 01464 return StmtError(Diag((*DS->decl_begin())->getLocation(), 01465 diag::err_toomany_element_decls)); 01466 01467 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 01468 FirstType = D->getType(); 01469 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 01470 // declare identifiers for objects having storage class 'auto' or 01471 // 'register'. 01472 if (!D->hasLocalStorage()) 01473 return StmtError(Diag(D->getLocation(), 01474 diag::err_non_variable_decl_in_for)); 01475 } else { 01476 Expr *FirstE = cast<Expr>(First); 01477 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 01478 return StmtError(Diag(First->getLocStart(), 01479 diag::err_selector_element_not_lvalue) 01480 << First->getSourceRange()); 01481 01482 FirstType = static_cast<Expr*>(First)->getType(); 01483 } 01484 if (!FirstType->isDependentType() && 01485 !FirstType->isObjCObjectPointerType() && 01486 !FirstType->isBlockPointerType()) 01487 Diag(ForLoc, diag::err_selector_element_type) 01488 << FirstType << First->getSourceRange(); 01489 } 01490 01491 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 01492 ForLoc, RParenLoc)); 01493 } 01494 01495 namespace { 01496 01497 enum BeginEndFunction { 01498 BEF_begin, 01499 BEF_end 01500 }; 01501 01502 /// Build a variable declaration for a for-range statement. 01503 static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 01504 QualType Type, const char *Name) { 01505 DeclContext *DC = SemaRef.CurContext; 01506 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 01507 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 01508 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 01509 TInfo, SC_Auto, SC_None); 01510 Decl->setImplicit(); 01511 return Decl; 01512 } 01513 01514 /// Finish building a variable declaration for a for-range statement. 01515 /// \return true if an error occurs. 01516 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 01517 SourceLocation Loc, int diag) { 01518 // Deduce the type for the iterator variable now rather than leaving it to 01519 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 01520 TypeSourceInfo *InitTSI = 0; 01521 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || 01522 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) == 01523 Sema::DAR_Failed) 01524 SemaRef.Diag(Loc, diag) << Init->getType(); 01525 if (!InitTSI) { 01526 Decl->setInvalidDecl(); 01527 return true; 01528 } 01529 Decl->setTypeSourceInfo(InitTSI); 01530 Decl->setType(InitTSI->getType()); 01531 01532 // In ARC, infer lifetime. 01533 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 01534 // we're doing the equivalent of fast iteration. 01535 if (SemaRef.getLangOpts().ObjCAutoRefCount && 01536 SemaRef.inferObjCARCLifetime(Decl)) 01537 Decl->setInvalidDecl(); 01538 01539 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 01540 /*TypeMayContainAuto=*/false); 01541 SemaRef.FinalizeDeclaration(Decl); 01542 SemaRef.CurContext->addHiddenDecl(Decl); 01543 return false; 01544 } 01545 01546 /// Produce a note indicating which begin/end function was implicitly called 01547 /// by a C++0x for-range statement. This is often not obvious from the code, 01548 /// nor from the diagnostics produced when analysing the implicit expressions 01549 /// required in a for-range statement. 01550 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 01551 BeginEndFunction BEF) { 01552 CallExpr *CE = dyn_cast<CallExpr>(E); 01553 if (!CE) 01554 return; 01555 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 01556 if (!D) 01557 return; 01558 SourceLocation Loc = D->getLocation(); 01559 01560 std::string Description; 01561 bool IsTemplate = false; 01562 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 01563 Description = SemaRef.getTemplateArgumentBindingsText( 01564 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 01565 IsTemplate = true; 01566 } 01567 01568 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 01569 << BEF << IsTemplate << Description << E->getType(); 01570 } 01571 01572 /// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 01573 /// given LookupResult is non-empty, it is assumed to describe a member which 01574 /// will be invoked. Otherwise, the function will be found via argument 01575 /// dependent lookup. 01576 static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 01577 SourceLocation Loc, 01578 VarDecl *Decl, 01579 BeginEndFunction BEF, 01580 const DeclarationNameInfo &NameInfo, 01581 LookupResult &MemberLookup, 01582 Expr *Range) { 01583 ExprResult CallExpr; 01584 if (!MemberLookup.empty()) { 01585 ExprResult MemberRef = 01586 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 01587 /*IsPtr=*/false, CXXScopeSpec(), 01588 /*TemplateKWLoc=*/SourceLocation(), 01589 /*FirstQualifierInScope=*/0, 01590 MemberLookup, 01591 /*TemplateArgs=*/0); 01592 if (MemberRef.isInvalid()) 01593 return ExprError(); 01594 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 01595 Loc, 0); 01596 if (CallExpr.isInvalid()) 01597 return ExprError(); 01598 } else { 01599 UnresolvedSet<0> FoundNames; 01600 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 01601 // std is an associated namespace. 01602 UnresolvedLookupExpr *Fn = 01603 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 01604 NestedNameSpecifierLoc(), NameInfo, 01605 /*NeedsADL=*/true, /*Overloaded=*/false, 01606 FoundNames.begin(), FoundNames.end(), 01607 /*LookInStdNamespace=*/true); 01608 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 01609 0, /*AllowTypoCorrection=*/false); 01610 if (CallExpr.isInvalid()) { 01611 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 01612 << Range->getType(); 01613 return ExprError(); 01614 } 01615 } 01616 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 01617 diag::err_for_range_iter_deduction_failure)) { 01618 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 01619 return ExprError(); 01620 } 01621 return CallExpr; 01622 } 01623 01624 } 01625 01626 /// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 01627 /// 01628 /// C++0x [stmt.ranged]: 01629 /// A range-based for statement is equivalent to 01630 /// 01631 /// { 01632 /// auto && __range = range-init; 01633 /// for ( auto __begin = begin-expr, 01634 /// __end = end-expr; 01635 /// __begin != __end; 01636 /// ++__begin ) { 01637 /// for-range-declaration = *__begin; 01638 /// statement 01639 /// } 01640 /// } 01641 /// 01642 /// The body of the loop is not available yet, since it cannot be analysed until 01643 /// we have determined the type of the for-range-declaration. 01644 StmtResult 01645 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 01646 Stmt *First, SourceLocation ColonLoc, Expr *Range, 01647 SourceLocation RParenLoc) { 01648 if (!First || !Range) 01649 return StmtError(); 01650 01651 DeclStmt *DS = dyn_cast<DeclStmt>(First); 01652 assert(DS && "first part of for range not a decl stmt"); 01653 01654 if (!DS->isSingleDecl()) { 01655 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 01656 return StmtError(); 01657 } 01658 if (DS->getSingleDecl()->isInvalidDecl()) 01659 return StmtError(); 01660 01661 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 01662 return StmtError(); 01663 01664 // Build auto && __range = range-init 01665 SourceLocation RangeLoc = Range->getLocStart(); 01666 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 01667 Context.getAutoRRefDeductType(), 01668 "__range"); 01669 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 01670 diag::err_for_range_deduction_failure)) 01671 return StmtError(); 01672 01673 // Claim the type doesn't contain auto: we've already done the checking. 01674 DeclGroupPtrTy RangeGroup = 01675 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 01676 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 01677 if (RangeDecl.isInvalid()) 01678 return StmtError(); 01679 01680 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 01681 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 01682 RParenLoc); 01683 } 01684 01685 /// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 01686 StmtResult 01687 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 01688 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 01689 Expr *Inc, Stmt *LoopVarDecl, 01690 SourceLocation RParenLoc) { 01691 Scope *S = getCurScope(); 01692 01693 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 01694 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 01695 QualType RangeVarType = RangeVar->getType(); 01696 01697 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 01698 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 01699 01700 StmtResult BeginEndDecl = BeginEnd; 01701 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 01702 01703 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 01704 SourceLocation RangeLoc = RangeVar->getLocation(); 01705 01706 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 01707 01708 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 01709 VK_LValue, ColonLoc); 01710 if (BeginRangeRef.isInvalid()) 01711 return StmtError(); 01712 01713 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 01714 VK_LValue, ColonLoc); 01715 if (EndRangeRef.isInvalid()) 01716 return StmtError(); 01717 01718 QualType AutoType = Context.getAutoDeductType(); 01719 Expr *Range = RangeVar->getInit(); 01720 if (!Range) 01721 return StmtError(); 01722 QualType RangeType = Range->getType(); 01723 01724 if (RequireCompleteType(RangeLoc, RangeType, 01725 diag::err_for_range_incomplete_type)) 01726 return StmtError(); 01727 01728 // Build auto __begin = begin-expr, __end = end-expr. 01729 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 01730 "__begin"); 01731 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 01732 "__end"); 01733 01734 // Build begin-expr and end-expr and attach to __begin and __end variables. 01735 ExprResult BeginExpr, EndExpr; 01736 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 01737 // - if _RangeT is an array type, begin-expr and end-expr are __range and 01738 // __range + __bound, respectively, where __bound is the array bound. If 01739 // _RangeT is an array of unknown size or an array of incomplete type, 01740 // the program is ill-formed; 01741 01742 // begin-expr is __range. 01743 BeginExpr = BeginRangeRef; 01744 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 01745 diag::err_for_range_iter_deduction_failure)) { 01746 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01747 return StmtError(); 01748 } 01749 01750 // Find the array bound. 01751 ExprResult BoundExpr; 01752 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 01753 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 01754 Context.getPointerDiffType(), 01755 RangeLoc)); 01756 else if (const VariableArrayType *VAT = 01757 dyn_cast<VariableArrayType>(UnqAT)) 01758 BoundExpr = VAT->getSizeExpr(); 01759 else { 01760 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 01761 // UnqAT is not incomplete and Range is not type-dependent. 01762 llvm_unreachable("Unexpected array type in for-range"); 01763 } 01764 01765 // end-expr is __range + __bound. 01766 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 01767 BoundExpr.get()); 01768 if (EndExpr.isInvalid()) 01769 return StmtError(); 01770 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 01771 diag::err_for_range_iter_deduction_failure)) { 01772 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 01773 return StmtError(); 01774 } 01775 } else { 01776 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 01777 ColonLoc); 01778 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 01779 ColonLoc); 01780 01781 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 01782 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 01783 01784 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 01785 // - if _RangeT is a class type, the unqualified-ids begin and end are 01786 // looked up in the scope of class _RangeT as if by class member access 01787 // lookup (3.4.5), and if either (or both) finds at least one 01788 // declaration, begin-expr and end-expr are __range.begin() and 01789 // __range.end(), respectively; 01790 LookupQualifiedName(BeginMemberLookup, D); 01791 LookupQualifiedName(EndMemberLookup, D); 01792 01793 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 01794 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 01795 << RangeType << BeginMemberLookup.empty(); 01796 return StmtError(); 01797 } 01798 } else { 01799 // - otherwise, begin-expr and end-expr are begin(__range) and 01800 // end(__range), respectively, where begin and end are looked up with 01801 // argument-dependent lookup (3.4.2). For the purposes of this name 01802 // lookup, namespace std is an associated namespace. 01803 } 01804 01805 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 01806 BEF_begin, BeginNameInfo, 01807 BeginMemberLookup, 01808 BeginRangeRef.get()); 01809 if (BeginExpr.isInvalid()) 01810 return StmtError(); 01811 01812 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 01813 BEF_end, EndNameInfo, 01814 EndMemberLookup, EndRangeRef.get()); 01815 if (EndExpr.isInvalid()) 01816 return StmtError(); 01817 } 01818 01819 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 01820 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 01821 if (!Context.hasSameType(BeginType, EndType)) { 01822 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 01823 << BeginType << EndType; 01824 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01825 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 01826 } 01827 01828 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 01829 // Claim the type doesn't contain auto: we've already done the checking. 01830 DeclGroupPtrTy BeginEndGroup = 01831 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 01832 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 01833 01834 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 01835 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 01836 VK_LValue, ColonLoc); 01837 if (BeginRef.isInvalid()) 01838 return StmtError(); 01839 01840 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 01841 VK_LValue, ColonLoc); 01842 if (EndRef.isInvalid()) 01843 return StmtError(); 01844 01845 // Build and check __begin != __end expression. 01846 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 01847 BeginRef.get(), EndRef.get()); 01848 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 01849 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 01850 if (NotEqExpr.isInvalid()) { 01851 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01852 if (!Context.hasSameType(BeginType, EndType)) 01853 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 01854 return StmtError(); 01855 } 01856 01857 // Build and check ++__begin expression. 01858 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 01859 VK_LValue, ColonLoc); 01860 if (BeginRef.isInvalid()) 01861 return StmtError(); 01862 01863 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 01864 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 01865 if (IncrExpr.isInvalid()) { 01866 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01867 return StmtError(); 01868 } 01869 01870 // Build and check *__begin expression. 01871 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 01872 VK_LValue, ColonLoc); 01873 if (BeginRef.isInvalid()) 01874 return StmtError(); 01875 01876 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 01877 if (DerefExpr.isInvalid()) { 01878 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01879 return StmtError(); 01880 } 01881 01882 // Attach *__begin as initializer for VD. 01883 if (!LoopVar->isInvalidDecl()) { 01884 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 01885 /*TypeMayContainAuto=*/true); 01886 if (LoopVar->isInvalidDecl()) 01887 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 01888 } 01889 } else { 01890 // The range is implicitly used as a placeholder when it is dependent. 01891 RangeVar->setUsed(); 01892 } 01893 01894 return Owned(new (Context) CXXForRangeStmt(RangeDS, 01895 cast_or_null<DeclStmt>(BeginEndDecl.get()), 01896 NotEqExpr.take(), IncrExpr.take(), 01897 LoopVarDS, /*Body=*/0, ForLoc, 01898 ColonLoc, RParenLoc)); 01899 } 01900 01901 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 01902 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the 01903 /// body cannot be performed until after the type of the range variable is 01904 /// determined. 01905 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 01906 if (!S || !B) 01907 return StmtError(); 01908 01909 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); 01910 ForStmt->setBody(B); 01911 01912 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, 01913 diag::warn_empty_range_based_for_body); 01914 01915 return S; 01916 } 01917 01918 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 01919 SourceLocation LabelLoc, 01920 LabelDecl *TheDecl) { 01921 getCurFunction()->setHasBranchIntoScope(); 01922 TheDecl->setUsed(); 01923 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 01924 } 01925 01926 StmtResult 01927 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 01928 Expr *E) { 01929 // Convert operand to void* 01930 if (!E->isTypeDependent()) { 01931 QualType ETy = E->getType(); 01932 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 01933 ExprResult ExprRes = Owned(E); 01934 AssignConvertType ConvTy = 01935 CheckSingleAssignmentConstraints(DestTy, ExprRes); 01936 if (ExprRes.isInvalid()) 01937 return StmtError(); 01938 E = ExprRes.take(); 01939 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 01940 return StmtError(); 01941 E = MaybeCreateExprWithCleanups(E); 01942 } 01943 01944 getCurFunction()->setHasIndirectGoto(); 01945 01946 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 01947 } 01948 01949 StmtResult 01950 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 01951 Scope *S = CurScope->getContinueParent(); 01952 if (!S) { 01953 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 01954 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 01955 } 01956 01957 return Owned(new (Context) ContinueStmt(ContinueLoc)); 01958 } 01959 01960 StmtResult 01961 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 01962 Scope *S = CurScope->getBreakParent(); 01963 if (!S) { 01964 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 01965 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 01966 } 01967 01968 return Owned(new (Context) BreakStmt(BreakLoc)); 01969 } 01970 01971 /// \brief Determine whether the given expression is a candidate for 01972 /// copy elision in either a return statement or a throw expression. 01973 /// 01974 /// \param ReturnType If we're determining the copy elision candidate for 01975 /// a return statement, this is the return type of the function. If we're 01976 /// determining the copy elision candidate for a throw expression, this will 01977 /// be a NULL type. 01978 /// 01979 /// \param E The expression being returned from the function or block, or 01980 /// being thrown. 01981 /// 01982 /// \param AllowFunctionParameter Whether we allow function parameters to 01983 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 01984 /// we re-use this logic to determine whether we should try to move as part of 01985 /// a return or throw (which does allow function parameters). 01986 /// 01987 /// \returns The NRVO candidate variable, if the return statement may use the 01988 /// NRVO, or NULL if there is no such candidate. 01989 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 01990 Expr *E, 01991 bool AllowFunctionParameter) { 01992 QualType ExprType = E->getType(); 01993 // - in a return statement in a function with ... 01994 // ... a class return type ... 01995 if (!ReturnType.isNull()) { 01996 if (!ReturnType->isRecordType()) 01997 return 0; 01998 // ... the same cv-unqualified type as the function return type ... 01999 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 02000 return 0; 02001 } 02002 02003 // ... the expression is the name of a non-volatile automatic object 02004 // (other than a function or catch-clause parameter)) ... 02005 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 02006 if (!DR) 02007 return 0; 02008 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 02009 if (!VD) 02010 return 0; 02011 02012 // ...object (other than a function or catch-clause parameter)... 02013 if (VD->getKind() != Decl::Var && 02014 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 02015 return 0; 02016 if (VD->isExceptionVariable()) return 0; 02017 02018 // ...automatic... 02019 if (!VD->hasLocalStorage()) return 0; 02020 02021 // ...non-volatile... 02022 if (VD->getType().isVolatileQualified()) return 0; 02023 if (VD->getType()->isReferenceType()) return 0; 02024 02025 // __block variables can't be allocated in a way that permits NRVO. 02026 if (VD->hasAttr<BlocksAttr>()) return 0; 02027 02028 // Variables with higher required alignment than their type's ABI 02029 // alignment cannot use NRVO. 02030 if (VD->hasAttr<AlignedAttr>() && 02031 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 02032 return 0; 02033 02034 return VD; 02035 } 02036 02037 /// \brief Perform the initialization of a potentially-movable value, which 02038 /// is the result of return value. 02039 /// 02040 /// This routine implements C++0x [class.copy]p33, which attempts to treat 02041 /// returned lvalues as rvalues in certain cases (to prefer move construction), 02042 /// then falls back to treating them as lvalues if that failed. 02043 ExprResult 02044 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 02045 const VarDecl *NRVOCandidate, 02046 QualType ResultType, 02047 Expr *Value, 02048 bool AllowNRVO) { 02049 // C++0x [class.copy]p33: 02050 // When the criteria for elision of a copy operation are met or would 02051 // be met save for the fact that the source object is a function 02052 // parameter, and the object to be copied is designated by an lvalue, 02053 // overload resolution to select the constructor for the copy is first 02054 // performed as if the object were designated by an rvalue. 02055 ExprResult Res = ExprError(); 02056 if (AllowNRVO && 02057 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 02058 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 02059 Value->getType(), CK_NoOp, Value, VK_XValue); 02060 02061 Expr *InitExpr = &AsRvalue; 02062 InitializationKind Kind 02063 = InitializationKind::CreateCopy(Value->getLocStart(), 02064 Value->getLocStart()); 02065 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 02066 02067 // [...] If overload resolution fails, or if the type of the first 02068 // parameter of the selected constructor is not an rvalue reference 02069 // to the object's type (possibly cv-qualified), overload resolution 02070 // is performed again, considering the object as an lvalue. 02071 if (Seq) { 02072 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 02073 StepEnd = Seq.step_end(); 02074 Step != StepEnd; ++Step) { 02075 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 02076 continue; 02077 02078 CXXConstructorDecl *Constructor 02079 = cast<CXXConstructorDecl>(Step->Function.Function); 02080 02081 const RValueReferenceType *RRefType 02082 = Constructor->getParamDecl(0)->getType() 02083 ->getAs<RValueReferenceType>(); 02084 02085 // If we don't meet the criteria, break out now. 02086 if (!RRefType || 02087 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 02088 Context.getTypeDeclType(Constructor->getParent()))) 02089 break; 02090 02091 // Promote "AsRvalue" to the heap, since we now need this 02092 // expression node to persist. 02093 Value = ImplicitCastExpr::Create(Context, Value->getType(), 02094 CK_NoOp, Value, 0, VK_XValue); 02095 02096 // Complete type-checking the initialization of the return type 02097 // using the constructor we found. 02098 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 02099 } 02100 } 02101 } 02102 02103 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 02104 // above, or overload resolution failed. Either way, we need to try 02105 // (again) now with the return value expression as written. 02106 if (Res.isInvalid()) 02107 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 02108 02109 return Res; 02110 } 02111 02112 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 02113 /// for capturing scopes. 02114 /// 02115 StmtResult 02116 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 02117 // If this is the first return we've seen, infer the return type. 02118 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those 02119 // rules which allows multiple return statements. 02120 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 02121 if (CurCap->HasImplicitReturnType) { 02122 QualType ReturnT; 02123 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 02124 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 02125 if (Result.isInvalid()) 02126 return StmtError(); 02127 RetValExp = Result.take(); 02128 02129 if (!RetValExp->isTypeDependent()) 02130 ReturnT = RetValExp->getType(); 02131 else 02132 ReturnT = Context.DependentTy; 02133 } else { 02134 if (RetValExp) { 02135 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 02136 // initializer list, because it is not an expression (even 02137 // though we represent it as one). We still deduce 'void'. 02138 Diag(ReturnLoc, diag::err_lambda_return_init_list) 02139 << RetValExp->getSourceRange(); 02140 } 02141 02142 ReturnT = Context.VoidTy; 02143 } 02144 // We require the return types to strictly match here. 02145 if (!CurCap->ReturnType.isNull() && 02146 !CurCap->ReturnType->isDependentType() && 02147 !ReturnT->isDependentType() && 02148 !Context.hasSameType(ReturnT, CurCap->ReturnType)) { 02149 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 02150 << ReturnT << CurCap->ReturnType 02151 << (getCurLambda() != 0); 02152 return StmtError(); 02153 } 02154 CurCap->ReturnType = ReturnT; 02155 } 02156 QualType FnRetType = CurCap->ReturnType; 02157 assert(!FnRetType.isNull()); 02158 02159 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 02160 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 02161 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 02162 return StmtError(); 02163 } 02164 } else { 02165 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap); 02166 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){ 02167 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 02168 return StmtError(); 02169 } 02170 } 02171 02172 // Otherwise, verify that this result type matches the previous one. We are 02173 // pickier with blocks than for normal functions because we don't have GCC 02174 // compatibility to worry about here. 02175 const VarDecl *NRVOCandidate = 0; 02176 if (FnRetType->isDependentType()) { 02177 // Delay processing for now. TODO: there are lots of dependent 02178 // types we can conclusively prove aren't void. 02179 } else if (FnRetType->isVoidType()) { 02180 if (RetValExp && !isa<InitListExpr>(RetValExp) && 02181 !(getLangOpts().CPlusPlus && 02182 (RetValExp->isTypeDependent() || 02183 RetValExp->getType()->isVoidType()))) { 02184 if (!getLangOpts().CPlusPlus && 02185 RetValExp->getType()->isVoidType()) 02186 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; 02187 else { 02188 Diag(ReturnLoc, diag::err_return_block_has_expr); 02189 RetValExp = 0; 02190 } 02191 } 02192 } else if (!RetValExp) { 02193 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 02194 } else if (!RetValExp->isTypeDependent()) { 02195 // we have a non-void block with an expression, continue checking 02196 02197 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 02198 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 02199 // function return. 02200 02201 // In C++ the return statement is handled via a copy initialization. 02202 // the C version of which boils down to CheckSingleAssignmentConstraints. 02203 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 02204 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 02205 FnRetType, 02206 NRVOCandidate != 0); 02207 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 02208 FnRetType, RetValExp); 02209 if (Res.isInvalid()) { 02210 // FIXME: Cleanup temporaries here, anyway? 02211 return StmtError(); 02212 } 02213 RetValExp = Res.take(); 02214 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 02215 } 02216 02217 if (RetValExp) { 02218 CheckImplicitConversions(RetValExp, ReturnLoc); 02219 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 02220 } 02221 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 02222 NRVOCandidate); 02223 02224 // If we need to check for the named return value optimization, save the 02225 // return statement in our scope for later processing. 02226 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 02227 !CurContext->isDependentContext()) 02228 FunctionScopes.back()->Returns.push_back(Result); 02229 02230 return Owned(Result); 02231 } 02232 02233 StmtResult 02234 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 02235 // Check for unexpanded parameter packs. 02236 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 02237 return StmtError(); 02238 02239 if (isa<CapturingScopeInfo>(getCurFunction())) 02240 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); 02241 02242 QualType FnRetType; 02243 QualType RelatedRetType; 02244 if (const FunctionDecl *FD = getCurFunctionDecl()) { 02245 FnRetType = FD->getResultType(); 02246 if (FD->hasAttr<NoReturnAttr>() || 02247 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 02248 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 02249 << FD->getDeclName(); 02250 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 02251 FnRetType = MD->getResultType(); 02252 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 02253 // In the implementation of a method with a related return type, the 02254 // type used to type-check the validity of return statements within the 02255 // method body is a pointer to the type of the class being implemented. 02256 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 02257 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); 02258 } 02259 } else // If we don't have a function/method context, bail. 02260 return StmtError(); 02261 02262 ReturnStmt *Result = 0; 02263 if (FnRetType->isVoidType()) { 02264 if (RetValExp) { 02265 if (isa<InitListExpr>(RetValExp)) { 02266 // We simply never allow init lists as the return value of void 02267 // functions. This is compatible because this was never allowed before, 02268 // so there's no legacy code to deal with. 02269 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02270 int FunctionKind = 0; 02271 if (isa<ObjCMethodDecl>(CurDecl)) 02272 FunctionKind = 1; 02273 else if (isa<CXXConstructorDecl>(CurDecl)) 02274 FunctionKind = 2; 02275 else if (isa<CXXDestructorDecl>(CurDecl)) 02276 FunctionKind = 3; 02277 02278 Diag(ReturnLoc, diag::err_return_init_list) 02279 << CurDecl->getDeclName() << FunctionKind 02280 << RetValExp->getSourceRange(); 02281 02282 // Drop the expression. 02283 RetValExp = 0; 02284 } else if (!RetValExp->isTypeDependent()) { 02285 // C99 6.8.6.4p1 (ext_ since GCC warns) 02286 unsigned D = diag::ext_return_has_expr; 02287 if (RetValExp->getType()->isVoidType()) 02288 D = diag::ext_return_has_void_expr; 02289 else { 02290 ExprResult Result = Owned(RetValExp); 02291 Result = IgnoredValueConversions(Result.take()); 02292 if (Result.isInvalid()) 02293 return StmtError(); 02294 RetValExp = Result.take(); 02295 RetValExp = ImpCastExprToType(RetValExp, 02296 Context.VoidTy, CK_ToVoid).take(); 02297 } 02298 02299 // return (some void expression); is legal in C++. 02300 if (D != diag::ext_return_has_void_expr || 02301 !getLangOpts().CPlusPlus) { 02302 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02303 02304 int FunctionKind = 0; 02305 if (isa<ObjCMethodDecl>(CurDecl)) 02306 FunctionKind = 1; 02307 else if (isa<CXXConstructorDecl>(CurDecl)) 02308 FunctionKind = 2; 02309 else if (isa<CXXDestructorDecl>(CurDecl)) 02310 FunctionKind = 3; 02311 02312 Diag(ReturnLoc, D) 02313 << CurDecl->getDeclName() << FunctionKind 02314 << RetValExp->getSourceRange(); 02315 } 02316 } 02317 02318 if (RetValExp) { 02319 CheckImplicitConversions(RetValExp, ReturnLoc); 02320 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 02321 } 02322 } 02323 02324 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 02325 } else if (!RetValExp && !FnRetType->isDependentType()) { 02326 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 02327 // C99 6.8.6.4p1 (ext_ since GCC warns) 02328 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr; 02329 02330 if (FunctionDecl *FD = getCurFunctionDecl()) 02331 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 02332 else 02333 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 02334 Result = new (Context) ReturnStmt(ReturnLoc); 02335 } else { 02336 const VarDecl *NRVOCandidate = 0; 02337 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 02338 // we have a non-void function with an expression, continue checking 02339 02340 if (!RelatedRetType.isNull()) { 02341 // If we have a related result type, perform an extra conversion here. 02342 // FIXME: The diagnostics here don't really describe what is happening. 02343 InitializedEntity Entity = 02344 InitializedEntity::InitializeTemporary(RelatedRetType); 02345 02346 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(), 02347 RetValExp); 02348 if (Res.isInvalid()) { 02349 // FIXME: Cleanup temporaries here, anyway? 02350 return StmtError(); 02351 } 02352 RetValExp = Res.takeAs<Expr>(); 02353 } 02354 02355 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 02356 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 02357 // function return. 02358 02359 // In C++ the return statement is handled via a copy initialization, 02360 // the C version of which boils down to CheckSingleAssignmentConstraints. 02361 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 02362 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 02363 FnRetType, 02364 NRVOCandidate != 0); 02365 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 02366 FnRetType, RetValExp); 02367 if (Res.isInvalid()) { 02368 // FIXME: Cleanup temporaries here, anyway? 02369 return StmtError(); 02370 } 02371 02372 RetValExp = Res.takeAs<Expr>(); 02373 if (RetValExp) 02374 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 02375 } 02376 02377 if (RetValExp) { 02378 CheckImplicitConversions(RetValExp, ReturnLoc); 02379 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 02380 } 02381 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 02382 } 02383 02384 // If we need to check for the named return value optimization, save the 02385 // return statement in our scope for later processing. 02386 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 02387 !CurContext->isDependentContext()) 02388 FunctionScopes.back()->Returns.push_back(Result); 02389 02390 return Owned(Result); 02391 } 02392 02393 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 02394 /// ignore "noop" casts in places where an lvalue is required by an inline asm. 02395 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but 02396 /// provide a strong guidance to not use it. 02397 /// 02398 /// This method checks to see if the argument is an acceptable l-value and 02399 /// returns false if it is a case we can handle. 02400 static bool CheckAsmLValue(const Expr *E, Sema &S) { 02401 // Type dependent expressions will be checked during instantiation. 02402 if (E->isTypeDependent()) 02403 return false; 02404 02405 if (E->isLValue()) 02406 return false; // Cool, this is an lvalue. 02407 02408 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 02409 // are supposed to allow. 02410 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 02411 if (E != E2 && E2->isLValue()) { 02412 if (!S.getLangOpts().HeinousExtensions) 02413 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 02414 << E->getSourceRange(); 02415 else 02416 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 02417 << E->getSourceRange(); 02418 // Accept, even if we emitted an error diagnostic. 02419 return false; 02420 } 02421 02422 // None of the above, just randomly invalid non-lvalue. 02423 return true; 02424 } 02425 02426 /// isOperandMentioned - Return true if the specified operand # is mentioned 02427 /// anywhere in the decomposed asm string. 02428 static bool isOperandMentioned(unsigned OpNo, 02429 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 02430 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 02431 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 02432 if (!Piece.isOperand()) continue; 02433 02434 // If this is a reference to the input and if the input was the smaller 02435 // one, then we have to reject this asm. 02436 if (Piece.getOperandNo() == OpNo) 02437 return true; 02438 } 02439 02440 return false; 02441 } 02442 02443 StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 02444 bool IsVolatile, unsigned NumOutputs, 02445 unsigned NumInputs, IdentifierInfo **Names, 02446 MultiExprArg constraints, MultiExprArg exprs, 02447 Expr *asmString, MultiExprArg clobbers, 02448 SourceLocation RParenLoc, bool MSAsm) { 02449 unsigned NumClobbers = clobbers.size(); 02450 StringLiteral **Constraints = 02451 reinterpret_cast<StringLiteral**>(constraints.get()); 02452 Expr **Exprs = exprs.get(); 02453 StringLiteral *AsmString = cast<StringLiteral>(asmString); 02454 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 02455 02456 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 02457 02458 // The parser verifies that there is a string literal here. 02459 if (!AsmString->isAscii()) 02460 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 02461 << AsmString->getSourceRange()); 02462 02463 for (unsigned i = 0; i != NumOutputs; i++) { 02464 StringLiteral *Literal = Constraints[i]; 02465 if (!Literal->isAscii()) 02466 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 02467 << Literal->getSourceRange()); 02468 02469 StringRef OutputName; 02470 if (Names[i]) 02471 OutputName = Names[i]->getName(); 02472 02473 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 02474 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 02475 return StmtError(Diag(Literal->getLocStart(), 02476 diag::err_asm_invalid_output_constraint) 02477 << Info.getConstraintStr()); 02478 02479 // Check that the output exprs are valid lvalues. 02480 Expr *OutputExpr = Exprs[i]; 02481 if (CheckAsmLValue(OutputExpr, *this)) { 02482 return StmtError(Diag(OutputExpr->getLocStart(), 02483 diag::err_asm_invalid_lvalue_in_output) 02484 << OutputExpr->getSourceRange()); 02485 } 02486 02487 OutputConstraintInfos.push_back(Info); 02488 } 02489 02490 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 02491 02492 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 02493 StringLiteral *Literal = Constraints[i]; 02494 if (!Literal->isAscii()) 02495 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 02496 << Literal->getSourceRange()); 02497 02498 StringRef InputName; 02499 if (Names[i]) 02500 InputName = Names[i]->getName(); 02501 02502 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 02503 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(), 02504 NumOutputs, Info)) { 02505 return StmtError(Diag(Literal->getLocStart(), 02506 diag::err_asm_invalid_input_constraint) 02507 << Info.getConstraintStr()); 02508 } 02509 02510 Expr *InputExpr = Exprs[i]; 02511 02512 // Only allow void types for memory constraints. 02513 if (Info.allowsMemory() && !Info.allowsRegister()) { 02514 if (CheckAsmLValue(InputExpr, *this)) 02515 return StmtError(Diag(InputExpr->getLocStart(), 02516 diag::err_asm_invalid_lvalue_in_input) 02517 << Info.getConstraintStr() 02518 << InputExpr->getSourceRange()); 02519 } 02520 02521 if (Info.allowsRegister()) { 02522 if (InputExpr->getType()->isVoidType()) { 02523 return StmtError(Diag(InputExpr->getLocStart(), 02524 diag::err_asm_invalid_type_in_input) 02525 << InputExpr->getType() << Info.getConstraintStr() 02526 << InputExpr->getSourceRange()); 02527 } 02528 } 02529 02530 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 02531 if (Result.isInvalid()) 02532 return StmtError(); 02533 02534 Exprs[i] = Result.take(); 02535 InputConstraintInfos.push_back(Info); 02536 } 02537 02538 // Check that the clobbers are valid. 02539 for (unsigned i = 0; i != NumClobbers; i++) { 02540 StringLiteral *Literal = Clobbers[i]; 02541 if (!Literal->isAscii()) 02542 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 02543 << Literal->getSourceRange()); 02544 02545 StringRef Clobber = Literal->getString(); 02546 02547 if (!Context.getTargetInfo().isValidClobber(Clobber)) 02548 return StmtError(Diag(Literal->getLocStart(), 02549 diag::err_asm_unknown_register_name) << Clobber); 02550 } 02551 02552 AsmStmt *NS = 02553 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 02554 NumOutputs, NumInputs, Names, Constraints, Exprs, 02555 AsmString, NumClobbers, Clobbers, RParenLoc); 02556 // Validate the asm string, ensuring it makes sense given the operands we 02557 // have. 02558 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 02559 unsigned DiagOffs; 02560 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 02561 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 02562 << AsmString->getSourceRange(); 02563 return StmtError(); 02564 } 02565 02566 // Validate tied input operands for type mismatches. 02567 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 02568 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 02569 02570 // If this is a tied constraint, verify that the output and input have 02571 // either exactly the same type, or that they are int/ptr operands with the 02572 // same size (int/long, int*/long, are ok etc). 02573 if (!Info.hasTiedOperand()) continue; 02574 02575 unsigned TiedTo = Info.getTiedOperand(); 02576 unsigned InputOpNo = i+NumOutputs; 02577 Expr *OutputExpr = Exprs[TiedTo]; 02578 Expr *InputExpr = Exprs[InputOpNo]; 02579 02580 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 02581 continue; 02582 02583 QualType InTy = InputExpr->getType(); 02584 QualType OutTy = OutputExpr->getType(); 02585 if (Context.hasSameType(InTy, OutTy)) 02586 continue; // All types can be tied to themselves. 02587 02588 // Decide if the input and output are in the same domain (integer/ptr or 02589 // floating point. 02590 enum AsmDomain { 02591 AD_Int, AD_FP, AD_Other 02592 } InputDomain, OutputDomain; 02593 02594 if (InTy->isIntegerType() || InTy->isPointerType()) 02595 InputDomain = AD_Int; 02596 else if (InTy->isRealFloatingType()) 02597 InputDomain = AD_FP; 02598 else 02599 InputDomain = AD_Other; 02600 02601 if (OutTy->isIntegerType() || OutTy->isPointerType()) 02602 OutputDomain = AD_Int; 02603 else if (OutTy->isRealFloatingType()) 02604 OutputDomain = AD_FP; 02605 else 02606 OutputDomain = AD_Other; 02607 02608 // They are ok if they are the same size and in the same domain. This 02609 // allows tying things like: 02610 // void* to int* 02611 // void* to int if they are the same size. 02612 // double to long double if they are the same size. 02613 // 02614 uint64_t OutSize = Context.getTypeSize(OutTy); 02615 uint64_t InSize = Context.getTypeSize(InTy); 02616 if (OutSize == InSize && InputDomain == OutputDomain && 02617 InputDomain != AD_Other) 02618 continue; 02619 02620 // If the smaller input/output operand is not mentioned in the asm string, 02621 // then we can promote the smaller one to a larger input and the asm string 02622 // won't notice. 02623 bool SmallerValueMentioned = false; 02624 02625 // If this is a reference to the input and if the input was the smaller 02626 // one, then we have to reject this asm. 02627 if (isOperandMentioned(InputOpNo, Pieces)) { 02628 // This is a use in the asm string of the smaller operand. Since we 02629 // codegen this by promoting to a wider value, the asm will get printed 02630 // "wrong". 02631 SmallerValueMentioned |= InSize < OutSize; 02632 } 02633 if (isOperandMentioned(TiedTo, Pieces)) { 02634 // If this is a reference to the output, and if the output is the larger 02635 // value, then it's ok because we'll promote the input to the larger type. 02636 SmallerValueMentioned |= OutSize < InSize; 02637 } 02638 02639 // If the smaller value wasn't mentioned in the asm string, and if the 02640 // output was a register, just extend the shorter one to the size of the 02641 // larger one. 02642 if (!SmallerValueMentioned && InputDomain != AD_Other && 02643 OutputConstraintInfos[TiedTo].allowsRegister()) 02644 continue; 02645 02646 // Either both of the operands were mentioned or the smaller one was 02647 // mentioned. One more special case that we'll allow: if the tied input is 02648 // integer, unmentioned, and is a constant, then we'll allow truncating it 02649 // down to the size of the destination. 02650 if (InputDomain == AD_Int && OutputDomain == AD_Int && 02651 !isOperandMentioned(InputOpNo, Pieces) && 02652 InputExpr->isEvaluatable(Context)) { 02653 CastKind castKind = 02654 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 02655 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 02656 Exprs[InputOpNo] = InputExpr; 02657 NS->setInputExpr(i, InputExpr); 02658 continue; 02659 } 02660 02661 Diag(InputExpr->getLocStart(), 02662 diag::err_asm_tying_incompatible_types) 02663 << InTy << OutTy << OutputExpr->getSourceRange() 02664 << InputExpr->getSourceRange(); 02665 return StmtError(); 02666 } 02667 02668 return Owned(NS); 02669 } 02670 02671 StmtResult 02672 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 02673 SourceLocation RParen, Decl *Parm, 02674 Stmt *Body) { 02675 VarDecl *Var = cast_or_null<VarDecl>(Parm); 02676 if (Var && Var->isInvalidDecl()) 02677 return StmtError(); 02678 02679 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 02680 } 02681 02682 StmtResult 02683 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 02684 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 02685 } 02686 02687 StmtResult 02688 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 02689 MultiStmtArg CatchStmts, Stmt *Finally) { 02690 if (!getLangOpts().ObjCExceptions) 02691 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 02692 02693 getCurFunction()->setHasBranchProtectedScope(); 02694 unsigned NumCatchStmts = CatchStmts.size(); 02695 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 02696 CatchStmts.release(), 02697 NumCatchStmts, 02698 Finally)); 02699 } 02700 02701 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { 02702 if (Throw) { 02703 ExprResult Result = DefaultLvalueConversion(Throw); 02704 if (Result.isInvalid()) 02705 return StmtError(); 02706 02707 Throw = MaybeCreateExprWithCleanups(Result.take()); 02708 QualType ThrowType = Throw->getType(); 02709 // Make sure the expression type is an ObjC pointer or "void *". 02710 if (!ThrowType->isDependentType() && 02711 !ThrowType->isObjCObjectPointerType()) { 02712 const PointerType *PT = ThrowType->getAs<PointerType>(); 02713 if (!PT || !PT->getPointeeType()->isVoidType()) 02714 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 02715 << Throw->getType() << Throw->getSourceRange()); 02716 } 02717 } 02718 02719 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 02720 } 02721 02722 StmtResult 02723 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 02724 Scope *CurScope) { 02725 if (!getLangOpts().ObjCExceptions) 02726 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 02727 02728 if (!Throw) { 02729 // @throw without an expression designates a rethrow (which much occur 02730 // in the context of an @catch clause). 02731 Scope *AtCatchParent = CurScope; 02732 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 02733 AtCatchParent = AtCatchParent->getParent(); 02734 if (!AtCatchParent) 02735 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 02736 } 02737 02738 return BuildObjCAtThrowStmt(AtLoc, Throw); 02739 } 02740 02741 ExprResult 02742 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 02743 ExprResult result = DefaultLvalueConversion(operand); 02744 if (result.isInvalid()) 02745 return ExprError(); 02746 operand = result.take(); 02747 02748 // Make sure the expression type is an ObjC pointer or "void *". 02749 QualType type = operand->getType(); 02750 if (!type->isDependentType() && 02751 !type->isObjCObjectPointerType()) { 02752 const PointerType *pointerType = type->getAs<PointerType>(); 02753 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 02754 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 02755 << type << operand->getSourceRange(); 02756 } 02757 02758 // The operand to @synchronized is a full-expression. 02759 return MaybeCreateExprWithCleanups(operand); 02760 } 02761 02762 StmtResult 02763 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 02764 Stmt *SyncBody) { 02765 // We can't jump into or indirect-jump out of a @synchronized block. 02766 getCurFunction()->setHasBranchProtectedScope(); 02767 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 02768 } 02769 02770 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 02771 /// and creates a proper catch handler from them. 02772 StmtResult 02773 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 02774 Stmt *HandlerBlock) { 02775 // There's nothing to test that ActOnExceptionDecl didn't already test. 02776 return Owned(new (Context) CXXCatchStmt(CatchLoc, 02777 cast_or_null<VarDecl>(ExDecl), 02778 HandlerBlock)); 02779 } 02780 02781 StmtResult 02782 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 02783 getCurFunction()->setHasBranchProtectedScope(); 02784 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 02785 } 02786 02787 namespace { 02788 02789 class TypeWithHandler { 02790 QualType t; 02791 CXXCatchStmt *stmt; 02792 public: 02793 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 02794 : t(type), stmt(statement) {} 02795 02796 // An arbitrary order is fine as long as it places identical 02797 // types next to each other. 02798 bool operator<(const TypeWithHandler &y) const { 02799 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 02800 return true; 02801 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 02802 return false; 02803 else 02804 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 02805 } 02806 02807 bool operator==(const TypeWithHandler& other) const { 02808 return t == other.t; 02809 } 02810 02811 CXXCatchStmt *getCatchStmt() const { return stmt; } 02812 SourceLocation getTypeSpecStartLoc() const { 02813 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 02814 } 02815 }; 02816 02817 } 02818 02819 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of 02820 /// handlers and creates a try statement from them. 02821 StmtResult 02822 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 02823 MultiStmtArg RawHandlers) { 02824 // Don't report an error if 'try' is used in system headers. 02825 if (!getLangOpts().CXXExceptions && 02826 !getSourceManager().isInSystemHeader(TryLoc)) 02827 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 02828 02829 unsigned NumHandlers = RawHandlers.size(); 02830 assert(NumHandlers > 0 && 02831 "The parser shouldn't call this if there are no handlers."); 02832 Stmt **Handlers = RawHandlers.get(); 02833 02834 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 02835 02836 for (unsigned i = 0; i < NumHandlers; ++i) { 02837 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 02838 if (!Handler->getExceptionDecl()) { 02839 if (i < NumHandlers - 1) 02840 return StmtError(Diag(Handler->getLocStart(), 02841 diag::err_early_catch_all)); 02842 02843 continue; 02844 } 02845 02846 const QualType CaughtType = Handler->getCaughtType(); 02847 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 02848 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 02849 } 02850 02851 // Detect handlers for the same type as an earlier one. 02852 if (NumHandlers > 1) { 02853 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 02854 02855 TypeWithHandler prev = TypesWithHandlers[0]; 02856 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 02857 TypeWithHandler curr = TypesWithHandlers[i]; 02858 02859 if (curr == prev) { 02860 Diag(curr.getTypeSpecStartLoc(), 02861 diag::warn_exception_caught_by_earlier_handler) 02862 << curr.getCatchStmt()->getCaughtType().getAsString(); 02863 Diag(prev.getTypeSpecStartLoc(), 02864 diag::note_previous_exception_handler) 02865 << prev.getCatchStmt()->getCaughtType().getAsString(); 02866 } 02867 02868 prev = curr; 02869 } 02870 } 02871 02872 getCurFunction()->setHasBranchProtectedScope(); 02873 02874 // FIXME: We should detect handlers that cannot catch anything because an 02875 // earlier handler catches a superclass. Need to find a method that is not 02876 // quadratic for this. 02877 // Neither of these are explicitly forbidden, but every compiler detects them 02878 // and warns. 02879 02880 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 02881 Handlers, NumHandlers)); 02882 } 02883 02884 StmtResult 02885 Sema::ActOnSEHTryBlock(bool IsCXXTry, 02886 SourceLocation TryLoc, 02887 Stmt *TryBlock, 02888 Stmt *Handler) { 02889 assert(TryBlock && Handler); 02890 02891 getCurFunction()->setHasBranchProtectedScope(); 02892 02893 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 02894 } 02895 02896 StmtResult 02897 Sema::ActOnSEHExceptBlock(SourceLocation Loc, 02898 Expr *FilterExpr, 02899 Stmt *Block) { 02900 assert(FilterExpr && Block); 02901 02902 if(!FilterExpr->getType()->isIntegerType()) { 02903 return StmtError(Diag(FilterExpr->getExprLoc(), 02904 diag::err_filter_expression_integral) 02905 << FilterExpr->getType()); 02906 } 02907 02908 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 02909 } 02910 02911 StmtResult 02912 Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 02913 Stmt *Block) { 02914 assert(Block); 02915 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 02916 } 02917 02918 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 02919 bool IsIfExists, 02920 NestedNameSpecifierLoc QualifierLoc, 02921 DeclarationNameInfo NameInfo, 02922 Stmt *Nested) 02923 { 02924 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 02925 QualifierLoc, NameInfo, 02926 cast<CompoundStmt>(Nested)); 02927 } 02928 02929 02930 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 02931 bool IsIfExists, 02932 CXXScopeSpec &SS, 02933 UnqualifiedId &Name, 02934 Stmt *Nested) { 02935 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 02936 SS.getWithLocInContext(Context), 02937 GetNameFromUnqualifiedId(Name), 02938 Nested); 02939 }