SemaStmt.cpp revision 729b853f4bfa83e53c638a06a9dccf83b4e1f720
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/AST/APValue.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExprObjC.h" 23#include "clang/AST/StmtObjC.h" 24#include "clang/AST/StmtCXX.h" 25#include "clang/AST/TypeLoc.h" 26#include "clang/Lex/Preprocessor.h" 27#include "clang/Basic/TargetInfo.h" 28#include "llvm/ADT/ArrayRef.h" 29#include "llvm/ADT/STLExtras.h" 30#include "llvm/ADT/SmallVector.h" 31using namespace clang; 32using namespace sema; 33 34StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 35 Expr *E = expr.get(); 36 if (!E) // FIXME: FullExprArg has no error state? 37 return StmtError(); 38 39 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 40 // void expression for its side effects. Conversion to void allows any 41 // operand, even incomplete types. 42 43 // Same thing in for stmt first clause (when expr) and third clause. 44 return Owned(static_cast<Stmt*>(E)); 45} 46 47 48StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) { 49 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro)); 50} 51 52StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 53 SourceLocation EndLoc) { 54 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 55 56 // If we have an invalid decl, just return an error. 57 if (DG.isNull()) return StmtError(); 58 59 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 60} 61 62void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 63 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 64 65 // If we have an invalid decl, just return. 66 if (DG.isNull() || !DG.isSingleDecl()) return; 67 // suppress any potential 'unused variable' warning. 68 DG.getSingleDecl()->setUsed(); 69} 70 71void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 72 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 73 return DiagnoseUnusedExprResult(Label->getSubStmt()); 74 75 const Expr *E = dyn_cast_or_null<Expr>(S); 76 if (!E) 77 return; 78 79 if (E->isBoundMemberFunction(Context)) { 80 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func) 81 << E->getSourceRange(); 82 return; 83 } 84 85 SourceLocation Loc; 86 SourceRange R1, R2; 87 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 88 return; 89 90 // Okay, we have an unused result. Depending on what the base expression is, 91 // we might want to make a more specific diagnostic. Check for one of these 92 // cases now. 93 unsigned DiagID = diag::warn_unused_expr; 94 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 95 E = Temps->getSubExpr(); 96 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 97 E = TempExpr->getSubExpr(); 98 99 E = E->IgnoreParenImpCasts(); 100 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 101 if (E->getType()->isVoidType()) 102 return; 103 104 // If the callee has attribute pure, const, or warn_unused_result, warn with 105 // a more specific message to make it clear what is happening. 106 if (const Decl *FD = CE->getCalleeDecl()) { 107 if (FD->getAttr<WarnUnusedResultAttr>()) { 108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 109 return; 110 } 111 if (FD->getAttr<PureAttr>()) { 112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 113 return; 114 } 115 if (FD->getAttr<ConstAttr>()) { 116 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 117 return; 118 } 119 } 120 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 121 const ObjCMethodDecl *MD = ME->getMethodDecl(); 122 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 123 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 124 return; 125 } 126 } else if (isa<ObjCPropertyRefExpr>(E)) { 127 DiagID = diag::warn_unused_property_expr; 128 } else if (const CXXFunctionalCastExpr *FC 129 = dyn_cast<CXXFunctionalCastExpr>(E)) { 130 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 131 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 132 return; 133 } 134 // Diagnose "(void*) blah" as a typo for "(void) blah". 135 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 136 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 137 QualType T = TI->getType(); 138 139 // We really do want to use the non-canonical type here. 140 if (T == Context.VoidPtrTy) { 141 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 142 143 Diag(Loc, diag::warn_unused_voidptr) 144 << FixItHint::CreateRemoval(TL.getStarLoc()); 145 return; 146 } 147 } 148 149 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 150} 151 152StmtResult 153Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 154 MultiStmtArg elts, bool isStmtExpr) { 155 unsigned NumElts = elts.size(); 156 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 157 // If we're in C89 mode, check that we don't have any decls after stmts. If 158 // so, emit an extension diagnostic. 159 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 160 // Note that __extension__ can be around a decl. 161 unsigned i = 0; 162 // Skip over all declarations. 163 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 164 /*empty*/; 165 166 // We found the end of the list or a statement. Scan for another declstmt. 167 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 168 /*empty*/; 169 170 if (i != NumElts) { 171 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 172 Diag(D->getLocation(), diag::ext_mixed_decls_code); 173 } 174 } 175 // Warn about unused expressions in statements. 176 for (unsigned i = 0; i != NumElts; ++i) { 177 // Ignore statements that are last in a statement expression. 178 if (isStmtExpr && i == NumElts - 1) 179 continue; 180 181 DiagnoseUnusedExprResult(Elts[i]); 182 } 183 184 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 185} 186 187StmtResult 188Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 189 SourceLocation DotDotDotLoc, Expr *RHSVal, 190 SourceLocation ColonLoc) { 191 assert((LHSVal != 0) && "missing expression in case statement"); 192 193 // C99 6.8.4.2p3: The expression shall be an integer constant. 194 // However, GCC allows any evaluatable integer expression. 195 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 196 VerifyIntegerConstantExpression(LHSVal)) 197 return StmtError(); 198 199 // GCC extension: The expression shall be an integer constant. 200 201 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 202 VerifyIntegerConstantExpression(RHSVal)) { 203 RHSVal = 0; // Recover by just forgetting about it. 204 } 205 206 if (getCurFunction()->SwitchStack.empty()) { 207 Diag(CaseLoc, diag::err_case_not_in_switch); 208 return StmtError(); 209 } 210 211 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 212 ColonLoc); 213 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 214 return Owned(CS); 215} 216 217/// ActOnCaseStmtBody - This installs a statement as the body of a case. 218void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 219 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 220 CS->setSubStmt(SubStmt); 221} 222 223StmtResult 224Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 225 Stmt *SubStmt, Scope *CurScope) { 226 if (getCurFunction()->SwitchStack.empty()) { 227 Diag(DefaultLoc, diag::err_default_not_in_switch); 228 return Owned(SubStmt); 229 } 230 231 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 232 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 233 return Owned(DS); 234} 235 236StmtResult 237Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 238 SourceLocation ColonLoc, Stmt *SubStmt) { 239 240 // If the label was multiply defined, reject it now. 241 if (TheDecl->getStmt()) { 242 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 243 Diag(TheDecl->getLocation(), diag::note_previous_definition); 244 return Owned(SubStmt); 245 } 246 247 // Otherwise, things are good. Fill in the declaration and return it. 248 TheDecl->setLocation(IdentLoc); 249 250 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 251 TheDecl->setStmt(LS); 252 TheDecl->setLocation(IdentLoc); 253 return Owned(LS); 254} 255 256StmtResult 257Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 258 Stmt *thenStmt, SourceLocation ElseLoc, 259 Stmt *elseStmt) { 260 ExprResult CondResult(CondVal.release()); 261 262 VarDecl *ConditionVar = 0; 263 if (CondVar) { 264 ConditionVar = cast<VarDecl>(CondVar); 265 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 266 if (CondResult.isInvalid()) 267 return StmtError(); 268 } 269 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 270 if (!ConditionExpr) 271 return StmtError(); 272 273 DiagnoseUnusedExprResult(thenStmt); 274 275 // Warn if the if block has a null body without an else value. 276 // this helps prevent bugs due to typos, such as 277 // if (condition); 278 // do_stuff(); 279 // 280 if (!elseStmt) { 281 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 282 // But do not warn if the body is a macro that expands to nothing, e.g: 283 // 284 // #define CALL(x) 285 // if (condition) 286 // CALL(0); 287 // 288 if (!stmt->hasLeadingEmptyMacro()) 289 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 290 } 291 292 DiagnoseUnusedExprResult(elseStmt); 293 294 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 295 thenStmt, ElseLoc, elseStmt)); 296} 297 298/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 299/// the specified width and sign. If an overflow occurs, detect it and emit 300/// the specified diagnostic. 301void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 302 unsigned NewWidth, bool NewSign, 303 SourceLocation Loc, 304 unsigned DiagID) { 305 // Perform a conversion to the promoted condition type if needed. 306 if (NewWidth > Val.getBitWidth()) { 307 // If this is an extension, just do it. 308 Val = Val.extend(NewWidth); 309 Val.setIsSigned(NewSign); 310 311 // If the input was signed and negative and the output is 312 // unsigned, don't bother to warn: this is implementation-defined 313 // behavior. 314 // FIXME: Introduce a second, default-ignored warning for this case? 315 } else if (NewWidth < Val.getBitWidth()) { 316 // If this is a truncation, check for overflow. 317 llvm::APSInt ConvVal(Val); 318 ConvVal = ConvVal.trunc(NewWidth); 319 ConvVal.setIsSigned(NewSign); 320 ConvVal = ConvVal.extend(Val.getBitWidth()); 321 ConvVal.setIsSigned(Val.isSigned()); 322 if (ConvVal != Val) 323 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 324 325 // Regardless of whether a diagnostic was emitted, really do the 326 // truncation. 327 Val = Val.trunc(NewWidth); 328 Val.setIsSigned(NewSign); 329 } else if (NewSign != Val.isSigned()) { 330 // Convert the sign to match the sign of the condition. This can cause 331 // overflow as well: unsigned(INTMIN) 332 // We don't diagnose this overflow, because it is implementation-defined 333 // behavior. 334 // FIXME: Introduce a second, default-ignored warning for this case? 335 llvm::APSInt OldVal(Val); 336 Val.setIsSigned(NewSign); 337 } 338} 339 340namespace { 341 struct CaseCompareFunctor { 342 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 343 const llvm::APSInt &RHS) { 344 return LHS.first < RHS; 345 } 346 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 347 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 348 return LHS.first < RHS.first; 349 } 350 bool operator()(const llvm::APSInt &LHS, 351 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 352 return LHS < RHS.first; 353 } 354 }; 355} 356 357/// CmpCaseVals - Comparison predicate for sorting case values. 358/// 359static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 360 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 361 if (lhs.first < rhs.first) 362 return true; 363 364 if (lhs.first == rhs.first && 365 lhs.second->getCaseLoc().getRawEncoding() 366 < rhs.second->getCaseLoc().getRawEncoding()) 367 return true; 368 return false; 369} 370 371/// CmpEnumVals - Comparison predicate for sorting enumeration values. 372/// 373static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 374 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 375{ 376 return lhs.first < rhs.first; 377} 378 379/// EqEnumVals - Comparison preficate for uniqing enumeration values. 380/// 381static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 382 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 383{ 384 return lhs.first == rhs.first; 385} 386 387/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 388/// potentially integral-promoted expression @p expr. 389static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) { 390 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) { 391 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr(); 392 QualType TypeBeforePromotion = ExprBeforePromotion->getType(); 393 if (TypeBeforePromotion->isIntegralOrEnumerationType()) { 394 return TypeBeforePromotion; 395 } 396 } 397 return expr->getType(); 398} 399 400StmtResult 401Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 402 Decl *CondVar) { 403 ExprResult CondResult; 404 405 VarDecl *ConditionVar = 0; 406 if (CondVar) { 407 ConditionVar = cast<VarDecl>(CondVar); 408 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 409 if (CondResult.isInvalid()) 410 return StmtError(); 411 412 Cond = CondResult.release(); 413 } 414 415 if (!Cond) 416 return StmtError(); 417 418 CondResult 419 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, 420 PDiag(diag::err_typecheck_statement_requires_integer), 421 PDiag(diag::err_switch_incomplete_class_type) 422 << Cond->getSourceRange(), 423 PDiag(diag::err_switch_explicit_conversion), 424 PDiag(diag::note_switch_conversion), 425 PDiag(diag::err_switch_multiple_conversions), 426 PDiag(diag::note_switch_conversion), 427 PDiag(0)); 428 if (CondResult.isInvalid()) return StmtError(); 429 Cond = CondResult.take(); 430 431 if (!CondVar) { 432 CheckImplicitConversions(Cond, SwitchLoc); 433 CondResult = MaybeCreateExprWithCleanups(Cond); 434 if (CondResult.isInvalid()) 435 return StmtError(); 436 Cond = CondResult.take(); 437 } 438 439 getCurFunction()->setHasBranchIntoScope(); 440 441 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 442 getCurFunction()->SwitchStack.push_back(SS); 443 return Owned(SS); 444} 445 446static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 447 if (Val.getBitWidth() < BitWidth) 448 Val = Val.extend(BitWidth); 449 else if (Val.getBitWidth() > BitWidth) 450 Val = Val.trunc(BitWidth); 451 Val.setIsSigned(IsSigned); 452} 453 454StmtResult 455Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 456 Stmt *BodyStmt) { 457 SwitchStmt *SS = cast<SwitchStmt>(Switch); 458 assert(SS == getCurFunction()->SwitchStack.back() && 459 "switch stack missing push/pop!"); 460 461 SS->setBody(BodyStmt, SwitchLoc); 462 getCurFunction()->SwitchStack.pop_back(); 463 464 if (SS->getCond() == 0) 465 return StmtError(); 466 467 Expr *CondExpr = SS->getCond(); 468 Expr *CondExprBeforePromotion = CondExpr; 469 QualType CondTypeBeforePromotion = 470 GetTypeBeforeIntegralPromotion(CondExpr); 471 472 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 473 UsualUnaryConversions(CondExpr); 474 QualType CondType = CondExpr->getType(); 475 SS->setCond(CondExpr); 476 477 // C++ 6.4.2.p2: 478 // Integral promotions are performed (on the switch condition). 479 // 480 // A case value unrepresentable by the original switch condition 481 // type (before the promotion) doesn't make sense, even when it can 482 // be represented by the promoted type. Therefore we need to find 483 // the pre-promotion type of the switch condition. 484 if (!CondExpr->isTypeDependent()) { 485 // We have already converted the expression to an integral or enumeration 486 // type, when we started the switch statement. If we don't have an 487 // appropriate type now, just return an error. 488 if (!CondType->isIntegralOrEnumerationType()) 489 return StmtError(); 490 491 if (CondExpr->isKnownToHaveBooleanValue()) { 492 // switch(bool_expr) {...} is often a programmer error, e.g. 493 // switch(n && mask) { ... } // Doh - should be "n & mask". 494 // One can always use an if statement instead of switch(bool_expr). 495 Diag(SwitchLoc, diag::warn_bool_switch_condition) 496 << CondExpr->getSourceRange(); 497 } 498 } 499 500 // Get the bitwidth of the switched-on value before promotions. We must 501 // convert the integer case values to this width before comparison. 502 bool HasDependentValue 503 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 504 unsigned CondWidth 505 = HasDependentValue? 0 506 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion)); 507 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType(); 508 509 // Accumulate all of the case values in a vector so that we can sort them 510 // and detect duplicates. This vector contains the APInt for the case after 511 // it has been converted to the condition type. 512 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 513 CaseValsTy CaseVals; 514 515 // Keep track of any GNU case ranges we see. The APSInt is the low value. 516 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 517 CaseRangesTy CaseRanges; 518 519 DefaultStmt *TheDefaultStmt = 0; 520 521 bool CaseListIsErroneous = false; 522 523 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 524 SC = SC->getNextSwitchCase()) { 525 526 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 527 if (TheDefaultStmt) { 528 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 529 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 530 531 // FIXME: Remove the default statement from the switch block so that 532 // we'll return a valid AST. This requires recursing down the AST and 533 // finding it, not something we are set up to do right now. For now, 534 // just lop the entire switch stmt out of the AST. 535 CaseListIsErroneous = true; 536 } 537 TheDefaultStmt = DS; 538 539 } else { 540 CaseStmt *CS = cast<CaseStmt>(SC); 541 542 // We already verified that the expression has a i-c-e value (C99 543 // 6.8.4.2p3) - get that value now. 544 Expr *Lo = CS->getLHS(); 545 546 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 547 HasDependentValue = true; 548 break; 549 } 550 551 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 552 553 // Convert the value to the same width/sign as the condition. 554 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 555 Lo->getLocStart(), 556 diag::warn_case_value_overflow); 557 558 // If the LHS is not the same type as the condition, insert an implicit 559 // cast. 560 ImpCastExprToType(Lo, CondType, CK_IntegralCast); 561 CS->setLHS(Lo); 562 563 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 564 if (CS->getRHS()) { 565 if (CS->getRHS()->isTypeDependent() || 566 CS->getRHS()->isValueDependent()) { 567 HasDependentValue = true; 568 break; 569 } 570 CaseRanges.push_back(std::make_pair(LoVal, CS)); 571 } else 572 CaseVals.push_back(std::make_pair(LoVal, CS)); 573 } 574 } 575 576 if (!HasDependentValue) { 577 // If we don't have a default statement, check whether the 578 // condition is constant. 579 llvm::APSInt ConstantCondValue; 580 bool HasConstantCond = false; 581 bool ShouldCheckConstantCond = false; 582 if (!HasDependentValue && !TheDefaultStmt) { 583 Expr::EvalResult Result; 584 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context); 585 if (HasConstantCond) { 586 assert(Result.Val.isInt() && "switch condition evaluated to non-int"); 587 ConstantCondValue = Result.Val.getInt(); 588 ShouldCheckConstantCond = true; 589 590 assert(ConstantCondValue.getBitWidth() == CondWidth && 591 ConstantCondValue.isSigned() == CondIsSigned); 592 } 593 } 594 595 // Sort all the scalar case values so we can easily detect duplicates. 596 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 597 598 if (!CaseVals.empty()) { 599 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 600 if (ShouldCheckConstantCond && 601 CaseVals[i].first == ConstantCondValue) 602 ShouldCheckConstantCond = false; 603 604 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 605 // If we have a duplicate, report it. 606 Diag(CaseVals[i].second->getLHS()->getLocStart(), 607 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 608 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 609 diag::note_duplicate_case_prev); 610 // FIXME: We really want to remove the bogus case stmt from the 611 // substmt, but we have no way to do this right now. 612 CaseListIsErroneous = true; 613 } 614 } 615 } 616 617 // Detect duplicate case ranges, which usually don't exist at all in 618 // the first place. 619 if (!CaseRanges.empty()) { 620 // Sort all the case ranges by their low value so we can easily detect 621 // overlaps between ranges. 622 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 623 624 // Scan the ranges, computing the high values and removing empty ranges. 625 std::vector<llvm::APSInt> HiVals; 626 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 627 llvm::APSInt &LoVal = CaseRanges[i].first; 628 CaseStmt *CR = CaseRanges[i].second; 629 Expr *Hi = CR->getRHS(); 630 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 631 632 // Convert the value to the same width/sign as the condition. 633 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 634 Hi->getLocStart(), 635 diag::warn_case_value_overflow); 636 637 // If the LHS is not the same type as the condition, insert an implicit 638 // cast. 639 ImpCastExprToType(Hi, CondType, CK_IntegralCast); 640 CR->setRHS(Hi); 641 642 // If the low value is bigger than the high value, the case is empty. 643 if (LoVal > HiVal) { 644 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 645 << SourceRange(CR->getLHS()->getLocStart(), 646 Hi->getLocEnd()); 647 CaseRanges.erase(CaseRanges.begin()+i); 648 --i, --e; 649 continue; 650 } 651 652 if (ShouldCheckConstantCond && 653 LoVal <= ConstantCondValue && 654 ConstantCondValue <= HiVal) 655 ShouldCheckConstantCond = false; 656 657 HiVals.push_back(HiVal); 658 } 659 660 // Rescan the ranges, looking for overlap with singleton values and other 661 // ranges. Since the range list is sorted, we only need to compare case 662 // ranges with their neighbors. 663 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 664 llvm::APSInt &CRLo = CaseRanges[i].first; 665 llvm::APSInt &CRHi = HiVals[i]; 666 CaseStmt *CR = CaseRanges[i].second; 667 668 // Check to see whether the case range overlaps with any 669 // singleton cases. 670 CaseStmt *OverlapStmt = 0; 671 llvm::APSInt OverlapVal(32); 672 673 // Find the smallest value >= the lower bound. If I is in the 674 // case range, then we have overlap. 675 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 676 CaseVals.end(), CRLo, 677 CaseCompareFunctor()); 678 if (I != CaseVals.end() && I->first < CRHi) { 679 OverlapVal = I->first; // Found overlap with scalar. 680 OverlapStmt = I->second; 681 } 682 683 // Find the smallest value bigger than the upper bound. 684 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 685 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 686 OverlapVal = (I-1)->first; // Found overlap with scalar. 687 OverlapStmt = (I-1)->second; 688 } 689 690 // Check to see if this case stmt overlaps with the subsequent 691 // case range. 692 if (i && CRLo <= HiVals[i-1]) { 693 OverlapVal = HiVals[i-1]; // Found overlap with range. 694 OverlapStmt = CaseRanges[i-1].second; 695 } 696 697 if (OverlapStmt) { 698 // If we have a duplicate, report it. 699 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 700 << OverlapVal.toString(10); 701 Diag(OverlapStmt->getLHS()->getLocStart(), 702 diag::note_duplicate_case_prev); 703 // FIXME: We really want to remove the bogus case stmt from the 704 // substmt, but we have no way to do this right now. 705 CaseListIsErroneous = true; 706 } 707 } 708 } 709 710 // Complain if we have a constant condition and we didn't find a match. 711 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 712 // TODO: it would be nice if we printed enums as enums, chars as 713 // chars, etc. 714 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 715 << ConstantCondValue.toString(10) 716 << CondExpr->getSourceRange(); 717 } 718 719 // Check to see if switch is over an Enum and handles all of its 720 // values. We only issue a warning if there is not 'default:', but 721 // we still do the analysis to preserve this information in the AST 722 // (which can be used by flow-based analyes). 723 // 724 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 725 726 // If switch has default case, then ignore it. 727 if (!CaseListIsErroneous && !HasConstantCond && ET) { 728 const EnumDecl *ED = ET->getDecl(); 729 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; 730 EnumValsTy EnumVals; 731 732 // Gather all enum values, set their type and sort them, 733 // allowing easier comparison with CaseVals. 734 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 735 EDI != ED->enumerator_end(); ++EDI) { 736 llvm::APSInt Val = EDI->getInitVal(); 737 AdjustAPSInt(Val, CondWidth, CondIsSigned); 738 EnumVals.push_back(std::make_pair(Val, *EDI)); 739 } 740 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 741 EnumValsTy::iterator EIend = 742 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 743 744 // See which case values aren't in enum. 745 // TODO: we might want to check whether case values are out of the 746 // enum even if we don't want to check whether all cases are handled. 747 if (!TheDefaultStmt) { 748 EnumValsTy::const_iterator EI = EnumVals.begin(); 749 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 750 CI != CaseVals.end(); CI++) { 751 while (EI != EIend && EI->first < CI->first) 752 EI++; 753 if (EI == EIend || EI->first > CI->first) 754 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 755 << ED->getDeclName(); 756 } 757 // See which of case ranges aren't in enum 758 EI = EnumVals.begin(); 759 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 760 RI != CaseRanges.end() && EI != EIend; RI++) { 761 while (EI != EIend && EI->first < RI->first) 762 EI++; 763 764 if (EI == EIend || EI->first != RI->first) { 765 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 766 << ED->getDeclName(); 767 } 768 769 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 770 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 771 while (EI != EIend && EI->first < Hi) 772 EI++; 773 if (EI == EIend || EI->first != Hi) 774 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 775 << ED->getDeclName(); 776 } 777 } 778 779 // Check which enum vals aren't in switch 780 CaseValsTy::const_iterator CI = CaseVals.begin(); 781 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 782 bool hasCasesNotInSwitch = false; 783 784 llvm::SmallVector<DeclarationName,8> UnhandledNames; 785 786 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 787 // Drop unneeded case values 788 llvm::APSInt CIVal; 789 while (CI != CaseVals.end() && CI->first < EI->first) 790 CI++; 791 792 if (CI != CaseVals.end() && CI->first == EI->first) 793 continue; 794 795 // Drop unneeded case ranges 796 for (; RI != CaseRanges.end(); RI++) { 797 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 798 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 799 if (EI->first <= Hi) 800 break; 801 } 802 803 if (RI == CaseRanges.end() || EI->first < RI->first) { 804 hasCasesNotInSwitch = true; 805 if (!TheDefaultStmt) 806 UnhandledNames.push_back(EI->second->getDeclName()); 807 } 808 } 809 810 // Produce a nice diagnostic if multiple values aren't handled. 811 switch (UnhandledNames.size()) { 812 case 0: break; 813 case 1: 814 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 815 << UnhandledNames[0]; 816 break; 817 case 2: 818 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 819 << UnhandledNames[0] << UnhandledNames[1]; 820 break; 821 case 3: 822 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 823 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 824 break; 825 default: 826 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 827 << (unsigned)UnhandledNames.size() 828 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 829 break; 830 } 831 832 if (!hasCasesNotInSwitch) 833 SS->setAllEnumCasesCovered(); 834 } 835 } 836 837 // FIXME: If the case list was broken is some way, we don't have a good system 838 // to patch it up. Instead, just return the whole substmt as broken. 839 if (CaseListIsErroneous) 840 return StmtError(); 841 842 return Owned(SS); 843} 844 845StmtResult 846Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 847 Decl *CondVar, Stmt *Body) { 848 ExprResult CondResult(Cond.release()); 849 850 VarDecl *ConditionVar = 0; 851 if (CondVar) { 852 ConditionVar = cast<VarDecl>(CondVar); 853 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 854 if (CondResult.isInvalid()) 855 return StmtError(); 856 } 857 Expr *ConditionExpr = CondResult.take(); 858 if (!ConditionExpr) 859 return StmtError(); 860 861 DiagnoseUnusedExprResult(Body); 862 863 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 864 Body, WhileLoc)); 865} 866 867StmtResult 868Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 869 SourceLocation WhileLoc, SourceLocation CondLParen, 870 Expr *Cond, SourceLocation CondRParen) { 871 assert(Cond && "ActOnDoStmt(): missing expression"); 872 873 if (CheckBooleanCondition(Cond, DoLoc)) 874 return StmtError(); 875 876 CheckImplicitConversions(Cond, DoLoc); 877 ExprResult CondResult = MaybeCreateExprWithCleanups(Cond); 878 if (CondResult.isInvalid()) 879 return StmtError(); 880 Cond = CondResult.take(); 881 882 DiagnoseUnusedExprResult(Body); 883 884 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 885} 886 887StmtResult 888Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 889 Stmt *First, FullExprArg second, Decl *secondVar, 890 FullExprArg third, 891 SourceLocation RParenLoc, Stmt *Body) { 892 if (!getLangOptions().CPlusPlus) { 893 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 894 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 895 // declare identifiers for objects having storage class 'auto' or 896 // 'register'. 897 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 898 DI!=DE; ++DI) { 899 VarDecl *VD = dyn_cast<VarDecl>(*DI); 900 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 901 VD = 0; 902 if (VD == 0) 903 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 904 // FIXME: mark decl erroneous! 905 } 906 } 907 } 908 909 ExprResult SecondResult(second.release()); 910 VarDecl *ConditionVar = 0; 911 if (secondVar) { 912 ConditionVar = cast<VarDecl>(secondVar); 913 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 914 if (SecondResult.isInvalid()) 915 return StmtError(); 916 } 917 918 Expr *Third = third.release().takeAs<Expr>(); 919 920 DiagnoseUnusedExprResult(First); 921 DiagnoseUnusedExprResult(Third); 922 DiagnoseUnusedExprResult(Body); 923 924 return Owned(new (Context) ForStmt(Context, First, 925 SecondResult.take(), ConditionVar, 926 Third, Body, ForLoc, LParenLoc, 927 RParenLoc)); 928} 929 930/// In an Objective C collection iteration statement: 931/// for (x in y) 932/// x can be an arbitrary l-value expression. Bind it up as a 933/// full-expression. 934StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 935 CheckImplicitConversions(E); 936 ExprResult Result = MaybeCreateExprWithCleanups(E); 937 if (Result.isInvalid()) return StmtError(); 938 return Owned(static_cast<Stmt*>(Result.get())); 939} 940 941StmtResult 942Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 943 SourceLocation LParenLoc, 944 Stmt *First, Expr *Second, 945 SourceLocation RParenLoc, Stmt *Body) { 946 if (First) { 947 QualType FirstType; 948 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 949 if (!DS->isSingleDecl()) 950 return StmtError(Diag((*DS->decl_begin())->getLocation(), 951 diag::err_toomany_element_decls)); 952 953 Decl *D = DS->getSingleDecl(); 954 FirstType = cast<ValueDecl>(D)->getType(); 955 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 956 // declare identifiers for objects having storage class 'auto' or 957 // 'register'. 958 VarDecl *VD = cast<VarDecl>(D); 959 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) 960 return StmtError(Diag(VD->getLocation(), 961 diag::err_non_variable_decl_in_for)); 962 } else { 963 Expr *FirstE = cast<Expr>(First); 964 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 965 return StmtError(Diag(First->getLocStart(), 966 diag::err_selector_element_not_lvalue) 967 << First->getSourceRange()); 968 969 FirstType = static_cast<Expr*>(First)->getType(); 970 } 971 if (!FirstType->isDependentType() && 972 !FirstType->isObjCObjectPointerType() && 973 !FirstType->isBlockPointerType()) 974 Diag(ForLoc, diag::err_selector_element_type) 975 << FirstType << First->getSourceRange(); 976 } 977 if (Second && !Second->isTypeDependent()) { 978 DefaultFunctionArrayLvalueConversion(Second); 979 QualType SecondType = Second->getType(); 980 if (!SecondType->isObjCObjectPointerType()) 981 Diag(ForLoc, diag::err_collection_expr_type) 982 << SecondType << Second->getSourceRange(); 983 else if (const ObjCObjectPointerType *OPT = 984 SecondType->getAsObjCInterfacePointerType()) { 985 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents; 986 IdentifierInfo* selIdent = 987 &Context.Idents.get("countByEnumeratingWithState"); 988 KeyIdents.push_back(selIdent); 989 selIdent = &Context.Idents.get("objects"); 990 KeyIdents.push_back(selIdent); 991 selIdent = &Context.Idents.get("count"); 992 KeyIdents.push_back(selIdent); 993 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]); 994 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) { 995 if (!IDecl->isForwardDecl() && 996 !IDecl->lookupInstanceMethod(CSelector)) { 997 // Must further look into private implementation methods. 998 if (!LookupPrivateInstanceMethod(CSelector, IDecl)) 999 Diag(ForLoc, diag::warn_collection_expr_type) 1000 << SecondType << CSelector << Second->getSourceRange(); 1001 } 1002 } 1003 } 1004 } 1005 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1006 ForLoc, RParenLoc)); 1007} 1008 1009StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1010 SourceLocation LabelLoc, 1011 LabelDecl *TheDecl) { 1012 getCurFunction()->setHasBranchIntoScope(); 1013 TheDecl->setUsed(); 1014 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1015} 1016 1017StmtResult 1018Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1019 Expr *E) { 1020 // Convert operand to void* 1021 if (!E->isTypeDependent()) { 1022 QualType ETy = E->getType(); 1023 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1024 AssignConvertType ConvTy = 1025 CheckSingleAssignmentConstraints(DestTy, E); 1026 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1027 return StmtError(); 1028 } 1029 1030 getCurFunction()->setHasIndirectGoto(); 1031 1032 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1033} 1034 1035StmtResult 1036Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1037 Scope *S = CurScope->getContinueParent(); 1038 if (!S) { 1039 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1040 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1041 } 1042 1043 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1044} 1045 1046StmtResult 1047Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1048 Scope *S = CurScope->getBreakParent(); 1049 if (!S) { 1050 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1051 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1052 } 1053 1054 return Owned(new (Context) BreakStmt(BreakLoc)); 1055} 1056 1057/// \brief Determine whether the given expression is a candidate for 1058/// copy elision in either a return statement or a throw expression. 1059/// 1060/// \param ReturnType If we're determining the copy elision candidate for 1061/// a return statement, this is the return type of the function. If we're 1062/// determining the copy elision candidate for a throw expression, this will 1063/// be a NULL type. 1064/// 1065/// \param E The expression being returned from the function or block, or 1066/// being thrown. 1067/// 1068/// \param AllowFunctionParameter 1069/// 1070/// \returns The NRVO candidate variable, if the return statement may use the 1071/// NRVO, or NULL if there is no such candidate. 1072const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1073 Expr *E, 1074 bool AllowFunctionParameter) { 1075 QualType ExprType = E->getType(); 1076 // - in a return statement in a function with ... 1077 // ... a class return type ... 1078 if (!ReturnType.isNull()) { 1079 if (!ReturnType->isRecordType()) 1080 return 0; 1081 // ... the same cv-unqualified type as the function return type ... 1082 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1083 return 0; 1084 } 1085 1086 // ... the expression is the name of a non-volatile automatic object 1087 // (other than a function or catch-clause parameter)) ... 1088 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1089 if (!DR) 1090 return 0; 1091 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1092 if (!VD) 1093 return 0; 1094 1095 if (VD->hasLocalStorage() && !VD->isExceptionVariable() && 1096 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1097 !VD->getType().isVolatileQualified() && 1098 ((VD->getKind() == Decl::Var) || 1099 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar))) 1100 return VD; 1101 1102 return 0; 1103} 1104 1105/// \brief Perform the initialization of a potentially-movable value, which 1106/// is the result of return value. 1107/// 1108/// This routine implements C++0x [class.copy]p33, which attempts to treat 1109/// returned lvalues as rvalues in certain cases (to prefer move construction), 1110/// then falls back to treating them as lvalues if that failed. 1111ExprResult 1112Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1113 const VarDecl *NRVOCandidate, 1114 QualType ResultType, 1115 Expr *Value) { 1116 // C++0x [class.copy]p33: 1117 // When the criteria for elision of a copy operation are met or would 1118 // be met save for the fact that the source object is a function 1119 // parameter, and the object to be copied is designated by an lvalue, 1120 // overload resolution to select the constructor for the copy is first 1121 // performed as if the object were designated by an rvalue. 1122 ExprResult Res = ExprError(); 1123 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) { 1124 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1125 Value->getType(), CK_LValueToRValue, 1126 Value, VK_XValue); 1127 1128 Expr *InitExpr = &AsRvalue; 1129 InitializationKind Kind 1130 = InitializationKind::CreateCopy(Value->getLocStart(), 1131 Value->getLocStart()); 1132 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1133 1134 // [...] If overload resolution fails, or if the type of the first 1135 // parameter of the selected constructor is not an rvalue reference 1136 // to the object's type (possibly cv-qualified), overload resolution 1137 // is performed again, considering the object as an lvalue. 1138 if (Seq.getKind() != InitializationSequence::FailedSequence) { 1139 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1140 StepEnd = Seq.step_end(); 1141 Step != StepEnd; ++Step) { 1142 if (Step->Kind 1143 != InitializationSequence::SK_ConstructorInitialization) 1144 continue; 1145 1146 CXXConstructorDecl *Constructor 1147 = cast<CXXConstructorDecl>(Step->Function.Function); 1148 1149 const RValueReferenceType *RRefType 1150 = Constructor->getParamDecl(0)->getType() 1151 ->getAs<RValueReferenceType>(); 1152 1153 // If we don't meet the criteria, break out now. 1154 if (!RRefType || 1155 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1156 Context.getTypeDeclType(Constructor->getParent()))) 1157 break; 1158 1159 // Promote "AsRvalue" to the heap, since we now need this 1160 // expression node to persist. 1161 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1162 CK_LValueToRValue, Value, 0, 1163 VK_XValue); 1164 1165 // Complete type-checking the initialization of the return type 1166 // using the constructor we found. 1167 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1168 } 1169 } 1170 } 1171 1172 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1173 // above, or overload resolution failed. Either way, we need to try 1174 // (again) now with the return value expression as written. 1175 if (Res.isInvalid()) 1176 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1177 1178 return Res; 1179} 1180 1181/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1182/// 1183StmtResult 1184Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1185 // If this is the first return we've seen in the block, infer the type of 1186 // the block from it. 1187 BlockScopeInfo *CurBlock = getCurBlock(); 1188 if (CurBlock->ReturnType.isNull()) { 1189 if (RetValExp) { 1190 // Don't call UsualUnaryConversions(), since we don't want to do 1191 // integer promotions here. 1192 DefaultFunctionArrayLvalueConversion(RetValExp); 1193 CurBlock->ReturnType = RetValExp->getType(); 1194 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1195 // We have to remove a 'const' added to copied-in variable which was 1196 // part of the implementation spec. and not the actual qualifier for 1197 // the variable. 1198 if (CDRE->isConstQualAdded()) 1199 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1200 } 1201 } else 1202 CurBlock->ReturnType = Context.VoidTy; 1203 } 1204 QualType FnRetType = CurBlock->ReturnType; 1205 1206 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1207 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1208 << getCurFunctionOrMethodDecl()->getDeclName(); 1209 return StmtError(); 1210 } 1211 1212 // Otherwise, verify that this result type matches the previous one. We are 1213 // pickier with blocks than for normal functions because we don't have GCC 1214 // compatibility to worry about here. 1215 ReturnStmt *Result = 0; 1216 if (CurBlock->ReturnType->isVoidType()) { 1217 if (RetValExp) { 1218 Diag(ReturnLoc, diag::err_return_block_has_expr); 1219 RetValExp = 0; 1220 } 1221 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1222 } else if (!RetValExp) { 1223 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1224 } else { 1225 const VarDecl *NRVOCandidate = 0; 1226 1227 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1228 // we have a non-void block with an expression, continue checking 1229 1230 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1231 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1232 // function return. 1233 1234 // In C++ the return statement is handled via a copy initialization. 1235 // the C version of which boils down to CheckSingleAssignmentConstraints. 1236 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1237 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1238 FnRetType, 1239 NRVOCandidate != 0); 1240 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1241 FnRetType, RetValExp); 1242 if (Res.isInvalid()) { 1243 // FIXME: Cleanup temporaries here, anyway? 1244 return StmtError(); 1245 } 1246 1247 if (RetValExp) { 1248 CheckImplicitConversions(RetValExp, ReturnLoc); 1249 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1250 } 1251 1252 RetValExp = Res.takeAs<Expr>(); 1253 if (RetValExp) 1254 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1255 } 1256 1257 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1258 } 1259 1260 // If we need to check for the named return value optimization, save the 1261 // return statement in our scope for later processing. 1262 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1263 !CurContext->isDependentContext()) 1264 FunctionScopes.back()->Returns.push_back(Result); 1265 1266 return Owned(Result); 1267} 1268 1269StmtResult 1270Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1271 if (getCurBlock()) 1272 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1273 1274 QualType FnRetType; 1275 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1276 FnRetType = FD->getResultType(); 1277 if (FD->hasAttr<NoReturnAttr>() || 1278 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1279 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1280 << getCurFunctionOrMethodDecl()->getDeclName(); 1281 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1282 FnRetType = MD->getResultType(); 1283 else // If we don't have a function/method context, bail. 1284 return StmtError(); 1285 1286 ReturnStmt *Result = 0; 1287 if (FnRetType->isVoidType()) { 1288 if (RetValExp && !RetValExp->isTypeDependent()) { 1289 // C99 6.8.6.4p1 (ext_ since GCC warns) 1290 unsigned D = diag::ext_return_has_expr; 1291 if (RetValExp->getType()->isVoidType()) 1292 D = diag::ext_return_has_void_expr; 1293 else { 1294 IgnoredValueConversions(RetValExp); 1295 ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid); 1296 } 1297 1298 // return (some void expression); is legal in C++. 1299 if (D != diag::ext_return_has_void_expr || 1300 !getLangOptions().CPlusPlus) { 1301 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1302 Diag(ReturnLoc, D) 1303 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1304 << RetValExp->getSourceRange(); 1305 } 1306 1307 CheckImplicitConversions(RetValExp, ReturnLoc); 1308 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1309 } 1310 1311 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1312 } else if (!RetValExp && !FnRetType->isDependentType()) { 1313 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1314 // C99 6.8.6.4p1 (ext_ since GCC warns) 1315 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1316 1317 if (FunctionDecl *FD = getCurFunctionDecl()) 1318 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1319 else 1320 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1321 Result = new (Context) ReturnStmt(ReturnLoc); 1322 } else { 1323 const VarDecl *NRVOCandidate = 0; 1324 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1325 // we have a non-void function with an expression, continue checking 1326 1327 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1328 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1329 // function return. 1330 1331 // In C++ the return statement is handled via a copy initialization. 1332 // the C version of which boils down to CheckSingleAssignmentConstraints. 1333 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1334 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1335 FnRetType, 1336 NRVOCandidate != 0); 1337 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1338 FnRetType, RetValExp); 1339 if (Res.isInvalid()) { 1340 // FIXME: Cleanup temporaries here, anyway? 1341 return StmtError(); 1342 } 1343 1344 RetValExp = Res.takeAs<Expr>(); 1345 if (RetValExp) 1346 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1347 } 1348 1349 if (RetValExp) { 1350 CheckImplicitConversions(RetValExp, ReturnLoc); 1351 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1352 } 1353 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1354 } 1355 1356 // If we need to check for the named return value optimization, save the 1357 // return statement in our scope for later processing. 1358 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1359 !CurContext->isDependentContext()) 1360 FunctionScopes.back()->Returns.push_back(Result); 1361 1362 return Owned(Result); 1363} 1364 1365/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1366/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1367/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1368/// provide a strong guidance to not use it. 1369/// 1370/// This method checks to see if the argument is an acceptable l-value and 1371/// returns false if it is a case we can handle. 1372static bool CheckAsmLValue(const Expr *E, Sema &S) { 1373 // Type dependent expressions will be checked during instantiation. 1374 if (E->isTypeDependent()) 1375 return false; 1376 1377 if (E->isLValue()) 1378 return false; // Cool, this is an lvalue. 1379 1380 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1381 // are supposed to allow. 1382 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1383 if (E != E2 && E2->isLValue()) { 1384 if (!S.getLangOptions().HeinousExtensions) 1385 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1386 << E->getSourceRange(); 1387 else 1388 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1389 << E->getSourceRange(); 1390 // Accept, even if we emitted an error diagnostic. 1391 return false; 1392 } 1393 1394 // None of the above, just randomly invalid non-lvalue. 1395 return true; 1396} 1397 1398/// isOperandMentioned - Return true if the specified operand # is mentioned 1399/// anywhere in the decomposed asm string. 1400static bool isOperandMentioned(unsigned OpNo, 1401 llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 1402 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 1403 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 1404 if (!Piece.isOperand()) continue; 1405 1406 // If this is a reference to the input and if the input was the smaller 1407 // one, then we have to reject this asm. 1408 if (Piece.getOperandNo() == OpNo) 1409 return true; 1410 } 1411 1412 return false; 1413} 1414 1415StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 1416 bool IsVolatile, unsigned NumOutputs, 1417 unsigned NumInputs, IdentifierInfo **Names, 1418 MultiExprArg constraints, MultiExprArg exprs, 1419 Expr *asmString, MultiExprArg clobbers, 1420 SourceLocation RParenLoc, bool MSAsm) { 1421 unsigned NumClobbers = clobbers.size(); 1422 StringLiteral **Constraints = 1423 reinterpret_cast<StringLiteral**>(constraints.get()); 1424 Expr **Exprs = exprs.get(); 1425 StringLiteral *AsmString = cast<StringLiteral>(asmString); 1426 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1427 1428 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1429 1430 // The parser verifies that there is a string literal here. 1431 if (AsmString->isWide()) 1432 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1433 << AsmString->getSourceRange()); 1434 1435 for (unsigned i = 0; i != NumOutputs; i++) { 1436 StringLiteral *Literal = Constraints[i]; 1437 if (Literal->isWide()) 1438 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1439 << Literal->getSourceRange()); 1440 1441 llvm::StringRef OutputName; 1442 if (Names[i]) 1443 OutputName = Names[i]->getName(); 1444 1445 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 1446 if (!Context.Target.validateOutputConstraint(Info)) 1447 return StmtError(Diag(Literal->getLocStart(), 1448 diag::err_asm_invalid_output_constraint) 1449 << Info.getConstraintStr()); 1450 1451 // Check that the output exprs are valid lvalues. 1452 Expr *OutputExpr = Exprs[i]; 1453 if (CheckAsmLValue(OutputExpr, *this)) { 1454 return StmtError(Diag(OutputExpr->getLocStart(), 1455 diag::err_asm_invalid_lvalue_in_output) 1456 << OutputExpr->getSourceRange()); 1457 } 1458 1459 OutputConstraintInfos.push_back(Info); 1460 } 1461 1462 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1463 1464 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1465 StringLiteral *Literal = Constraints[i]; 1466 if (Literal->isWide()) 1467 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1468 << Literal->getSourceRange()); 1469 1470 llvm::StringRef InputName; 1471 if (Names[i]) 1472 InputName = Names[i]->getName(); 1473 1474 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 1475 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1476 NumOutputs, Info)) { 1477 return StmtError(Diag(Literal->getLocStart(), 1478 diag::err_asm_invalid_input_constraint) 1479 << Info.getConstraintStr()); 1480 } 1481 1482 Expr *InputExpr = Exprs[i]; 1483 1484 // Only allow void types for memory constraints. 1485 if (Info.allowsMemory() && !Info.allowsRegister()) { 1486 if (CheckAsmLValue(InputExpr, *this)) 1487 return StmtError(Diag(InputExpr->getLocStart(), 1488 diag::err_asm_invalid_lvalue_in_input) 1489 << Info.getConstraintStr() 1490 << InputExpr->getSourceRange()); 1491 } 1492 1493 if (Info.allowsRegister()) { 1494 if (InputExpr->getType()->isVoidType()) { 1495 return StmtError(Diag(InputExpr->getLocStart(), 1496 diag::err_asm_invalid_type_in_input) 1497 << InputExpr->getType() << Info.getConstraintStr() 1498 << InputExpr->getSourceRange()); 1499 } 1500 } 1501 1502 DefaultFunctionArrayLvalueConversion(Exprs[i]); 1503 1504 InputConstraintInfos.push_back(Info); 1505 } 1506 1507 // Check that the clobbers are valid. 1508 for (unsigned i = 0; i != NumClobbers; i++) { 1509 StringLiteral *Literal = Clobbers[i]; 1510 if (Literal->isWide()) 1511 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1512 << Literal->getSourceRange()); 1513 1514 llvm::StringRef Clobber = Literal->getString(); 1515 1516 if (!Context.Target.isValidGCCRegisterName(Clobber)) 1517 return StmtError(Diag(Literal->getLocStart(), 1518 diag::err_asm_unknown_register_name) << Clobber); 1519 } 1520 1521 AsmStmt *NS = 1522 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 1523 NumOutputs, NumInputs, Names, Constraints, Exprs, 1524 AsmString, NumClobbers, Clobbers, RParenLoc); 1525 // Validate the asm string, ensuring it makes sense given the operands we 1526 // have. 1527 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1528 unsigned DiagOffs; 1529 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1530 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1531 << AsmString->getSourceRange(); 1532 return StmtError(); 1533 } 1534 1535 // Validate tied input operands for type mismatches. 1536 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1537 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1538 1539 // If this is a tied constraint, verify that the output and input have 1540 // either exactly the same type, or that they are int/ptr operands with the 1541 // same size (int/long, int*/long, are ok etc). 1542 if (!Info.hasTiedOperand()) continue; 1543 1544 unsigned TiedTo = Info.getTiedOperand(); 1545 unsigned InputOpNo = i+NumOutputs; 1546 Expr *OutputExpr = Exprs[TiedTo]; 1547 Expr *InputExpr = Exprs[InputOpNo]; 1548 QualType InTy = InputExpr->getType(); 1549 QualType OutTy = OutputExpr->getType(); 1550 if (Context.hasSameType(InTy, OutTy)) 1551 continue; // All types can be tied to themselves. 1552 1553 // Decide if the input and output are in the same domain (integer/ptr or 1554 // floating point. 1555 enum AsmDomain { 1556 AD_Int, AD_FP, AD_Other 1557 } InputDomain, OutputDomain; 1558 1559 if (InTy->isIntegerType() || InTy->isPointerType()) 1560 InputDomain = AD_Int; 1561 else if (InTy->isRealFloatingType()) 1562 InputDomain = AD_FP; 1563 else 1564 InputDomain = AD_Other; 1565 1566 if (OutTy->isIntegerType() || OutTy->isPointerType()) 1567 OutputDomain = AD_Int; 1568 else if (OutTy->isRealFloatingType()) 1569 OutputDomain = AD_FP; 1570 else 1571 OutputDomain = AD_Other; 1572 1573 // They are ok if they are the same size and in the same domain. This 1574 // allows tying things like: 1575 // void* to int* 1576 // void* to int if they are the same size. 1577 // double to long double if they are the same size. 1578 // 1579 uint64_t OutSize = Context.getTypeSize(OutTy); 1580 uint64_t InSize = Context.getTypeSize(InTy); 1581 if (OutSize == InSize && InputDomain == OutputDomain && 1582 InputDomain != AD_Other) 1583 continue; 1584 1585 // If the smaller input/output operand is not mentioned in the asm string, 1586 // then we can promote the smaller one to a larger input and the asm string 1587 // won't notice. 1588 bool SmallerValueMentioned = false; 1589 1590 // If this is a reference to the input and if the input was the smaller 1591 // one, then we have to reject this asm. 1592 if (isOperandMentioned(InputOpNo, Pieces)) { 1593 // This is a use in the asm string of the smaller operand. Since we 1594 // codegen this by promoting to a wider value, the asm will get printed 1595 // "wrong". 1596 SmallerValueMentioned |= InSize < OutSize; 1597 } 1598 if (isOperandMentioned(TiedTo, Pieces)) { 1599 // If this is a reference to the output, and if the output is the larger 1600 // value, then it's ok because we'll promote the input to the larger type. 1601 SmallerValueMentioned |= OutSize < InSize; 1602 } 1603 1604 // If the smaller value wasn't mentioned in the asm string, and if the 1605 // output was a register, just extend the shorter one to the size of the 1606 // larger one. 1607 if (!SmallerValueMentioned && InputDomain != AD_Other && 1608 OutputConstraintInfos[TiedTo].allowsRegister()) 1609 continue; 1610 1611 // Either both of the operands were mentioned or the smaller one was 1612 // mentioned. One more special case that we'll allow: if the tied input is 1613 // integer, unmentioned, and is a constant, then we'll allow truncating it 1614 // down to the size of the destination. 1615 if (InputDomain == AD_Int && OutputDomain == AD_Int && 1616 !isOperandMentioned(InputOpNo, Pieces) && 1617 InputExpr->isEvaluatable(Context)) { 1618 ImpCastExprToType(InputExpr, OutTy, CK_IntegralCast); 1619 Exprs[InputOpNo] = InputExpr; 1620 NS->setInputExpr(i, InputExpr); 1621 continue; 1622 } 1623 1624 Diag(InputExpr->getLocStart(), 1625 diag::err_asm_tying_incompatible_types) 1626 << InTy << OutTy << OutputExpr->getSourceRange() 1627 << InputExpr->getSourceRange(); 1628 return StmtError(); 1629 } 1630 1631 return Owned(NS); 1632} 1633 1634StmtResult 1635Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 1636 SourceLocation RParen, Decl *Parm, 1637 Stmt *Body) { 1638 VarDecl *Var = cast_or_null<VarDecl>(Parm); 1639 if (Var && Var->isInvalidDecl()) 1640 return StmtError(); 1641 1642 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 1643} 1644 1645StmtResult 1646Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 1647 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 1648} 1649 1650StmtResult 1651Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 1652 MultiStmtArg CatchStmts, Stmt *Finally) { 1653 if (!getLangOptions().ObjCExceptions) 1654 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 1655 1656 getCurFunction()->setHasBranchProtectedScope(); 1657 unsigned NumCatchStmts = CatchStmts.size(); 1658 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 1659 CatchStmts.release(), 1660 NumCatchStmts, 1661 Finally)); 1662} 1663 1664StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 1665 Expr *Throw) { 1666 if (Throw) { 1667 DefaultLvalueConversion(Throw); 1668 1669 QualType ThrowType = Throw->getType(); 1670 // Make sure the expression type is an ObjC pointer or "void *". 1671 if (!ThrowType->isDependentType() && 1672 !ThrowType->isObjCObjectPointerType()) { 1673 const PointerType *PT = ThrowType->getAs<PointerType>(); 1674 if (!PT || !PT->getPointeeType()->isVoidType()) 1675 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1676 << Throw->getType() << Throw->getSourceRange()); 1677 } 1678 } 1679 1680 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 1681} 1682 1683StmtResult 1684Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 1685 Scope *CurScope) { 1686 if (!getLangOptions().ObjCExceptions) 1687 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 1688 1689 if (!Throw) { 1690 // @throw without an expression designates a rethrow (which much occur 1691 // in the context of an @catch clause). 1692 Scope *AtCatchParent = CurScope; 1693 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1694 AtCatchParent = AtCatchParent->getParent(); 1695 if (!AtCatchParent) 1696 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1697 } 1698 1699 return BuildObjCAtThrowStmt(AtLoc, Throw); 1700} 1701 1702StmtResult 1703Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 1704 Stmt *SyncBody) { 1705 getCurFunction()->setHasBranchProtectedScope(); 1706 1707 DefaultLvalueConversion(SyncExpr); 1708 1709 // Make sure the expression type is an ObjC pointer or "void *". 1710 if (!SyncExpr->getType()->isDependentType() && 1711 !SyncExpr->getType()->isObjCObjectPointerType()) { 1712 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 1713 if (!PT || !PT->getPointeeType()->isVoidType()) 1714 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 1715 << SyncExpr->getType() << SyncExpr->getSourceRange()); 1716 } 1717 1718 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 1719} 1720 1721/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1722/// and creates a proper catch handler from them. 1723StmtResult 1724Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 1725 Stmt *HandlerBlock) { 1726 // There's nothing to test that ActOnExceptionDecl didn't already test. 1727 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1728 cast_or_null<VarDecl>(ExDecl), 1729 HandlerBlock)); 1730} 1731 1732namespace { 1733 1734class TypeWithHandler { 1735 QualType t; 1736 CXXCatchStmt *stmt; 1737public: 1738 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 1739 : t(type), stmt(statement) {} 1740 1741 // An arbitrary order is fine as long as it places identical 1742 // types next to each other. 1743 bool operator<(const TypeWithHandler &y) const { 1744 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 1745 return true; 1746 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 1747 return false; 1748 else 1749 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 1750 } 1751 1752 bool operator==(const TypeWithHandler& other) const { 1753 return t == other.t; 1754 } 1755 1756 CXXCatchStmt *getCatchStmt() const { return stmt; } 1757 SourceLocation getTypeSpecStartLoc() const { 1758 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 1759 } 1760}; 1761 1762} 1763 1764/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1765/// handlers and creates a try statement from them. 1766StmtResult 1767Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 1768 MultiStmtArg RawHandlers) { 1769 // Don't report an error if 'try' is used in system headers. 1770 if (!getLangOptions().Exceptions && 1771 !getSourceManager().isInSystemHeader(TryLoc)) 1772 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 1773 1774 unsigned NumHandlers = RawHandlers.size(); 1775 assert(NumHandlers > 0 && 1776 "The parser shouldn't call this if there are no handlers."); 1777 Stmt **Handlers = RawHandlers.get(); 1778 1779 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 1780 1781 for (unsigned i = 0; i < NumHandlers; ++i) { 1782 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1783 if (!Handler->getExceptionDecl()) { 1784 if (i < NumHandlers - 1) 1785 return StmtError(Diag(Handler->getLocStart(), 1786 diag::err_early_catch_all)); 1787 1788 continue; 1789 } 1790 1791 const QualType CaughtType = Handler->getCaughtType(); 1792 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 1793 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 1794 } 1795 1796 // Detect handlers for the same type as an earlier one. 1797 if (NumHandlers > 1) { 1798 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 1799 1800 TypeWithHandler prev = TypesWithHandlers[0]; 1801 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 1802 TypeWithHandler curr = TypesWithHandlers[i]; 1803 1804 if (curr == prev) { 1805 Diag(curr.getTypeSpecStartLoc(), 1806 diag::warn_exception_caught_by_earlier_handler) 1807 << curr.getCatchStmt()->getCaughtType().getAsString(); 1808 Diag(prev.getTypeSpecStartLoc(), 1809 diag::note_previous_exception_handler) 1810 << prev.getCatchStmt()->getCaughtType().getAsString(); 1811 } 1812 1813 prev = curr; 1814 } 1815 } 1816 1817 getCurFunction()->setHasBranchProtectedScope(); 1818 1819 // FIXME: We should detect handlers that cannot catch anything because an 1820 // earlier handler catches a superclass. Need to find a method that is not 1821 // quadratic for this. 1822 // Neither of these are explicitly forbidden, but every compiler detects them 1823 // and warns. 1824 1825 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 1826 Handlers, NumHandlers)); 1827} 1828