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