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