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