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