SemaStmt.cpp revision 39e6ab4be93d9c5e729a578ddd9d415cd2d49872
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for statements. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/ASTDiagnostic.h" 17#include "clang/AST/CharUnits.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/EvaluatedExprVisitor.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/ExprObjC.h" 22#include "clang/AST/StmtCXX.h" 23#include "clang/AST/StmtObjC.h" 24#include "clang/AST/TypeLoc.h" 25#include "clang/Basic/TargetInfo.h" 26#include "clang/Lex/Preprocessor.h" 27#include "clang/Sema/Initialization.h" 28#include "clang/Sema/Lookup.h" 29#include "clang/Sema/Scope.h" 30#include "clang/Sema/ScopeInfo.h" 31#include "llvm/ADT/ArrayRef.h" 32#include "llvm/ADT/STLExtras.h" 33#include "llvm/ADT/SmallPtrSet.h" 34#include "llvm/ADT/SmallString.h" 35#include "llvm/ADT/SmallVector.h" 36using namespace clang; 37using namespace sema; 38 39StmtResult Sema::ActOnExprStmt(ExprResult FE) { 40 if (FE.isInvalid()) 41 return StmtError(); 42 43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), 44 /*DiscardedValue*/ true); 45 if (FE.isInvalid()) 46 return StmtError(); 47 48 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 49 // void expression for its side effects. Conversion to void allows any 50 // operand, even incomplete types. 51 52 // Same thing in for stmt first clause (when expr) and third clause. 53 return Owned(static_cast<Stmt*>(FE.take())); 54} 55 56 57StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 58 bool HasLeadingEmptyMacro) { 59 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro)); 60} 61 62StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 63 SourceLocation EndLoc) { 64 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 65 66 // If we have an invalid decl, just return an error. 67 if (DG.isNull()) return StmtError(); 68 69 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 70} 71 72void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 73 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 74 75 // If we have an invalid decl, just return. 76 if (DG.isNull() || !DG.isSingleDecl()) return; 77 VarDecl *var = cast<VarDecl>(DG.getSingleDecl()); 78 79 // suppress any potential 'unused variable' warning. 80 var->setUsed(); 81 82 // foreach variables are never actually initialized in the way that 83 // the parser came up with. 84 var->setInit(0); 85 86 // In ARC, we don't need to retain the iteration variable of a fast 87 // enumeration loop. Rather than actually trying to catch that 88 // during declaration processing, we remove the consequences here. 89 if (getLangOpts().ObjCAutoRefCount) { 90 QualType type = var->getType(); 91 92 // Only do this if we inferred the lifetime. Inferred lifetime 93 // will show up as a local qualifier because explicit lifetime 94 // should have shown up as an AttributedType instead. 95 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 96 // Add 'const' and mark the variable as pseudo-strong. 97 var->setType(type.withConst()); 98 var->setARCPseudoStrong(true); 99 } 100 } 101} 102 103/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='. 104/// 105/// Adding a cast to void (or other expression wrappers) will prevent the 106/// warning from firing. 107static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 108 SourceLocation Loc; 109 bool IsNotEqual, CanAssign; 110 111 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 112 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE) 113 return false; 114 115 Loc = Op->getOperatorLoc(); 116 IsNotEqual = Op->getOpcode() == BO_NE; 117 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 118 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 119 if (Op->getOperator() != OO_EqualEqual && 120 Op->getOperator() != OO_ExclaimEqual) 121 return false; 122 123 Loc = Op->getOperatorLoc(); 124 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 125 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 126 } else { 127 // Not a typo-prone comparison. 128 return false; 129 } 130 131 // Suppress warnings when the operator, suspicious as it may be, comes from 132 // a macro expansion. 133 if (S.SourceMgr.isMacroBodyExpansion(Loc)) 134 return false; 135 136 S.Diag(Loc, diag::warn_unused_comparison) 137 << (unsigned)IsNotEqual << E->getSourceRange(); 138 139 // If the LHS is a plausible entity to assign to, provide a fixit hint to 140 // correct common typos. 141 if (CanAssign) { 142 if (IsNotEqual) 143 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 144 << FixItHint::CreateReplacement(Loc, "|="); 145 else 146 S.Diag(Loc, diag::note_equality_comparison_to_assign) 147 << FixItHint::CreateReplacement(Loc, "="); 148 } 149 150 return true; 151} 152 153void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 154 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 155 return DiagnoseUnusedExprResult(Label->getSubStmt()); 156 157 const Expr *E = dyn_cast_or_null<Expr>(S); 158 if (!E) 159 return; 160 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc(); 161 if (SourceMgr.isInSystemMacro(ExprLoc) || 162 SourceMgr.isMacroBodyExpansion(ExprLoc)) 163 return; 164 165 const Expr *WarnExpr; 166 SourceLocation Loc; 167 SourceRange R1, R2; 168 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context)) 169 return; 170 171 // If this is a GNU statement expression expanded from a macro, it is probably 172 // unused because it is a function-like macro that can be used as either an 173 // expression or statement. Don't warn, because it is almost certainly a 174 // false positive. 175 if (isa<StmtExpr>(E) && Loc.isMacroID()) 176 return; 177 178 // Okay, we have an unused result. Depending on what the base expression is, 179 // we might want to make a more specific diagnostic. Check for one of these 180 // cases now. 181 unsigned DiagID = diag::warn_unused_expr; 182 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 183 E = Temps->getSubExpr(); 184 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 185 E = TempExpr->getSubExpr(); 186 187 if (DiagnoseUnusedComparison(*this, E)) 188 return; 189 190 E = WarnExpr; 191 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 192 if (E->getType()->isVoidType()) 193 return; 194 195 // If the callee has attribute pure, const, or warn_unused_result, warn with 196 // a more specific message to make it clear what is happening. 197 if (const Decl *FD = CE->getCalleeDecl()) { 198 if (FD->getAttr<WarnUnusedResultAttr>()) { 199 Diag(Loc, diag::warn_unused_result) << R1 << R2; 200 return; 201 } 202 if (FD->getAttr<PureAttr>()) { 203 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 204 return; 205 } 206 if (FD->getAttr<ConstAttr>()) { 207 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 208 return; 209 } 210 } 211 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 212 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { 213 Diag(Loc, diag::err_arc_unused_init_message) << R1; 214 return; 215 } 216 const ObjCMethodDecl *MD = ME->getMethodDecl(); 217 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 218 Diag(Loc, diag::warn_unused_result) << R1 << R2; 219 return; 220 } 221 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 222 const Expr *Source = POE->getSyntacticForm(); 223 if (isa<ObjCSubscriptRefExpr>(Source)) 224 DiagID = diag::warn_unused_container_subscript_expr; 225 else 226 DiagID = diag::warn_unused_property_expr; 227 } else if (const CXXFunctionalCastExpr *FC 228 = dyn_cast<CXXFunctionalCastExpr>(E)) { 229 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 230 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 231 return; 232 } 233 // Diagnose "(void*) blah" as a typo for "(void) blah". 234 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 235 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 236 QualType T = TI->getType(); 237 238 // We really do want to use the non-canonical type here. 239 if (T == Context.VoidPtrTy) { 240 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>(); 241 242 Diag(Loc, diag::warn_unused_voidptr) 243 << FixItHint::CreateRemoval(TL.getStarLoc()); 244 return; 245 } 246 } 247 248 if (E->isGLValue() && E->getType().isVolatileQualified()) { 249 Diag(Loc, diag::warn_unused_volatile) << R1 << R2; 250 return; 251 } 252 253 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 254} 255 256void Sema::ActOnStartOfCompoundStmt() { 257 PushCompoundScope(); 258} 259 260void Sema::ActOnFinishOfCompoundStmt() { 261 PopCompoundScope(); 262} 263 264sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { 265 return getCurFunction()->CompoundScopes.back(); 266} 267 268StmtResult 269Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 270 MultiStmtArg elts, bool isStmtExpr) { 271 unsigned NumElts = elts.size(); 272 Stmt **Elts = elts.data(); 273 // If we're in C89 mode, check that we don't have any decls after stmts. If 274 // so, emit an extension diagnostic. 275 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { 276 // Note that __extension__ can be around a decl. 277 unsigned i = 0; 278 // Skip over all declarations. 279 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 280 /*empty*/; 281 282 // We found the end of the list or a statement. Scan for another declstmt. 283 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 284 /*empty*/; 285 286 if (i != NumElts) { 287 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 288 Diag(D->getLocation(), diag::ext_mixed_decls_code); 289 } 290 } 291 // Warn about unused expressions in statements. 292 for (unsigned i = 0; i != NumElts; ++i) { 293 // Ignore statements that are last in a statement expression. 294 if (isStmtExpr && i == NumElts - 1) 295 continue; 296 297 DiagnoseUnusedExprResult(Elts[i]); 298 } 299 300 // Check for suspicious empty body (null statement) in `for' and `while' 301 // statements. Don't do anything for template instantiations, this just adds 302 // noise. 303 if (NumElts != 0 && !CurrentInstantiationScope && 304 getCurCompoundScope().HasEmptyLoopBodies) { 305 for (unsigned i = 0; i != NumElts - 1; ++i) 306 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); 307 } 308 309 return Owned(new (Context) CompoundStmt(Context, 310 llvm::makeArrayRef(Elts, NumElts), 311 L, R)); 312} 313 314StmtResult 315Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 316 SourceLocation DotDotDotLoc, Expr *RHSVal, 317 SourceLocation ColonLoc) { 318 assert((LHSVal != 0) && "missing expression in case statement"); 319 320 if (getCurFunction()->SwitchStack.empty()) { 321 Diag(CaseLoc, diag::err_case_not_in_switch); 322 return StmtError(); 323 } 324 325 if (!getLangOpts().CPlusPlus11) { 326 // C99 6.8.4.2p3: The expression shall be an integer constant. 327 // However, GCC allows any evaluatable integer expression. 328 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) { 329 LHSVal = VerifyIntegerConstantExpression(LHSVal).take(); 330 if (!LHSVal) 331 return StmtError(); 332 } 333 334 // GCC extension: The expression shall be an integer constant. 335 336 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) { 337 RHSVal = VerifyIntegerConstantExpression(RHSVal).take(); 338 // Recover from an error by just forgetting about it. 339 } 340 } 341 342 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false, 343 getLangOpts().CPlusPlus11).take(); 344 if (RHSVal) 345 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false, 346 getLangOpts().CPlusPlus11).take(); 347 348 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 349 ColonLoc); 350 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 351 return Owned(CS); 352} 353 354/// ActOnCaseStmtBody - This installs a statement as the body of a case. 355void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 356 DiagnoseUnusedExprResult(SubStmt); 357 358 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 359 CS->setSubStmt(SubStmt); 360} 361 362StmtResult 363Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 364 Stmt *SubStmt, Scope *CurScope) { 365 DiagnoseUnusedExprResult(SubStmt); 366 367 if (getCurFunction()->SwitchStack.empty()) { 368 Diag(DefaultLoc, diag::err_default_not_in_switch); 369 return Owned(SubStmt); 370 } 371 372 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 373 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 374 return Owned(DS); 375} 376 377StmtResult 378Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 379 SourceLocation ColonLoc, Stmt *SubStmt) { 380 // If the label was multiply defined, reject it now. 381 if (TheDecl->getStmt()) { 382 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 383 Diag(TheDecl->getLocation(), diag::note_previous_definition); 384 return Owned(SubStmt); 385 } 386 387 // Otherwise, things are good. Fill in the declaration and return it. 388 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 389 TheDecl->setStmt(LS); 390 if (!TheDecl->isGnuLocal()) { 391 TheDecl->setLocStart(IdentLoc); 392 TheDecl->setLocation(IdentLoc); 393 } 394 return Owned(LS); 395} 396 397StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc, 398 ArrayRef<const Attr*> Attrs, 399 Stmt *SubStmt) { 400 // Fill in the declaration and return it. 401 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt); 402 return Owned(LS); 403} 404 405StmtResult 406Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 407 Stmt *thenStmt, SourceLocation ElseLoc, 408 Stmt *elseStmt) { 409 // If the condition was invalid, discard the if statement. We could recover 410 // better by replacing it with a valid expr, but don't do that yet. 411 if (!CondVal.get() && !CondVar) { 412 getCurFunction()->setHasDroppedStmt(); 413 return StmtError(); 414 } 415 416 ExprResult CondResult(CondVal.release()); 417 418 VarDecl *ConditionVar = 0; 419 if (CondVar) { 420 ConditionVar = cast<VarDecl>(CondVar); 421 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 422 if (CondResult.isInvalid()) 423 return StmtError(); 424 } 425 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 426 if (!ConditionExpr) 427 return StmtError(); 428 429 DiagnoseUnusedExprResult(thenStmt); 430 431 if (!elseStmt) { 432 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt, 433 diag::warn_empty_if_body); 434 } 435 436 DiagnoseUnusedExprResult(elseStmt); 437 438 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 439 thenStmt, ElseLoc, elseStmt)); 440} 441 442/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 443/// the specified width and sign. If an overflow occurs, detect it and emit 444/// the specified diagnostic. 445void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 446 unsigned NewWidth, bool NewSign, 447 SourceLocation Loc, 448 unsigned DiagID) { 449 // Perform a conversion to the promoted condition type if needed. 450 if (NewWidth > Val.getBitWidth()) { 451 // If this is an extension, just do it. 452 Val = Val.extend(NewWidth); 453 Val.setIsSigned(NewSign); 454 455 // If the input was signed and negative and the output is 456 // unsigned, don't bother to warn: this is implementation-defined 457 // behavior. 458 // FIXME: Introduce a second, default-ignored warning for this case? 459 } else if (NewWidth < Val.getBitWidth()) { 460 // If this is a truncation, check for overflow. 461 llvm::APSInt ConvVal(Val); 462 ConvVal = ConvVal.trunc(NewWidth); 463 ConvVal.setIsSigned(NewSign); 464 ConvVal = ConvVal.extend(Val.getBitWidth()); 465 ConvVal.setIsSigned(Val.isSigned()); 466 if (ConvVal != Val) 467 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 468 469 // Regardless of whether a diagnostic was emitted, really do the 470 // truncation. 471 Val = Val.trunc(NewWidth); 472 Val.setIsSigned(NewSign); 473 } else if (NewSign != Val.isSigned()) { 474 // Convert the sign to match the sign of the condition. This can cause 475 // overflow as well: unsigned(INTMIN) 476 // We don't diagnose this overflow, because it is implementation-defined 477 // behavior. 478 // FIXME: Introduce a second, default-ignored warning for this case? 479 llvm::APSInt OldVal(Val); 480 Val.setIsSigned(NewSign); 481 } 482} 483 484namespace { 485 struct CaseCompareFunctor { 486 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 487 const llvm::APSInt &RHS) { 488 return LHS.first < RHS; 489 } 490 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 491 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 492 return LHS.first < RHS.first; 493 } 494 bool operator()(const llvm::APSInt &LHS, 495 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 496 return LHS < RHS.first; 497 } 498 }; 499} 500 501/// CmpCaseVals - Comparison predicate for sorting case values. 502/// 503static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 504 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 505 if (lhs.first < rhs.first) 506 return true; 507 508 if (lhs.first == rhs.first && 509 lhs.second->getCaseLoc().getRawEncoding() 510 < rhs.second->getCaseLoc().getRawEncoding()) 511 return true; 512 return false; 513} 514 515/// CmpEnumVals - Comparison predicate for sorting enumeration values. 516/// 517static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 518 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 519{ 520 return lhs.first < rhs.first; 521} 522 523/// EqEnumVals - Comparison preficate for uniqing enumeration values. 524/// 525static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 526 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 527{ 528 return lhs.first == rhs.first; 529} 530 531/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 532/// potentially integral-promoted expression @p expr. 533static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 534 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 535 expr = cleanups->getSubExpr(); 536 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 537 if (impcast->getCastKind() != CK_IntegralCast) break; 538 expr = impcast->getSubExpr(); 539 } 540 return expr->getType(); 541} 542 543StmtResult 544Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 545 Decl *CondVar) { 546 ExprResult CondResult; 547 548 VarDecl *ConditionVar = 0; 549 if (CondVar) { 550 ConditionVar = cast<VarDecl>(CondVar); 551 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 552 if (CondResult.isInvalid()) 553 return StmtError(); 554 555 Cond = CondResult.release(); 556 } 557 558 if (!Cond) 559 return StmtError(); 560 561 class SwitchConvertDiagnoser : public ICEConvertDiagnoser { 562 Expr *Cond; 563 564 public: 565 SwitchConvertDiagnoser(Expr *Cond) 566 : ICEConvertDiagnoser(false, true), Cond(Cond) { } 567 568 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 569 QualType T) { 570 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; 571 } 572 573 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 574 QualType T) { 575 return S.Diag(Loc, diag::err_switch_incomplete_class_type) 576 << T << Cond->getSourceRange(); 577 } 578 579 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 580 QualType T, 581 QualType ConvTy) { 582 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; 583 } 584 585 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 586 QualType ConvTy) { 587 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 588 << ConvTy->isEnumeralType() << ConvTy; 589 } 590 591 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 592 QualType T) { 593 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; 594 } 595 596 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 597 QualType ConvTy) { 598 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 599 << ConvTy->isEnumeralType() << ConvTy; 600 } 601 602 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 603 QualType T, 604 QualType ConvTy) { 605 return DiagnosticBuilder::getEmpty(); 606 } 607 } SwitchDiagnoser(Cond); 608 609 CondResult 610 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser, 611 /*AllowScopedEnumerations*/ true); 612 if (CondResult.isInvalid()) return StmtError(); 613 Cond = CondResult.take(); 614 615 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 616 CondResult = UsualUnaryConversions(Cond); 617 if (CondResult.isInvalid()) return StmtError(); 618 Cond = CondResult.take(); 619 620 if (!CondVar) { 621 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc); 622 if (CondResult.isInvalid()) 623 return StmtError(); 624 Cond = CondResult.take(); 625 } 626 627 getCurFunction()->setHasBranchIntoScope(); 628 629 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 630 getCurFunction()->SwitchStack.push_back(SS); 631 return Owned(SS); 632} 633 634static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 635 if (Val.getBitWidth() < BitWidth) 636 Val = Val.extend(BitWidth); 637 else if (Val.getBitWidth() > BitWidth) 638 Val = Val.trunc(BitWidth); 639 Val.setIsSigned(IsSigned); 640} 641 642StmtResult 643Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 644 Stmt *BodyStmt) { 645 SwitchStmt *SS = cast<SwitchStmt>(Switch); 646 assert(SS == getCurFunction()->SwitchStack.back() && 647 "switch stack missing push/pop!"); 648 649 SS->setBody(BodyStmt, SwitchLoc); 650 getCurFunction()->SwitchStack.pop_back(); 651 652 Expr *CondExpr = SS->getCond(); 653 if (!CondExpr) return StmtError(); 654 655 QualType CondType = CondExpr->getType(); 656 657 Expr *CondExprBeforePromotion = CondExpr; 658 QualType CondTypeBeforePromotion = 659 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 660 661 // C++ 6.4.2.p2: 662 // Integral promotions are performed (on the switch condition). 663 // 664 // A case value unrepresentable by the original switch condition 665 // type (before the promotion) doesn't make sense, even when it can 666 // be represented by the promoted type. Therefore we need to find 667 // the pre-promotion type of the switch condition. 668 if (!CondExpr->isTypeDependent()) { 669 // We have already converted the expression to an integral or enumeration 670 // type, when we started the switch statement. If we don't have an 671 // appropriate type now, just return an error. 672 if (!CondType->isIntegralOrEnumerationType()) 673 return StmtError(); 674 675 if (CondExpr->isKnownToHaveBooleanValue()) { 676 // switch(bool_expr) {...} is often a programmer error, e.g. 677 // switch(n && mask) { ... } // Doh - should be "n & mask". 678 // One can always use an if statement instead of switch(bool_expr). 679 Diag(SwitchLoc, diag::warn_bool_switch_condition) 680 << CondExpr->getSourceRange(); 681 } 682 } 683 684 // Get the bitwidth of the switched-on value before promotions. We must 685 // convert the integer case values to this width before comparison. 686 bool HasDependentValue 687 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 688 unsigned CondWidth 689 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 690 bool CondIsSigned 691 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 692 693 // Accumulate all of the case values in a vector so that we can sort them 694 // and detect duplicates. This vector contains the APInt for the case after 695 // it has been converted to the condition type. 696 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 697 CaseValsTy CaseVals; 698 699 // Keep track of any GNU case ranges we see. The APSInt is the low value. 700 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 701 CaseRangesTy CaseRanges; 702 703 DefaultStmt *TheDefaultStmt = 0; 704 705 bool CaseListIsErroneous = false; 706 707 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 708 SC = SC->getNextSwitchCase()) { 709 710 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 711 if (TheDefaultStmt) { 712 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 713 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 714 715 // FIXME: Remove the default statement from the switch block so that 716 // we'll return a valid AST. This requires recursing down the AST and 717 // finding it, not something we are set up to do right now. For now, 718 // just lop the entire switch stmt out of the AST. 719 CaseListIsErroneous = true; 720 } 721 TheDefaultStmt = DS; 722 723 } else { 724 CaseStmt *CS = cast<CaseStmt>(SC); 725 726 Expr *Lo = CS->getLHS(); 727 728 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 729 HasDependentValue = true; 730 break; 731 } 732 733 llvm::APSInt LoVal; 734 735 if (getLangOpts().CPlusPlus11) { 736 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 737 // constant expression of the promoted type of the switch condition. 738 ExprResult ConvLo = 739 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue); 740 if (ConvLo.isInvalid()) { 741 CaseListIsErroneous = true; 742 continue; 743 } 744 Lo = ConvLo.take(); 745 } else { 746 // We already verified that the expression has a i-c-e value (C99 747 // 6.8.4.2p3) - get that value now. 748 LoVal = Lo->EvaluateKnownConstInt(Context); 749 750 // If the LHS is not the same type as the condition, insert an implicit 751 // cast. 752 Lo = DefaultLvalueConversion(Lo).take(); 753 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 754 } 755 756 // Convert the value to the same width/sign as the condition had prior to 757 // integral promotions. 758 // 759 // FIXME: This causes us to reject valid code: 760 // switch ((char)c) { case 256: case 0: return 0; } 761 // Here we claim there is a duplicated condition value, but there is not. 762 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 763 Lo->getLocStart(), 764 diag::warn_case_value_overflow); 765 766 CS->setLHS(Lo); 767 768 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 769 if (CS->getRHS()) { 770 if (CS->getRHS()->isTypeDependent() || 771 CS->getRHS()->isValueDependent()) { 772 HasDependentValue = true; 773 break; 774 } 775 CaseRanges.push_back(std::make_pair(LoVal, CS)); 776 } else 777 CaseVals.push_back(std::make_pair(LoVal, CS)); 778 } 779 } 780 781 if (!HasDependentValue) { 782 // If we don't have a default statement, check whether the 783 // condition is constant. 784 llvm::APSInt ConstantCondValue; 785 bool HasConstantCond = false; 786 if (!HasDependentValue && !TheDefaultStmt) { 787 HasConstantCond 788 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context, 789 Expr::SE_AllowSideEffects); 790 assert(!HasConstantCond || 791 (ConstantCondValue.getBitWidth() == CondWidth && 792 ConstantCondValue.isSigned() == CondIsSigned)); 793 } 794 bool ShouldCheckConstantCond = HasConstantCond; 795 796 // Sort all the scalar case values so we can easily detect duplicates. 797 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 798 799 if (!CaseVals.empty()) { 800 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 801 if (ShouldCheckConstantCond && 802 CaseVals[i].first == ConstantCondValue) 803 ShouldCheckConstantCond = false; 804 805 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 806 // If we have a duplicate, report it. 807 // First, determine if either case value has a name 808 StringRef PrevString, CurrString; 809 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); 810 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); 811 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { 812 PrevString = DeclRef->getDecl()->getName(); 813 } 814 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { 815 CurrString = DeclRef->getDecl()->getName(); 816 } 817 SmallString<16> CaseValStr; 818 CaseVals[i-1].first.toString(CaseValStr); 819 820 if (PrevString == CurrString) 821 Diag(CaseVals[i].second->getLHS()->getLocStart(), 822 diag::err_duplicate_case) << 823 (PrevString.empty() ? CaseValStr.str() : PrevString); 824 else 825 Diag(CaseVals[i].second->getLHS()->getLocStart(), 826 diag::err_duplicate_case_differing_expr) << 827 (PrevString.empty() ? CaseValStr.str() : PrevString) << 828 (CurrString.empty() ? CaseValStr.str() : CurrString) << 829 CaseValStr; 830 831 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 832 diag::note_duplicate_case_prev); 833 // FIXME: We really want to remove the bogus case stmt from the 834 // substmt, but we have no way to do this right now. 835 CaseListIsErroneous = true; 836 } 837 } 838 } 839 840 // Detect duplicate case ranges, which usually don't exist at all in 841 // the first place. 842 if (!CaseRanges.empty()) { 843 // Sort all the case ranges by their low value so we can easily detect 844 // overlaps between ranges. 845 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 846 847 // Scan the ranges, computing the high values and removing empty ranges. 848 std::vector<llvm::APSInt> HiVals; 849 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 850 llvm::APSInt &LoVal = CaseRanges[i].first; 851 CaseStmt *CR = CaseRanges[i].second; 852 Expr *Hi = CR->getRHS(); 853 llvm::APSInt HiVal; 854 855 if (getLangOpts().CPlusPlus11) { 856 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 857 // constant expression of the promoted type of the switch condition. 858 ExprResult ConvHi = 859 CheckConvertedConstantExpression(Hi, CondType, HiVal, 860 CCEK_CaseValue); 861 if (ConvHi.isInvalid()) { 862 CaseListIsErroneous = true; 863 continue; 864 } 865 Hi = ConvHi.take(); 866 } else { 867 HiVal = Hi->EvaluateKnownConstInt(Context); 868 869 // If the RHS is not the same type as the condition, insert an 870 // implicit cast. 871 Hi = DefaultLvalueConversion(Hi).take(); 872 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 873 } 874 875 // Convert the value to the same width/sign as the condition. 876 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 877 Hi->getLocStart(), 878 diag::warn_case_value_overflow); 879 880 CR->setRHS(Hi); 881 882 // If the low value is bigger than the high value, the case is empty. 883 if (LoVal > HiVal) { 884 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 885 << SourceRange(CR->getLHS()->getLocStart(), 886 Hi->getLocEnd()); 887 CaseRanges.erase(CaseRanges.begin()+i); 888 --i, --e; 889 continue; 890 } 891 892 if (ShouldCheckConstantCond && 893 LoVal <= ConstantCondValue && 894 ConstantCondValue <= HiVal) 895 ShouldCheckConstantCond = false; 896 897 HiVals.push_back(HiVal); 898 } 899 900 // Rescan the ranges, looking for overlap with singleton values and other 901 // ranges. Since the range list is sorted, we only need to compare case 902 // ranges with their neighbors. 903 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 904 llvm::APSInt &CRLo = CaseRanges[i].first; 905 llvm::APSInt &CRHi = HiVals[i]; 906 CaseStmt *CR = CaseRanges[i].second; 907 908 // Check to see whether the case range overlaps with any 909 // singleton cases. 910 CaseStmt *OverlapStmt = 0; 911 llvm::APSInt OverlapVal(32); 912 913 // Find the smallest value >= the lower bound. If I is in the 914 // case range, then we have overlap. 915 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 916 CaseVals.end(), CRLo, 917 CaseCompareFunctor()); 918 if (I != CaseVals.end() && I->first < CRHi) { 919 OverlapVal = I->first; // Found overlap with scalar. 920 OverlapStmt = I->second; 921 } 922 923 // Find the smallest value bigger than the upper bound. 924 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 925 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 926 OverlapVal = (I-1)->first; // Found overlap with scalar. 927 OverlapStmt = (I-1)->second; 928 } 929 930 // Check to see if this case stmt overlaps with the subsequent 931 // case range. 932 if (i && CRLo <= HiVals[i-1]) { 933 OverlapVal = HiVals[i-1]; // Found overlap with range. 934 OverlapStmt = CaseRanges[i-1].second; 935 } 936 937 if (OverlapStmt) { 938 // If we have a duplicate, report it. 939 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 940 << OverlapVal.toString(10); 941 Diag(OverlapStmt->getLHS()->getLocStart(), 942 diag::note_duplicate_case_prev); 943 // FIXME: We really want to remove the bogus case stmt from the 944 // substmt, but we have no way to do this right now. 945 CaseListIsErroneous = true; 946 } 947 } 948 } 949 950 // Complain if we have a constant condition and we didn't find a match. 951 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 952 // TODO: it would be nice if we printed enums as enums, chars as 953 // chars, etc. 954 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 955 << ConstantCondValue.toString(10) 956 << CondExpr->getSourceRange(); 957 } 958 959 // Check to see if switch is over an Enum and handles all of its 960 // values. We only issue a warning if there is not 'default:', but 961 // we still do the analysis to preserve this information in the AST 962 // (which can be used by flow-based analyes). 963 // 964 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 965 966 // If switch has default case, then ignore it. 967 if (!CaseListIsErroneous && !HasConstantCond && ET) { 968 const EnumDecl *ED = ET->getDecl(); 969 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 970 EnumValsTy; 971 EnumValsTy EnumVals; 972 973 // Gather all enum values, set their type and sort them, 974 // allowing easier comparison with CaseVals. 975 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 976 EDI != ED->enumerator_end(); ++EDI) { 977 llvm::APSInt Val = EDI->getInitVal(); 978 AdjustAPSInt(Val, CondWidth, CondIsSigned); 979 EnumVals.push_back(std::make_pair(Val, *EDI)); 980 } 981 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 982 EnumValsTy::iterator EIend = 983 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 984 985 // See which case values aren't in enum. 986 EnumValsTy::const_iterator EI = EnumVals.begin(); 987 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 988 CI != CaseVals.end(); CI++) { 989 while (EI != EIend && EI->first < CI->first) 990 EI++; 991 if (EI == EIend || EI->first > CI->first) 992 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 993 << CondTypeBeforePromotion; 994 } 995 // See which of case ranges aren't in enum 996 EI = EnumVals.begin(); 997 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 998 RI != CaseRanges.end() && EI != EIend; RI++) { 999 while (EI != EIend && EI->first < RI->first) 1000 EI++; 1001 1002 if (EI == EIend || EI->first != RI->first) { 1003 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 1004 << CondTypeBeforePromotion; 1005 } 1006 1007 llvm::APSInt Hi = 1008 RI->second->getRHS()->EvaluateKnownConstInt(Context); 1009 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 1010 while (EI != EIend && EI->first < Hi) 1011 EI++; 1012 if (EI == EIend || EI->first != Hi) 1013 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 1014 << CondTypeBeforePromotion; 1015 } 1016 1017 // Check which enum vals aren't in switch 1018 CaseValsTy::const_iterator CI = CaseVals.begin(); 1019 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 1020 bool hasCasesNotInSwitch = false; 1021 1022 SmallVector<DeclarationName,8> UnhandledNames; 1023 1024 for (EI = EnumVals.begin(); EI != EIend; EI++){ 1025 // Drop unneeded case values 1026 llvm::APSInt CIVal; 1027 while (CI != CaseVals.end() && CI->first < EI->first) 1028 CI++; 1029 1030 if (CI != CaseVals.end() && CI->first == EI->first) 1031 continue; 1032 1033 // Drop unneeded case ranges 1034 for (; RI != CaseRanges.end(); RI++) { 1035 llvm::APSInt Hi = 1036 RI->second->getRHS()->EvaluateKnownConstInt(Context); 1037 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 1038 if (EI->first <= Hi) 1039 break; 1040 } 1041 1042 if (RI == CaseRanges.end() || EI->first < RI->first) { 1043 hasCasesNotInSwitch = true; 1044 UnhandledNames.push_back(EI->second->getDeclName()); 1045 } 1046 } 1047 1048 if (TheDefaultStmt && UnhandledNames.empty()) 1049 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); 1050 1051 // Produce a nice diagnostic if multiple values aren't handled. 1052 switch (UnhandledNames.size()) { 1053 case 0: break; 1054 case 1: 1055 Diag(CondExpr->getExprLoc(), TheDefaultStmt 1056 ? diag::warn_def_missing_case1 : diag::warn_missing_case1) 1057 << UnhandledNames[0]; 1058 break; 1059 case 2: 1060 Diag(CondExpr->getExprLoc(), TheDefaultStmt 1061 ? diag::warn_def_missing_case2 : diag::warn_missing_case2) 1062 << UnhandledNames[0] << UnhandledNames[1]; 1063 break; 1064 case 3: 1065 Diag(CondExpr->getExprLoc(), TheDefaultStmt 1066 ? diag::warn_def_missing_case3 : diag::warn_missing_case3) 1067 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 1068 break; 1069 default: 1070 Diag(CondExpr->getExprLoc(), TheDefaultStmt 1071 ? diag::warn_def_missing_cases : diag::warn_missing_cases) 1072 << (unsigned)UnhandledNames.size() 1073 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 1074 break; 1075 } 1076 1077 if (!hasCasesNotInSwitch) 1078 SS->setAllEnumCasesCovered(); 1079 } 1080 } 1081 1082 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt, 1083 diag::warn_empty_switch_body); 1084 1085 // FIXME: If the case list was broken is some way, we don't have a good system 1086 // to patch it up. Instead, just return the whole substmt as broken. 1087 if (CaseListIsErroneous) 1088 return StmtError(); 1089 1090 return Owned(SS); 1091} 1092 1093void 1094Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 1095 Expr *SrcExpr) { 1096 unsigned DIAG = diag::warn_not_in_enum_assignement; 1097 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc()) 1098 == DiagnosticsEngine::Ignored) 1099 return; 1100 1101 if (const EnumType *ET = DstType->getAs<EnumType>()) 1102 if (!Context.hasSameType(SrcType, DstType) && 1103 SrcType->isIntegerType()) { 1104 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() && 1105 SrcExpr->isIntegerConstantExpr(Context)) { 1106 // Get the bitwidth of the enum value before promotions. 1107 unsigned DstWith = Context.getIntWidth(DstType); 1108 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType(); 1109 1110 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context); 1111 const EnumDecl *ED = ET->getDecl(); 1112 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 1113 EnumValsTy; 1114 EnumValsTy EnumVals; 1115 1116 // Gather all enum values, set their type and sort them, 1117 // allowing easier comparison with rhs constant. 1118 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 1119 EDI != ED->enumerator_end(); ++EDI) { 1120 llvm::APSInt Val = EDI->getInitVal(); 1121 AdjustAPSInt(Val, DstWith, DstIsSigned); 1122 EnumVals.push_back(std::make_pair(Val, *EDI)); 1123 } 1124 if (EnumVals.empty()) 1125 return; 1126 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 1127 EnumValsTy::iterator EIend = 1128 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 1129 1130 // See which case values aren't in enum. 1131 EnumValsTy::const_iterator EI = EnumVals.begin(); 1132 while (EI != EIend && EI->first < RhsVal) 1133 EI++; 1134 if (EI == EIend || EI->first != RhsVal) { 1135 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement) 1136 << DstType; 1137 } 1138 } 1139 } 1140} 1141 1142StmtResult 1143Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 1144 Decl *CondVar, Stmt *Body) { 1145 ExprResult CondResult(Cond.release()); 1146 1147 VarDecl *ConditionVar = 0; 1148 if (CondVar) { 1149 ConditionVar = cast<VarDecl>(CondVar); 1150 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 1151 if (CondResult.isInvalid()) 1152 return StmtError(); 1153 } 1154 Expr *ConditionExpr = CondResult.take(); 1155 if (!ConditionExpr) 1156 return StmtError(); 1157 1158 DiagnoseUnusedExprResult(Body); 1159 1160 if (isa<NullStmt>(Body)) 1161 getCurCompoundScope().setHasEmptyLoopBodies(); 1162 1163 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 1164 Body, WhileLoc)); 1165} 1166 1167StmtResult 1168Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 1169 SourceLocation WhileLoc, SourceLocation CondLParen, 1170 Expr *Cond, SourceLocation CondRParen) { 1171 assert(Cond && "ActOnDoStmt(): missing expression"); 1172 1173 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 1174 if (CondResult.isInvalid()) 1175 return StmtError(); 1176 Cond = CondResult.take(); 1177 1178 CondResult = ActOnFinishFullExpr(Cond, DoLoc); 1179 if (CondResult.isInvalid()) 1180 return StmtError(); 1181 Cond = CondResult.take(); 1182 1183 DiagnoseUnusedExprResult(Body); 1184 1185 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 1186} 1187 1188namespace { 1189 // This visitor will traverse a conditional statement and store all 1190 // the evaluated decls into a vector. Simple is set to true if none 1191 // of the excluded constructs are used. 1192 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { 1193 llvm::SmallPtrSet<VarDecl*, 8> &Decls; 1194 SmallVector<SourceRange, 10> &Ranges; 1195 bool Simple; 1196public: 1197 typedef EvaluatedExprVisitor<DeclExtractor> Inherited; 1198 1199 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, 1200 SmallVector<SourceRange, 10> &Ranges) : 1201 Inherited(S.Context), 1202 Decls(Decls), 1203 Ranges(Ranges), 1204 Simple(true) {} 1205 1206 bool isSimple() { return Simple; } 1207 1208 // Replaces the method in EvaluatedExprVisitor. 1209 void VisitMemberExpr(MemberExpr* E) { 1210 Simple = false; 1211 } 1212 1213 // Any Stmt not whitelisted will cause the condition to be marked complex. 1214 void VisitStmt(Stmt *S) { 1215 Simple = false; 1216 } 1217 1218 void VisitBinaryOperator(BinaryOperator *E) { 1219 Visit(E->getLHS()); 1220 Visit(E->getRHS()); 1221 } 1222 1223 void VisitCastExpr(CastExpr *E) { 1224 Visit(E->getSubExpr()); 1225 } 1226 1227 void VisitUnaryOperator(UnaryOperator *E) { 1228 // Skip checking conditionals with derefernces. 1229 if (E->getOpcode() == UO_Deref) 1230 Simple = false; 1231 else 1232 Visit(E->getSubExpr()); 1233 } 1234 1235 void VisitConditionalOperator(ConditionalOperator *E) { 1236 Visit(E->getCond()); 1237 Visit(E->getTrueExpr()); 1238 Visit(E->getFalseExpr()); 1239 } 1240 1241 void VisitParenExpr(ParenExpr *E) { 1242 Visit(E->getSubExpr()); 1243 } 1244 1245 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 1246 Visit(E->getOpaqueValue()->getSourceExpr()); 1247 Visit(E->getFalseExpr()); 1248 } 1249 1250 void VisitIntegerLiteral(IntegerLiteral *E) { } 1251 void VisitFloatingLiteral(FloatingLiteral *E) { } 1252 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } 1253 void VisitCharacterLiteral(CharacterLiteral *E) { } 1254 void VisitGNUNullExpr(GNUNullExpr *E) { } 1255 void VisitImaginaryLiteral(ImaginaryLiteral *E) { } 1256 1257 void VisitDeclRefExpr(DeclRefExpr *E) { 1258 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 1259 if (!VD) return; 1260 1261 Ranges.push_back(E->getSourceRange()); 1262 1263 Decls.insert(VD); 1264 } 1265 1266 }; // end class DeclExtractor 1267 1268 // DeclMatcher checks to see if the decls are used in a non-evauluated 1269 // context. 1270 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { 1271 llvm::SmallPtrSet<VarDecl*, 8> &Decls; 1272 bool FoundDecl; 1273 1274public: 1275 typedef EvaluatedExprVisitor<DeclMatcher> Inherited; 1276 1277 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) : 1278 Inherited(S.Context), Decls(Decls), FoundDecl(false) { 1279 if (!Statement) return; 1280 1281 Visit(Statement); 1282 } 1283 1284 void VisitReturnStmt(ReturnStmt *S) { 1285 FoundDecl = true; 1286 } 1287 1288 void VisitBreakStmt(BreakStmt *S) { 1289 FoundDecl = true; 1290 } 1291 1292 void VisitGotoStmt(GotoStmt *S) { 1293 FoundDecl = true; 1294 } 1295 1296 void VisitCastExpr(CastExpr *E) { 1297 if (E->getCastKind() == CK_LValueToRValue) 1298 CheckLValueToRValueCast(E->getSubExpr()); 1299 else 1300 Visit(E->getSubExpr()); 1301 } 1302 1303 void CheckLValueToRValueCast(Expr *E) { 1304 E = E->IgnoreParenImpCasts(); 1305 1306 if (isa<DeclRefExpr>(E)) { 1307 return; 1308 } 1309 1310 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1311 Visit(CO->getCond()); 1312 CheckLValueToRValueCast(CO->getTrueExpr()); 1313 CheckLValueToRValueCast(CO->getFalseExpr()); 1314 return; 1315 } 1316 1317 if (BinaryConditionalOperator *BCO = 1318 dyn_cast<BinaryConditionalOperator>(E)) { 1319 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); 1320 CheckLValueToRValueCast(BCO->getFalseExpr()); 1321 return; 1322 } 1323 1324 Visit(E); 1325 } 1326 1327 void VisitDeclRefExpr(DeclRefExpr *E) { 1328 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 1329 if (Decls.count(VD)) 1330 FoundDecl = true; 1331 } 1332 1333 bool FoundDeclInUse() { return FoundDecl; } 1334 1335 }; // end class DeclMatcher 1336 1337 void CheckForLoopConditionalStatement(Sema &S, Expr *Second, 1338 Expr *Third, Stmt *Body) { 1339 // Condition is empty 1340 if (!Second) return; 1341 1342 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body, 1343 Second->getLocStart()) 1344 == DiagnosticsEngine::Ignored) 1345 return; 1346 1347 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); 1348 llvm::SmallPtrSet<VarDecl*, 8> Decls; 1349 SmallVector<SourceRange, 10> Ranges; 1350 DeclExtractor DE(S, Decls, Ranges); 1351 DE.Visit(Second); 1352 1353 // Don't analyze complex conditionals. 1354 if (!DE.isSimple()) return; 1355 1356 // No decls found. 1357 if (Decls.size() == 0) return; 1358 1359 // Don't warn on volatile, static, or global variables. 1360 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(), 1361 E = Decls.end(); 1362 I != E; ++I) 1363 if ((*I)->getType().isVolatileQualified() || 1364 (*I)->hasGlobalStorage()) return; 1365 1366 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || 1367 DeclMatcher(S, Decls, Third).FoundDeclInUse() || 1368 DeclMatcher(S, Decls, Body).FoundDeclInUse()) 1369 return; 1370 1371 // Load decl names into diagnostic. 1372 if (Decls.size() > 4) 1373 PDiag << 0; 1374 else { 1375 PDiag << Decls.size(); 1376 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(), 1377 E = Decls.end(); 1378 I != E; ++I) 1379 PDiag << (*I)->getDeclName(); 1380 } 1381 1382 // Load SourceRanges into diagnostic if there is room. 1383 // Otherwise, load the SourceRange of the conditional expression. 1384 if (Ranges.size() <= PartialDiagnostic::MaxArguments) 1385 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(), 1386 E = Ranges.end(); 1387 I != E; ++I) 1388 PDiag << *I; 1389 else 1390 PDiag << Second->getSourceRange(); 1391 1392 S.Diag(Ranges.begin()->getBegin(), PDiag); 1393 } 1394 1395} // end namespace 1396 1397StmtResult 1398Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1399 Stmt *First, FullExprArg second, Decl *secondVar, 1400 FullExprArg third, 1401 SourceLocation RParenLoc, Stmt *Body) { 1402 if (!getLangOpts().CPlusPlus) { 1403 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 1404 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1405 // declare identifiers for objects having storage class 'auto' or 1406 // 'register'. 1407 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 1408 DI!=DE; ++DI) { 1409 VarDecl *VD = dyn_cast<VarDecl>(*DI); 1410 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 1411 VD = 0; 1412 if (VD == 0) 1413 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 1414 // FIXME: mark decl erroneous! 1415 } 1416 } 1417 } 1418 1419 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body); 1420 1421 ExprResult SecondResult(second.release()); 1422 VarDecl *ConditionVar = 0; 1423 if (secondVar) { 1424 ConditionVar = cast<VarDecl>(secondVar); 1425 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1426 if (SecondResult.isInvalid()) 1427 return StmtError(); 1428 } 1429 1430 Expr *Third = third.release().takeAs<Expr>(); 1431 1432 DiagnoseUnusedExprResult(First); 1433 DiagnoseUnusedExprResult(Third); 1434 DiagnoseUnusedExprResult(Body); 1435 1436 if (isa<NullStmt>(Body)) 1437 getCurCompoundScope().setHasEmptyLoopBodies(); 1438 1439 return Owned(new (Context) ForStmt(Context, First, 1440 SecondResult.take(), ConditionVar, 1441 Third, Body, ForLoc, LParenLoc, 1442 RParenLoc)); 1443} 1444 1445/// In an Objective C collection iteration statement: 1446/// for (x in y) 1447/// x can be an arbitrary l-value expression. Bind it up as a 1448/// full-expression. 1449StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1450 // Reduce placeholder expressions here. Note that this rejects the 1451 // use of pseudo-object l-values in this position. 1452 ExprResult result = CheckPlaceholderExpr(E); 1453 if (result.isInvalid()) return StmtError(); 1454 E = result.take(); 1455 1456 ExprResult FullExpr = ActOnFinishFullExpr(E); 1457 if (FullExpr.isInvalid()) 1458 return StmtError(); 1459 return StmtResult(static_cast<Stmt*>(FullExpr.take())); 1460} 1461 1462ExprResult 1463Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1464 if (!collection) 1465 return ExprError(); 1466 1467 // Bail out early if we've got a type-dependent expression. 1468 if (collection->isTypeDependent()) return Owned(collection); 1469 1470 // Perform normal l-value conversion. 1471 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1472 if (result.isInvalid()) 1473 return ExprError(); 1474 collection = result.take(); 1475 1476 // The operand needs to have object-pointer type. 1477 // TODO: should we do a contextual conversion? 1478 const ObjCObjectPointerType *pointerType = 1479 collection->getType()->getAs<ObjCObjectPointerType>(); 1480 if (!pointerType) 1481 return Diag(forLoc, diag::err_collection_expr_type) 1482 << collection->getType() << collection->getSourceRange(); 1483 1484 // Check that the operand provides 1485 // - countByEnumeratingWithState:objects:count: 1486 const ObjCObjectType *objectType = pointerType->getObjectType(); 1487 ObjCInterfaceDecl *iface = objectType->getInterface(); 1488 1489 // If we have a forward-declared type, we can't do this check. 1490 // Under ARC, it is an error not to have a forward-declared class. 1491 if (iface && 1492 RequireCompleteType(forLoc, QualType(objectType, 0), 1493 getLangOpts().ObjCAutoRefCount 1494 ? diag::err_arc_collection_forward 1495 : 0, 1496 collection)) { 1497 // Otherwise, if we have any useful type information, check that 1498 // the type declares the appropriate method. 1499 } else if (iface || !objectType->qual_empty()) { 1500 IdentifierInfo *selectorIdents[] = { 1501 &Context.Idents.get("countByEnumeratingWithState"), 1502 &Context.Idents.get("objects"), 1503 &Context.Idents.get("count") 1504 }; 1505 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1506 1507 ObjCMethodDecl *method = 0; 1508 1509 // If there's an interface, look in both the public and private APIs. 1510 if (iface) { 1511 method = iface->lookupInstanceMethod(selector); 1512 if (!method) method = iface->lookupPrivateMethod(selector); 1513 } 1514 1515 // Also check protocol qualifiers. 1516 if (!method) 1517 method = LookupMethodInQualifiedType(selector, pointerType, 1518 /*instance*/ true); 1519 1520 // If we didn't find it anywhere, give up. 1521 if (!method) { 1522 Diag(forLoc, diag::warn_collection_expr_type) 1523 << collection->getType() << selector << collection->getSourceRange(); 1524 } 1525 1526 // TODO: check for an incompatible signature? 1527 } 1528 1529 // Wrap up any cleanups in the expression. 1530 return Owned(collection); 1531} 1532 1533StmtResult 1534Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1535 Stmt *First, Expr *collection, 1536 SourceLocation RParenLoc) { 1537 1538 ExprResult CollectionExprResult = 1539 CheckObjCForCollectionOperand(ForLoc, collection); 1540 1541 if (First) { 1542 QualType FirstType; 1543 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1544 if (!DS->isSingleDecl()) 1545 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1546 diag::err_toomany_element_decls)); 1547 1548 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1549 FirstType = D->getType(); 1550 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1551 // declare identifiers for objects having storage class 'auto' or 1552 // 'register'. 1553 if (!D->hasLocalStorage()) 1554 return StmtError(Diag(D->getLocation(), 1555 diag::err_non_variable_decl_in_for)); 1556 } else { 1557 Expr *FirstE = cast<Expr>(First); 1558 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1559 return StmtError(Diag(First->getLocStart(), 1560 diag::err_selector_element_not_lvalue) 1561 << First->getSourceRange()); 1562 1563 FirstType = static_cast<Expr*>(First)->getType(); 1564 } 1565 if (!FirstType->isDependentType() && 1566 !FirstType->isObjCObjectPointerType() && 1567 !FirstType->isBlockPointerType()) 1568 return StmtError(Diag(ForLoc, diag::err_selector_element_type) 1569 << FirstType << First->getSourceRange()); 1570 } 1571 1572 if (CollectionExprResult.isInvalid()) 1573 return StmtError(); 1574 1575 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take()); 1576 if (CollectionExprResult.isInvalid()) 1577 return StmtError(); 1578 1579 return Owned(new (Context) ObjCForCollectionStmt(First, 1580 CollectionExprResult.take(), 0, 1581 ForLoc, RParenLoc)); 1582} 1583 1584/// Finish building a variable declaration for a for-range statement. 1585/// \return true if an error occurs. 1586static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1587 SourceLocation Loc, int diag) { 1588 // Deduce the type for the iterator variable now rather than leaving it to 1589 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1590 TypeSourceInfo *InitTSI = 0; 1591 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || 1592 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) == 1593 Sema::DAR_Failed) 1594 SemaRef.Diag(Loc, diag) << Init->getType(); 1595 if (!InitTSI) { 1596 Decl->setInvalidDecl(); 1597 return true; 1598 } 1599 Decl->setTypeSourceInfo(InitTSI); 1600 Decl->setType(InitTSI->getType()); 1601 1602 // In ARC, infer lifetime. 1603 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1604 // we're doing the equivalent of fast iteration. 1605 if (SemaRef.getLangOpts().ObjCAutoRefCount && 1606 SemaRef.inferObjCARCLifetime(Decl)) 1607 Decl->setInvalidDecl(); 1608 1609 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1610 /*TypeMayContainAuto=*/false); 1611 SemaRef.FinalizeDeclaration(Decl); 1612 SemaRef.CurContext->addHiddenDecl(Decl); 1613 return false; 1614} 1615 1616namespace { 1617 1618/// Produce a note indicating which begin/end function was implicitly called 1619/// by a C++11 for-range statement. This is often not obvious from the code, 1620/// nor from the diagnostics produced when analysing the implicit expressions 1621/// required in a for-range statement. 1622void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1623 Sema::BeginEndFunction BEF) { 1624 CallExpr *CE = dyn_cast<CallExpr>(E); 1625 if (!CE) 1626 return; 1627 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1628 if (!D) 1629 return; 1630 SourceLocation Loc = D->getLocation(); 1631 1632 std::string Description; 1633 bool IsTemplate = false; 1634 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1635 Description = SemaRef.getTemplateArgumentBindingsText( 1636 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1637 IsTemplate = true; 1638 } 1639 1640 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1641 << BEF << IsTemplate << Description << E->getType(); 1642} 1643 1644/// Build a variable declaration for a for-range statement. 1645VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1646 QualType Type, const char *Name) { 1647 DeclContext *DC = SemaRef.CurContext; 1648 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1649 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1650 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1651 TInfo, SC_Auto, SC_None); 1652 Decl->setImplicit(); 1653 return Decl; 1654} 1655 1656} 1657 1658static bool ObjCEnumerationCollection(Expr *Collection) { 1659 return !Collection->isTypeDependent() 1660 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0; 1661} 1662 1663/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. 1664/// 1665/// C++11 [stmt.ranged]: 1666/// A range-based for statement is equivalent to 1667/// 1668/// { 1669/// auto && __range = range-init; 1670/// for ( auto __begin = begin-expr, 1671/// __end = end-expr; 1672/// __begin != __end; 1673/// ++__begin ) { 1674/// for-range-declaration = *__begin; 1675/// statement 1676/// } 1677/// } 1678/// 1679/// The body of the loop is not available yet, since it cannot be analysed until 1680/// we have determined the type of the for-range-declaration. 1681StmtResult 1682Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, 1683 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1684 SourceLocation RParenLoc, BuildForRangeKind Kind) { 1685 if (!First || !Range) 1686 return StmtError(); 1687 1688 if (ObjCEnumerationCollection(Range)) 1689 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc); 1690 1691 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1692 assert(DS && "first part of for range not a decl stmt"); 1693 1694 if (!DS->isSingleDecl()) { 1695 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1696 return StmtError(); 1697 } 1698 if (DS->getSingleDecl()->isInvalidDecl()) 1699 return StmtError(); 1700 1701 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1702 return StmtError(); 1703 1704 // Build auto && __range = range-init 1705 SourceLocation RangeLoc = Range->getLocStart(); 1706 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1707 Context.getAutoRRefDeductType(), 1708 "__range"); 1709 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1710 diag::err_for_range_deduction_failure)) 1711 return StmtError(); 1712 1713 // Claim the type doesn't contain auto: we've already done the checking. 1714 DeclGroupPtrTy RangeGroup = 1715 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1716 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1717 if (RangeDecl.isInvalid()) 1718 return StmtError(); 1719 1720 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1721 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1722 RParenLoc, Kind); 1723} 1724 1725/// \brief Create the initialization, compare, and increment steps for 1726/// the range-based for loop expression. 1727/// This function does not handle array-based for loops, 1728/// which are created in Sema::BuildCXXForRangeStmt. 1729/// 1730/// \returns a ForRangeStatus indicating success or what kind of error occurred. 1731/// BeginExpr and EndExpr are set and FRS_Success is returned on success; 1732/// CandidateSet and BEF are set and some non-success value is returned on 1733/// failure. 1734static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S, 1735 Expr *BeginRange, Expr *EndRange, 1736 QualType RangeType, 1737 VarDecl *BeginVar, 1738 VarDecl *EndVar, 1739 SourceLocation ColonLoc, 1740 OverloadCandidateSet *CandidateSet, 1741 ExprResult *BeginExpr, 1742 ExprResult *EndExpr, 1743 Sema::BeginEndFunction *BEF) { 1744 DeclarationNameInfo BeginNameInfo( 1745 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc); 1746 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"), 1747 ColonLoc); 1748 1749 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo, 1750 Sema::LookupMemberName); 1751 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName); 1752 1753 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1754 // - if _RangeT is a class type, the unqualified-ids begin and end are 1755 // looked up in the scope of class _RangeT as if by class member access 1756 // lookup (3.4.5), and if either (or both) finds at least one 1757 // declaration, begin-expr and end-expr are __range.begin() and 1758 // __range.end(), respectively; 1759 SemaRef.LookupQualifiedName(BeginMemberLookup, D); 1760 SemaRef.LookupQualifiedName(EndMemberLookup, D); 1761 1762 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1763 SourceLocation RangeLoc = BeginVar->getLocation(); 1764 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin; 1765 1766 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch) 1767 << RangeLoc << BeginRange->getType() << *BEF; 1768 return Sema::FRS_DiagnosticIssued; 1769 } 1770 } else { 1771 // - otherwise, begin-expr and end-expr are begin(__range) and 1772 // end(__range), respectively, where begin and end are looked up with 1773 // argument-dependent lookup (3.4.2). For the purposes of this name 1774 // lookup, namespace std is an associated namespace. 1775 1776 } 1777 1778 *BEF = Sema::BEF_begin; 1779 Sema::ForRangeStatus RangeStatus = 1780 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar, 1781 Sema::BEF_begin, BeginNameInfo, 1782 BeginMemberLookup, CandidateSet, 1783 BeginRange, BeginExpr); 1784 1785 if (RangeStatus != Sema::FRS_Success) 1786 return RangeStatus; 1787 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc, 1788 diag::err_for_range_iter_deduction_failure)) { 1789 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF); 1790 return Sema::FRS_DiagnosticIssued; 1791 } 1792 1793 *BEF = Sema::BEF_end; 1794 RangeStatus = 1795 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar, 1796 Sema::BEF_end, EndNameInfo, 1797 EndMemberLookup, CandidateSet, 1798 EndRange, EndExpr); 1799 if (RangeStatus != Sema::FRS_Success) 1800 return RangeStatus; 1801 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc, 1802 diag::err_for_range_iter_deduction_failure)) { 1803 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF); 1804 return Sema::FRS_DiagnosticIssued; 1805 } 1806 return Sema::FRS_Success; 1807} 1808 1809/// Speculatively attempt to dereference an invalid range expression. 1810/// If the attempt fails, this function will return a valid, null StmtResult 1811/// and emit no diagnostics. 1812static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, 1813 SourceLocation ForLoc, 1814 Stmt *LoopVarDecl, 1815 SourceLocation ColonLoc, 1816 Expr *Range, 1817 SourceLocation RangeLoc, 1818 SourceLocation RParenLoc) { 1819 // Determine whether we can rebuild the for-range statement with a 1820 // dereferenced range expression. 1821 ExprResult AdjustedRange; 1822 { 1823 Sema::SFINAETrap Trap(SemaRef); 1824 1825 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range); 1826 if (AdjustedRange.isInvalid()) 1827 return StmtResult(); 1828 1829 StmtResult SR = 1830 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc, 1831 AdjustedRange.get(), RParenLoc, 1832 Sema::BFRK_Check); 1833 if (SR.isInvalid()) 1834 return StmtResult(); 1835 } 1836 1837 // The attempt to dereference worked well enough that it could produce a valid 1838 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in 1839 // case there are any other (non-fatal) problems with it. 1840 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference) 1841 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*"); 1842 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc, 1843 AdjustedRange.get(), RParenLoc, 1844 Sema::BFRK_Rebuild); 1845} 1846 1847/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. 1848StmtResult 1849Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1850 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1851 Expr *Inc, Stmt *LoopVarDecl, 1852 SourceLocation RParenLoc, BuildForRangeKind Kind) { 1853 Scope *S = getCurScope(); 1854 1855 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1856 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1857 QualType RangeVarType = RangeVar->getType(); 1858 1859 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1860 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1861 1862 StmtResult BeginEndDecl = BeginEnd; 1863 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1864 1865 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1866 SourceLocation RangeLoc = RangeVar->getLocation(); 1867 1868 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 1869 1870 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1871 VK_LValue, ColonLoc); 1872 if (BeginRangeRef.isInvalid()) 1873 return StmtError(); 1874 1875 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1876 VK_LValue, ColonLoc); 1877 if (EndRangeRef.isInvalid()) 1878 return StmtError(); 1879 1880 QualType AutoType = Context.getAutoDeductType(); 1881 Expr *Range = RangeVar->getInit(); 1882 if (!Range) 1883 return StmtError(); 1884 QualType RangeType = Range->getType(); 1885 1886 if (RequireCompleteType(RangeLoc, RangeType, 1887 diag::err_for_range_incomplete_type)) 1888 return StmtError(); 1889 1890 // Build auto __begin = begin-expr, __end = end-expr. 1891 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1892 "__begin"); 1893 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1894 "__end"); 1895 1896 // Build begin-expr and end-expr and attach to __begin and __end variables. 1897 ExprResult BeginExpr, EndExpr; 1898 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1899 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1900 // __range + __bound, respectively, where __bound is the array bound. If 1901 // _RangeT is an array of unknown size or an array of incomplete type, 1902 // the program is ill-formed; 1903 1904 // begin-expr is __range. 1905 BeginExpr = BeginRangeRef; 1906 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 1907 diag::err_for_range_iter_deduction_failure)) { 1908 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1909 return StmtError(); 1910 } 1911 1912 // Find the array bound. 1913 ExprResult BoundExpr; 1914 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1915 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1916 Context.getPointerDiffType(), 1917 RangeLoc)); 1918 else if (const VariableArrayType *VAT = 1919 dyn_cast<VariableArrayType>(UnqAT)) 1920 BoundExpr = VAT->getSizeExpr(); 1921 else { 1922 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1923 // UnqAT is not incomplete and Range is not type-dependent. 1924 llvm_unreachable("Unexpected array type in for-range"); 1925 } 1926 1927 // end-expr is __range + __bound. 1928 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 1929 BoundExpr.get()); 1930 if (EndExpr.isInvalid()) 1931 return StmtError(); 1932 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1933 diag::err_for_range_iter_deduction_failure)) { 1934 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1935 return StmtError(); 1936 } 1937 } else { 1938 OverloadCandidateSet CandidateSet(RangeLoc); 1939 Sema::BeginEndFunction BEFFailure; 1940 ForRangeStatus RangeStatus = 1941 BuildNonArrayForRange(*this, S, BeginRangeRef.get(), 1942 EndRangeRef.get(), RangeType, 1943 BeginVar, EndVar, ColonLoc, &CandidateSet, 1944 &BeginExpr, &EndExpr, &BEFFailure); 1945 1946 // If building the range failed, try dereferencing the range expression 1947 // unless a diagnostic was issued or the end function is problematic. 1948 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction && 1949 BEFFailure == BEF_begin) { 1950 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc, 1951 LoopVarDecl, ColonLoc, 1952 Range, RangeLoc, 1953 RParenLoc); 1954 if (SR.isInvalid() || SR.isUsable()) 1955 return SR; 1956 } 1957 1958 // Otherwise, emit diagnostics if we haven't already. 1959 if (RangeStatus == FRS_NoViableFunction) { 1960 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get(); 1961 Diag(Range->getLocStart(), diag::err_for_range_invalid) 1962 << RangeLoc << Range->getType() << BEFFailure; 1963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range); 1964 } 1965 // Return an error if no fix was discovered. 1966 if (RangeStatus != FRS_Success) 1967 return StmtError(); 1968 } 1969 1970 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() && 1971 "invalid range expression in for loop"); 1972 1973 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same. 1974 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1975 if (!Context.hasSameType(BeginType, EndType)) { 1976 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1977 << BeginType << EndType; 1978 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1979 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1980 } 1981 1982 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1983 // Claim the type doesn't contain auto: we've already done the checking. 1984 DeclGroupPtrTy BeginEndGroup = 1985 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1986 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1987 1988 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 1989 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1990 VK_LValue, ColonLoc); 1991 if (BeginRef.isInvalid()) 1992 return StmtError(); 1993 1994 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1995 VK_LValue, ColonLoc); 1996 if (EndRef.isInvalid()) 1997 return StmtError(); 1998 1999 // Build and check __begin != __end expression. 2000 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 2001 BeginRef.get(), EndRef.get()); 2002 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 2003 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 2004 if (NotEqExpr.isInvalid()) { 2005 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 2006 << RangeLoc << 0 << BeginRangeRef.get()->getType(); 2007 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2008 if (!Context.hasSameType(BeginType, EndType)) 2009 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 2010 return StmtError(); 2011 } 2012 2013 // Build and check ++__begin expression. 2014 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 2015 VK_LValue, ColonLoc); 2016 if (BeginRef.isInvalid()) 2017 return StmtError(); 2018 2019 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 2020 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 2021 if (IncrExpr.isInvalid()) { 2022 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 2023 << RangeLoc << 2 << BeginRangeRef.get()->getType() ; 2024 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2025 return StmtError(); 2026 } 2027 2028 // Build and check *__begin expression. 2029 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 2030 VK_LValue, ColonLoc); 2031 if (BeginRef.isInvalid()) 2032 return StmtError(); 2033 2034 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 2035 if (DerefExpr.isInvalid()) { 2036 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 2037 << RangeLoc << 1 << BeginRangeRef.get()->getType(); 2038 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2039 return StmtError(); 2040 } 2041 2042 // Attach *__begin as initializer for VD. Don't touch it if we're just 2043 // trying to determine whether this would be a valid range. 2044 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { 2045 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 2046 /*TypeMayContainAuto=*/true); 2047 if (LoopVar->isInvalidDecl()) 2048 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2049 } 2050 } else { 2051 // The range is implicitly used as a placeholder when it is dependent. 2052 RangeVar->setUsed(); 2053 } 2054 2055 // Don't bother to actually allocate the result if we're just trying to 2056 // determine whether it would be valid. 2057 if (Kind == BFRK_Check) 2058 return StmtResult(); 2059 2060 return Owned(new (Context) CXXForRangeStmt(RangeDS, 2061 cast_or_null<DeclStmt>(BeginEndDecl.get()), 2062 NotEqExpr.take(), IncrExpr.take(), 2063 LoopVarDS, /*Body=*/0, ForLoc, 2064 ColonLoc, RParenLoc)); 2065} 2066 2067/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach 2068/// statement. 2069StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) { 2070 if (!S || !B) 2071 return StmtError(); 2072 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S); 2073 2074 ForStmt->setBody(B); 2075 return S; 2076} 2077 2078/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 2079/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 2080/// body cannot be performed until after the type of the range variable is 2081/// determined. 2082StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 2083 if (!S || !B) 2084 return StmtError(); 2085 2086 if (isa<ObjCForCollectionStmt>(S)) 2087 return FinishObjCForCollectionStmt(S, B); 2088 2089 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); 2090 ForStmt->setBody(B); 2091 2092 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, 2093 diag::warn_empty_range_based_for_body); 2094 2095 return S; 2096} 2097 2098StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 2099 SourceLocation LabelLoc, 2100 LabelDecl *TheDecl) { 2101 getCurFunction()->setHasBranchIntoScope(); 2102 TheDecl->setUsed(); 2103 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 2104} 2105 2106StmtResult 2107Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 2108 Expr *E) { 2109 // Convert operand to void* 2110 if (!E->isTypeDependent()) { 2111 QualType ETy = E->getType(); 2112 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 2113 ExprResult ExprRes = Owned(E); 2114 AssignConvertType ConvTy = 2115 CheckSingleAssignmentConstraints(DestTy, ExprRes); 2116 if (ExprRes.isInvalid()) 2117 return StmtError(); 2118 E = ExprRes.take(); 2119 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 2120 return StmtError(); 2121 } 2122 2123 ExprResult ExprRes = ActOnFinishFullExpr(E); 2124 if (ExprRes.isInvalid()) 2125 return StmtError(); 2126 E = ExprRes.take(); 2127 2128 getCurFunction()->setHasIndirectGoto(); 2129 2130 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 2131} 2132 2133StmtResult 2134Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 2135 Scope *S = CurScope->getContinueParent(); 2136 if (!S) { 2137 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 2138 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 2139 } 2140 2141 return Owned(new (Context) ContinueStmt(ContinueLoc)); 2142} 2143 2144StmtResult 2145Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 2146 Scope *S = CurScope->getBreakParent(); 2147 if (!S) { 2148 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 2149 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 2150 } 2151 2152 return Owned(new (Context) BreakStmt(BreakLoc)); 2153} 2154 2155/// \brief Determine whether the given expression is a candidate for 2156/// copy elision in either a return statement or a throw expression. 2157/// 2158/// \param ReturnType If we're determining the copy elision candidate for 2159/// a return statement, this is the return type of the function. If we're 2160/// determining the copy elision candidate for a throw expression, this will 2161/// be a NULL type. 2162/// 2163/// \param E The expression being returned from the function or block, or 2164/// being thrown. 2165/// 2166/// \param AllowFunctionParameter Whether we allow function parameters to 2167/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 2168/// we re-use this logic to determine whether we should try to move as part of 2169/// a return or throw (which does allow function parameters). 2170/// 2171/// \returns The NRVO candidate variable, if the return statement may use the 2172/// NRVO, or NULL if there is no such candidate. 2173const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 2174 Expr *E, 2175 bool AllowFunctionParameter) { 2176 QualType ExprType = E->getType(); 2177 // - in a return statement in a function with ... 2178 // ... a class return type ... 2179 if (!ReturnType.isNull()) { 2180 if (!ReturnType->isRecordType()) 2181 return 0; 2182 // ... the same cv-unqualified type as the function return type ... 2183 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 2184 return 0; 2185 } 2186 2187 // ... the expression is the name of a non-volatile automatic object 2188 // (other than a function or catch-clause parameter)) ... 2189 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 2190 if (!DR || DR->refersToEnclosingLocal()) 2191 return 0; 2192 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 2193 if (!VD) 2194 return 0; 2195 2196 // ...object (other than a function or catch-clause parameter)... 2197 if (VD->getKind() != Decl::Var && 2198 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 2199 return 0; 2200 if (VD->isExceptionVariable()) return 0; 2201 2202 // ...automatic... 2203 if (!VD->hasLocalStorage()) return 0; 2204 2205 // ...non-volatile... 2206 if (VD->getType().isVolatileQualified()) return 0; 2207 if (VD->getType()->isReferenceType()) return 0; 2208 2209 // __block variables can't be allocated in a way that permits NRVO. 2210 if (VD->hasAttr<BlocksAttr>()) return 0; 2211 2212 // Variables with higher required alignment than their type's ABI 2213 // alignment cannot use NRVO. 2214 if (VD->hasAttr<AlignedAttr>() && 2215 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 2216 return 0; 2217 2218 return VD; 2219} 2220 2221/// \brief Perform the initialization of a potentially-movable value, which 2222/// is the result of return value. 2223/// 2224/// This routine implements C++0x [class.copy]p33, which attempts to treat 2225/// returned lvalues as rvalues in certain cases (to prefer move construction), 2226/// then falls back to treating them as lvalues if that failed. 2227ExprResult 2228Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 2229 const VarDecl *NRVOCandidate, 2230 QualType ResultType, 2231 Expr *Value, 2232 bool AllowNRVO) { 2233 // C++0x [class.copy]p33: 2234 // When the criteria for elision of a copy operation are met or would 2235 // be met save for the fact that the source object is a function 2236 // parameter, and the object to be copied is designated by an lvalue, 2237 // overload resolution to select the constructor for the copy is first 2238 // performed as if the object were designated by an rvalue. 2239 ExprResult Res = ExprError(); 2240 if (AllowNRVO && 2241 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 2242 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 2243 Value->getType(), CK_NoOp, Value, VK_XValue); 2244 2245 Expr *InitExpr = &AsRvalue; 2246 InitializationKind Kind 2247 = InitializationKind::CreateCopy(Value->getLocStart(), 2248 Value->getLocStart()); 2249 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 2250 2251 // [...] If overload resolution fails, or if the type of the first 2252 // parameter of the selected constructor is not an rvalue reference 2253 // to the object's type (possibly cv-qualified), overload resolution 2254 // is performed again, considering the object as an lvalue. 2255 if (Seq) { 2256 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 2257 StepEnd = Seq.step_end(); 2258 Step != StepEnd; ++Step) { 2259 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 2260 continue; 2261 2262 CXXConstructorDecl *Constructor 2263 = cast<CXXConstructorDecl>(Step->Function.Function); 2264 2265 const RValueReferenceType *RRefType 2266 = Constructor->getParamDecl(0)->getType() 2267 ->getAs<RValueReferenceType>(); 2268 2269 // If we don't meet the criteria, break out now. 2270 if (!RRefType || 2271 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 2272 Context.getTypeDeclType(Constructor->getParent()))) 2273 break; 2274 2275 // Promote "AsRvalue" to the heap, since we now need this 2276 // expression node to persist. 2277 Value = ImplicitCastExpr::Create(Context, Value->getType(), 2278 CK_NoOp, Value, 0, VK_XValue); 2279 2280 // Complete type-checking the initialization of the return type 2281 // using the constructor we found. 2282 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 2283 } 2284 } 2285 } 2286 2287 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 2288 // above, or overload resolution failed. Either way, we need to try 2289 // (again) now with the return value expression as written. 2290 if (Res.isInvalid()) 2291 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 2292 2293 return Res; 2294} 2295 2296/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 2297/// for capturing scopes. 2298/// 2299StmtResult 2300Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 2301 // If this is the first return we've seen, infer the return type. 2302 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those 2303 // rules which allows multiple return statements. 2304 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 2305 QualType FnRetType = CurCap->ReturnType; 2306 2307 // For blocks/lambdas with implicit return types, we check each return 2308 // statement individually, and deduce the common return type when the block 2309 // or lambda is completed. 2310 if (CurCap->HasImplicitReturnType) { 2311 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 2312 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 2313 if (Result.isInvalid()) 2314 return StmtError(); 2315 RetValExp = Result.take(); 2316 2317 if (!RetValExp->isTypeDependent()) 2318 FnRetType = RetValExp->getType(); 2319 else 2320 FnRetType = CurCap->ReturnType = Context.DependentTy; 2321 } else { 2322 if (RetValExp) { 2323 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 2324 // initializer list, because it is not an expression (even 2325 // though we represent it as one). We still deduce 'void'. 2326 Diag(ReturnLoc, diag::err_lambda_return_init_list) 2327 << RetValExp->getSourceRange(); 2328 } 2329 2330 FnRetType = Context.VoidTy; 2331 } 2332 2333 // Although we'll properly infer the type of the block once it's completed, 2334 // make sure we provide a return type now for better error recovery. 2335 if (CurCap->ReturnType.isNull()) 2336 CurCap->ReturnType = FnRetType; 2337 } 2338 assert(!FnRetType.isNull()); 2339 2340 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 2341 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 2342 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 2343 return StmtError(); 2344 } 2345 } else { 2346 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap); 2347 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){ 2348 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 2349 return StmtError(); 2350 } 2351 } 2352 2353 // Otherwise, verify that this result type matches the previous one. We are 2354 // pickier with blocks than for normal functions because we don't have GCC 2355 // compatibility to worry about here. 2356 const VarDecl *NRVOCandidate = 0; 2357 if (FnRetType->isDependentType()) { 2358 // Delay processing for now. TODO: there are lots of dependent 2359 // types we can conclusively prove aren't void. 2360 } else if (FnRetType->isVoidType()) { 2361 if (RetValExp && !isa<InitListExpr>(RetValExp) && 2362 !(getLangOpts().CPlusPlus && 2363 (RetValExp->isTypeDependent() || 2364 RetValExp->getType()->isVoidType()))) { 2365 if (!getLangOpts().CPlusPlus && 2366 RetValExp->getType()->isVoidType()) 2367 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; 2368 else { 2369 Diag(ReturnLoc, diag::err_return_block_has_expr); 2370 RetValExp = 0; 2371 } 2372 } 2373 } else if (!RetValExp) { 2374 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 2375 } else if (!RetValExp->isTypeDependent()) { 2376 // we have a non-void block with an expression, continue checking 2377 2378 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 2379 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 2380 // function return. 2381 2382 // In C++ the return statement is handled via a copy initialization. 2383 // the C version of which boils down to CheckSingleAssignmentConstraints. 2384 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 2385 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 2386 FnRetType, 2387 NRVOCandidate != 0); 2388 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 2389 FnRetType, RetValExp); 2390 if (Res.isInvalid()) { 2391 // FIXME: Cleanup temporaries here, anyway? 2392 return StmtError(); 2393 } 2394 RetValExp = Res.take(); 2395 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 2396 } 2397 2398 if (RetValExp) { 2399 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 2400 if (ER.isInvalid()) 2401 return StmtError(); 2402 RetValExp = ER.take(); 2403 } 2404 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 2405 NRVOCandidate); 2406 2407 // If we need to check for the named return value optimization, 2408 // or if we need to infer the return type, 2409 // save the return statement in our scope for later processing. 2410 if (CurCap->HasImplicitReturnType || 2411 (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 2412 !CurContext->isDependentContext())) 2413 FunctionScopes.back()->Returns.push_back(Result); 2414 2415 return Owned(Result); 2416} 2417 2418StmtResult 2419Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 2420 // Check for unexpanded parameter packs. 2421 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 2422 return StmtError(); 2423 2424 if (isa<CapturingScopeInfo>(getCurFunction())) 2425 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); 2426 2427 QualType FnRetType; 2428 QualType RelatedRetType; 2429 if (const FunctionDecl *FD = getCurFunctionDecl()) { 2430 FnRetType = FD->getResultType(); 2431 if (FD->isNoReturn()) 2432 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 2433 << FD->getDeclName(); 2434 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 2435 FnRetType = MD->getResultType(); 2436 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 2437 // In the implementation of a method with a related return type, the 2438 // type used to type-check the validity of return statements within the 2439 // method body is a pointer to the type of the class being implemented. 2440 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 2441 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); 2442 } 2443 } else // If we don't have a function/method context, bail. 2444 return StmtError(); 2445 2446 ReturnStmt *Result = 0; 2447 if (FnRetType->isVoidType()) { 2448 if (RetValExp) { 2449 if (isa<InitListExpr>(RetValExp)) { 2450 // We simply never allow init lists as the return value of void 2451 // functions. This is compatible because this was never allowed before, 2452 // so there's no legacy code to deal with. 2453 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 2454 int FunctionKind = 0; 2455 if (isa<ObjCMethodDecl>(CurDecl)) 2456 FunctionKind = 1; 2457 else if (isa<CXXConstructorDecl>(CurDecl)) 2458 FunctionKind = 2; 2459 else if (isa<CXXDestructorDecl>(CurDecl)) 2460 FunctionKind = 3; 2461 2462 Diag(ReturnLoc, diag::err_return_init_list) 2463 << CurDecl->getDeclName() << FunctionKind 2464 << RetValExp->getSourceRange(); 2465 2466 // Drop the expression. 2467 RetValExp = 0; 2468 } else if (!RetValExp->isTypeDependent()) { 2469 // C99 6.8.6.4p1 (ext_ since GCC warns) 2470 unsigned D = diag::ext_return_has_expr; 2471 if (RetValExp->getType()->isVoidType()) 2472 D = diag::ext_return_has_void_expr; 2473 else { 2474 ExprResult Result = Owned(RetValExp); 2475 Result = IgnoredValueConversions(Result.take()); 2476 if (Result.isInvalid()) 2477 return StmtError(); 2478 RetValExp = Result.take(); 2479 RetValExp = ImpCastExprToType(RetValExp, 2480 Context.VoidTy, CK_ToVoid).take(); 2481 } 2482 2483 // return (some void expression); is legal in C++. 2484 if (D != diag::ext_return_has_void_expr || 2485 !getLangOpts().CPlusPlus) { 2486 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 2487 2488 int FunctionKind = 0; 2489 if (isa<ObjCMethodDecl>(CurDecl)) 2490 FunctionKind = 1; 2491 else if (isa<CXXConstructorDecl>(CurDecl)) 2492 FunctionKind = 2; 2493 else if (isa<CXXDestructorDecl>(CurDecl)) 2494 FunctionKind = 3; 2495 2496 Diag(ReturnLoc, D) 2497 << CurDecl->getDeclName() << FunctionKind 2498 << RetValExp->getSourceRange(); 2499 } 2500 } 2501 2502 if (RetValExp) { 2503 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 2504 if (ER.isInvalid()) 2505 return StmtError(); 2506 RetValExp = ER.take(); 2507 } 2508 } 2509 2510 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 2511 } else if (!RetValExp && !FnRetType->isDependentType()) { 2512 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 2513 // C99 6.8.6.4p1 (ext_ since GCC warns) 2514 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr; 2515 2516 if (FunctionDecl *FD = getCurFunctionDecl()) 2517 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 2518 else 2519 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 2520 Result = new (Context) ReturnStmt(ReturnLoc); 2521 } else { 2522 const VarDecl *NRVOCandidate = 0; 2523 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 2524 // we have a non-void function with an expression, continue checking 2525 2526 if (!RelatedRetType.isNull()) { 2527 // If we have a related result type, perform an extra conversion here. 2528 // FIXME: The diagnostics here don't really describe what is happening. 2529 InitializedEntity Entity = 2530 InitializedEntity::InitializeTemporary(RelatedRetType); 2531 2532 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(), 2533 RetValExp); 2534 if (Res.isInvalid()) { 2535 // FIXME: Cleanup temporaries here, anyway? 2536 return StmtError(); 2537 } 2538 RetValExp = Res.takeAs<Expr>(); 2539 } 2540 2541 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 2542 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 2543 // function return. 2544 2545 // In C++ the return statement is handled via a copy initialization, 2546 // the C version of which boils down to CheckSingleAssignmentConstraints. 2547 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 2548 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 2549 FnRetType, 2550 NRVOCandidate != 0); 2551 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 2552 FnRetType, RetValExp); 2553 if (Res.isInvalid()) { 2554 // FIXME: Cleanup temporaries here, anyway? 2555 return StmtError(); 2556 } 2557 2558 RetValExp = Res.takeAs<Expr>(); 2559 if (RetValExp) 2560 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 2561 } 2562 2563 if (RetValExp) { 2564 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 2565 if (ER.isInvalid()) 2566 return StmtError(); 2567 RetValExp = ER.take(); 2568 } 2569 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 2570 } 2571 2572 // If we need to check for the named return value optimization, save the 2573 // return statement in our scope for later processing. 2574 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 2575 !CurContext->isDependentContext()) 2576 FunctionScopes.back()->Returns.push_back(Result); 2577 2578 return Owned(Result); 2579} 2580 2581StmtResult 2582Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2583 SourceLocation RParen, Decl *Parm, 2584 Stmt *Body) { 2585 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2586 if (Var && Var->isInvalidDecl()) 2587 return StmtError(); 2588 2589 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2590} 2591 2592StmtResult 2593Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2594 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2595} 2596 2597StmtResult 2598Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2599 MultiStmtArg CatchStmts, Stmt *Finally) { 2600 if (!getLangOpts().ObjCExceptions) 2601 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2602 2603 getCurFunction()->setHasBranchProtectedScope(); 2604 unsigned NumCatchStmts = CatchStmts.size(); 2605 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2606 CatchStmts.data(), 2607 NumCatchStmts, 2608 Finally)); 2609} 2610 2611StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { 2612 if (Throw) { 2613 ExprResult Result = DefaultLvalueConversion(Throw); 2614 if (Result.isInvalid()) 2615 return StmtError(); 2616 2617 Result = ActOnFinishFullExpr(Result.take()); 2618 if (Result.isInvalid()) 2619 return StmtError(); 2620 Throw = Result.take(); 2621 2622 QualType ThrowType = Throw->getType(); 2623 // Make sure the expression type is an ObjC pointer or "void *". 2624 if (!ThrowType->isDependentType() && 2625 !ThrowType->isObjCObjectPointerType()) { 2626 const PointerType *PT = ThrowType->getAs<PointerType>(); 2627 if (!PT || !PT->getPointeeType()->isVoidType()) 2628 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2629 << Throw->getType() << Throw->getSourceRange()); 2630 } 2631 } 2632 2633 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2634} 2635 2636StmtResult 2637Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2638 Scope *CurScope) { 2639 if (!getLangOpts().ObjCExceptions) 2640 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2641 2642 if (!Throw) { 2643 // @throw without an expression designates a rethrow (which much occur 2644 // in the context of an @catch clause). 2645 Scope *AtCatchParent = CurScope; 2646 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2647 AtCatchParent = AtCatchParent->getParent(); 2648 if (!AtCatchParent) 2649 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2650 } 2651 return BuildObjCAtThrowStmt(AtLoc, Throw); 2652} 2653 2654ExprResult 2655Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 2656 ExprResult result = DefaultLvalueConversion(operand); 2657 if (result.isInvalid()) 2658 return ExprError(); 2659 operand = result.take(); 2660 2661 // Make sure the expression type is an ObjC pointer or "void *". 2662 QualType type = operand->getType(); 2663 if (!type->isDependentType() && 2664 !type->isObjCObjectPointerType()) { 2665 const PointerType *pointerType = type->getAs<PointerType>(); 2666 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 2667 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 2668 << type << operand->getSourceRange(); 2669 } 2670 2671 // The operand to @synchronized is a full-expression. 2672 return ActOnFinishFullExpr(operand); 2673} 2674 2675StmtResult 2676Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2677 Stmt *SyncBody) { 2678 // We can't jump into or indirect-jump out of a @synchronized block. 2679 getCurFunction()->setHasBranchProtectedScope(); 2680 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2681} 2682 2683/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2684/// and creates a proper catch handler from them. 2685StmtResult 2686Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2687 Stmt *HandlerBlock) { 2688 // There's nothing to test that ActOnExceptionDecl didn't already test. 2689 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2690 cast_or_null<VarDecl>(ExDecl), 2691 HandlerBlock)); 2692} 2693 2694StmtResult 2695Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 2696 getCurFunction()->setHasBranchProtectedScope(); 2697 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 2698} 2699 2700namespace { 2701 2702class TypeWithHandler { 2703 QualType t; 2704 CXXCatchStmt *stmt; 2705public: 2706 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2707 : t(type), stmt(statement) {} 2708 2709 // An arbitrary order is fine as long as it places identical 2710 // types next to each other. 2711 bool operator<(const TypeWithHandler &y) const { 2712 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2713 return true; 2714 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2715 return false; 2716 else 2717 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2718 } 2719 2720 bool operator==(const TypeWithHandler& other) const { 2721 return t == other.t; 2722 } 2723 2724 CXXCatchStmt *getCatchStmt() const { return stmt; } 2725 SourceLocation getTypeSpecStartLoc() const { 2726 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2727 } 2728}; 2729 2730} 2731 2732/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2733/// handlers and creates a try statement from them. 2734StmtResult 2735Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2736 MultiStmtArg RawHandlers) { 2737 // Don't report an error if 'try' is used in system headers. 2738 if (!getLangOpts().CXXExceptions && 2739 !getSourceManager().isInSystemHeader(TryLoc)) 2740 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2741 2742 unsigned NumHandlers = RawHandlers.size(); 2743 assert(NumHandlers > 0 && 2744 "The parser shouldn't call this if there are no handlers."); 2745 Stmt **Handlers = RawHandlers.data(); 2746 2747 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2748 2749 for (unsigned i = 0; i < NumHandlers; ++i) { 2750 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 2751 if (!Handler->getExceptionDecl()) { 2752 if (i < NumHandlers - 1) 2753 return StmtError(Diag(Handler->getLocStart(), 2754 diag::err_early_catch_all)); 2755 2756 continue; 2757 } 2758 2759 const QualType CaughtType = Handler->getCaughtType(); 2760 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2761 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2762 } 2763 2764 // Detect handlers for the same type as an earlier one. 2765 if (NumHandlers > 1) { 2766 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2767 2768 TypeWithHandler prev = TypesWithHandlers[0]; 2769 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2770 TypeWithHandler curr = TypesWithHandlers[i]; 2771 2772 if (curr == prev) { 2773 Diag(curr.getTypeSpecStartLoc(), 2774 diag::warn_exception_caught_by_earlier_handler) 2775 << curr.getCatchStmt()->getCaughtType().getAsString(); 2776 Diag(prev.getTypeSpecStartLoc(), 2777 diag::note_previous_exception_handler) 2778 << prev.getCatchStmt()->getCaughtType().getAsString(); 2779 } 2780 2781 prev = curr; 2782 } 2783 } 2784 2785 getCurFunction()->setHasBranchProtectedScope(); 2786 2787 // FIXME: We should detect handlers that cannot catch anything because an 2788 // earlier handler catches a superclass. Need to find a method that is not 2789 // quadratic for this. 2790 // Neither of these are explicitly forbidden, but every compiler detects them 2791 // and warns. 2792 2793 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2794 llvm::makeArrayRef(Handlers, NumHandlers))); 2795} 2796 2797StmtResult 2798Sema::ActOnSEHTryBlock(bool IsCXXTry, 2799 SourceLocation TryLoc, 2800 Stmt *TryBlock, 2801 Stmt *Handler) { 2802 assert(TryBlock && Handler); 2803 2804 getCurFunction()->setHasBranchProtectedScope(); 2805 2806 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2807} 2808 2809StmtResult 2810Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2811 Expr *FilterExpr, 2812 Stmt *Block) { 2813 assert(FilterExpr && Block); 2814 2815 if(!FilterExpr->getType()->isIntegerType()) { 2816 return StmtError(Diag(FilterExpr->getExprLoc(), 2817 diag::err_filter_expression_integral) 2818 << FilterExpr->getType()); 2819 } 2820 2821 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2822} 2823 2824StmtResult 2825Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2826 Stmt *Block) { 2827 assert(Block); 2828 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2829} 2830 2831StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 2832 bool IsIfExists, 2833 NestedNameSpecifierLoc QualifierLoc, 2834 DeclarationNameInfo NameInfo, 2835 Stmt *Nested) 2836{ 2837 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 2838 QualifierLoc, NameInfo, 2839 cast<CompoundStmt>(Nested)); 2840} 2841 2842 2843StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 2844 bool IsIfExists, 2845 CXXScopeSpec &SS, 2846 UnqualifiedId &Name, 2847 Stmt *Nested) { 2848 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 2849 SS.getWithLocInContext(Context), 2850 GetNameFromUnqualifiedId(Name), 2851 Nested); 2852} 2853