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