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