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