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