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