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