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