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