SemaStmt.cpp revision 50bf68fc9698742e36c311fc37e6e4b7de235c4b
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for statements. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Scope.h" 16#include "clang/Sema/ScopeInfo.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/APValue.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/ArrayRef.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/ADT/SmallVector.h" 32using namespace clang; 33using namespace sema; 34 35StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 36 Expr *E = expr.get(); 37 if (!E) // FIXME: FullExprArg has no error state? 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 49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 50 SourceLocation LeadingEmptyMacroLoc) { 51 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc)); 52} 53 54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, 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 VarDecl *var = cast<VarDecl>(DG.getSingleDecl()); 70 71 // suppress any potential 'unused variable' warning. 72 var->setUsed(); 73 74 // foreach variables are never actually initialized in the way that 75 // the parser came up with. 76 var->setInit(0); 77 78 // In ARC, we don't need to retain the iteration variable of a fast 79 // enumeration loop. Rather than actually trying to catch that 80 // during declaration processing, we remove the consequences here. 81 if (getLangOptions().ObjCAutoRefCount) { 82 QualType type = var->getType(); 83 84 // Only do this if we inferred the lifetime. Inferred lifetime 85 // will show up as a local qualifier because explicit lifetime 86 // should have shown up as an AttributedType instead. 87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 88 // Add 'const' and mark the variable as pseudo-strong. 89 var->setType(type.withConst()); 90 var->setARCPseudoStrong(true); 91 } 92 } 93} 94 95/// \brief Diagnose '==' and '!=' in top-level statements as likely 96/// typos for '=' or '|=' (resp.). 97/// 98/// This function looks through common stand-alone statements to dig out the 99/// substatement of interest. It should be viable to call on any direct member 100/// of a CompoundStmt. 101/// 102/// Adding a cast to void (or other expression wrappers) will prevent the 103/// warning from firing. 104static void DiagnoseTopLevelComparison(Sema &S, const Stmt *Statement) { 105 if (!Statement) return; 106 const Expr *E = dyn_cast<Expr>(Statement); 107 if (!E) { 108 // Descend to sub-statements where they remain "top-level" in that they're 109 // unused. 110 switch (Statement->getStmtClass()) { 111 default: 112 // Skip statements which don't have a direct substatement of interest. 113 // Compound statements are handled by the caller. 114 return; 115 116 case Stmt::CaseStmtClass: 117 case Stmt::DefaultStmtClass: 118 DiagnoseTopLevelComparison(S, cast<SwitchCase>(Statement)->getSubStmt()); 119 return; 120 case Stmt::LabelStmtClass: 121 DiagnoseTopLevelComparison(S, cast<LabelStmt>(Statement)->getSubStmt()); 122 return; 123 124 case Stmt::DoStmtClass: 125 DiagnoseTopLevelComparison(S, cast<DoStmt>(Statement)->getBody()); 126 return; 127 case Stmt::IfStmtClass: { 128 const IfStmt *If = cast<IfStmt>(Statement); 129 DiagnoseTopLevelComparison(S, If->getThen()); 130 DiagnoseTopLevelComparison(S, If->getElse()); 131 return; 132 } 133 case Stmt::ForStmtClass: { 134 const ForStmt *ForLoop = cast<ForStmt>(Statement); 135 DiagnoseTopLevelComparison(S, ForLoop->getInit()); 136 DiagnoseTopLevelComparison(S, ForLoop->getInc()); 137 DiagnoseTopLevelComparison(S, ForLoop->getBody()); 138 return; 139 } 140 case Stmt::SwitchStmtClass: 141 DiagnoseTopLevelComparison(S, cast<SwitchStmt>(Statement)->getBody()); 142 return; 143 case Stmt::WhileStmtClass: 144 DiagnoseTopLevelComparison(S, cast<WhileStmt>(Statement)->getBody()); 145 return; 146 } 147 } 148 149 SourceLocation Loc; 150 bool IsNotEqual, CanAssign; 151 152 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 153 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE) 154 return; 155 156 Loc = Op->getOperatorLoc(); 157 IsNotEqual = Op->getOpcode() == BO_NE; 158 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 159 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 160 if (Op->getOperator() != OO_EqualEqual && 161 Op->getOperator() != OO_ExclaimEqual) 162 return; 163 164 Loc = Op->getOperatorLoc(); 165 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 166 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 167 } else { 168 // Not a typo-prone comparison. 169 return; 170 } 171 172 // Suppress warnings when the operator, suspicious as it may be, comes from 173 // a macro expansion. 174 if (Loc.isMacroID()) 175 return; 176 177 S.Diag(Loc, diag::warn_comparison_top_level_stmt) 178 << (unsigned)IsNotEqual << E->getSourceRange(); 179 180 SourceLocation Open = E->getSourceRange().getBegin(); 181 SourceLocation Close = S.PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 182 S.Diag(Loc, diag::note_top_level_comparison_void_cast_silence) 183 << FixItHint::CreateInsertion(Open, "(void)(") 184 << FixItHint::CreateInsertion(Close, ")"); 185 186 // If the LHS is a plausible entity to assign to, provide a fixit hint to 187 // correct common typos. 188 if (CanAssign) { 189 if (IsNotEqual) 190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 191 << FixItHint::CreateReplacement(Loc, "|="); 192 else 193 S.Diag(Loc, diag::note_equality_comparison_to_assign) 194 << FixItHint::CreateReplacement(Loc, "="); 195 } 196} 197 198void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 199 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 200 return DiagnoseUnusedExprResult(Label->getSubStmt()); 201 202 const Expr *E = dyn_cast_or_null<Expr>(S); 203 if (!E) 204 return; 205 206 SourceLocation Loc; 207 SourceRange R1, R2; 208 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 209 return; 210 211 // Okay, we have an unused result. Depending on what the base expression is, 212 // we might want to make a more specific diagnostic. Check for one of these 213 // cases now. 214 unsigned DiagID = diag::warn_unused_expr; 215 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 216 E = Temps->getSubExpr(); 217 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 218 E = TempExpr->getSubExpr(); 219 220 E = E->IgnoreParenImpCasts(); 221 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 222 if (E->getType()->isVoidType()) 223 return; 224 225 // If the callee has attribute pure, const, or warn_unused_result, warn with 226 // a more specific message to make it clear what is happening. 227 if (const Decl *FD = CE->getCalleeDecl()) { 228 if (FD->getAttr<WarnUnusedResultAttr>()) { 229 Diag(Loc, diag::warn_unused_result) << R1 << R2; 230 return; 231 } 232 if (FD->getAttr<PureAttr>()) { 233 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 234 return; 235 } 236 if (FD->getAttr<ConstAttr>()) { 237 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 238 return; 239 } 240 } 241 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 242 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) { 243 Diag(Loc, diag::err_arc_unused_init_message) << R1; 244 return; 245 } 246 const ObjCMethodDecl *MD = ME->getMethodDecl(); 247 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 248 Diag(Loc, diag::warn_unused_result) << R1 << R2; 249 return; 250 } 251 } else if (isa<ObjCPropertyRefExpr>(E)) { 252 DiagID = diag::warn_unused_property_expr; 253 } else if (const CXXFunctionalCastExpr *FC 254 = dyn_cast<CXXFunctionalCastExpr>(E)) { 255 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 256 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 257 return; 258 } 259 // Diagnose "(void*) blah" as a typo for "(void) blah". 260 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 261 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 262 QualType T = TI->getType(); 263 264 // We really do want to use the non-canonical type here. 265 if (T == Context.VoidPtrTy) { 266 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 267 268 Diag(Loc, diag::warn_unused_voidptr) 269 << FixItHint::CreateRemoval(TL.getStarLoc()); 270 return; 271 } 272 } 273 274 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 275} 276 277StmtResult 278Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 279 MultiStmtArg elts, bool isStmtExpr) { 280 unsigned NumElts = elts.size(); 281 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 282 // If we're in C89 mode, check that we don't have any decls after stmts. If 283 // so, emit an extension diagnostic. 284 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 285 // Note that __extension__ can be around a decl. 286 unsigned i = 0; 287 // Skip over all declarations. 288 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 289 /*empty*/; 290 291 // We found the end of the list or a statement. Scan for another declstmt. 292 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 293 /*empty*/; 294 295 if (i != NumElts) { 296 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 297 Diag(D->getLocation(), diag::ext_mixed_decls_code); 298 } 299 } 300 // Warn about unused expressions in statements. 301 for (unsigned i = 0; i != NumElts; ++i) { 302 // Ignore statements that are last in a statement expression. 303 if (isStmtExpr && i == NumElts - 1) 304 continue; 305 306 // FIXME: It'd be nice to not show both of these. The first is a more 307 // precise (and more likely to be enabled) warning. We should suppress the 308 // second when the first fires. 309 DiagnoseTopLevelComparison(*this, Elts[i]); 310 DiagnoseUnusedExprResult(Elts[i]); 311 } 312 313 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 314} 315 316StmtResult 317Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 318 SourceLocation DotDotDotLoc, Expr *RHSVal, 319 SourceLocation ColonLoc) { 320 assert((LHSVal != 0) && "missing expression in case statement"); 321 322 // C99 6.8.4.2p3: The expression shall be an integer constant. 323 // However, GCC allows any evaluatable integer expression. 324 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 325 VerifyIntegerConstantExpression(LHSVal)) 326 return StmtError(); 327 328 // GCC extension: The expression shall be an integer constant. 329 330 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 331 VerifyIntegerConstantExpression(RHSVal)) { 332 RHSVal = 0; // Recover by just forgetting about it. 333 } 334 335 if (getCurFunction()->SwitchStack.empty()) { 336 Diag(CaseLoc, diag::err_case_not_in_switch); 337 return StmtError(); 338 } 339 340 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 341 ColonLoc); 342 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 343 return Owned(CS); 344} 345 346/// ActOnCaseStmtBody - This installs a statement as the body of a case. 347void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 348 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 349 CS->setSubStmt(SubStmt); 350} 351 352StmtResult 353Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 354 Stmt *SubStmt, Scope *CurScope) { 355 if (getCurFunction()->SwitchStack.empty()) { 356 Diag(DefaultLoc, diag::err_default_not_in_switch); 357 return Owned(SubStmt); 358 } 359 360 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 361 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 362 return Owned(DS); 363} 364 365StmtResult 366Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 367 SourceLocation ColonLoc, Stmt *SubStmt) { 368 369 // If the label was multiply defined, reject it now. 370 if (TheDecl->getStmt()) { 371 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 372 Diag(TheDecl->getLocation(), diag::note_previous_definition); 373 return Owned(SubStmt); 374 } 375 376 // Otherwise, things are good. Fill in the declaration and return it. 377 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 378 TheDecl->setStmt(LS); 379 if (!TheDecl->isGnuLocal()) 380 TheDecl->setLocation(IdentLoc); 381 return Owned(LS); 382} 383 384StmtResult 385Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 386 Stmt *thenStmt, SourceLocation ElseLoc, 387 Stmt *elseStmt) { 388 ExprResult CondResult(CondVal.release()); 389 390 VarDecl *ConditionVar = 0; 391 if (CondVar) { 392 ConditionVar = cast<VarDecl>(CondVar); 393 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 394 if (CondResult.isInvalid()) 395 return StmtError(); 396 } 397 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 398 if (!ConditionExpr) 399 return StmtError(); 400 401 DiagnoseUnusedExprResult(thenStmt); 402 403 // Warn if the if block has a null body without an else value. 404 // this helps prevent bugs due to typos, such as 405 // if (condition); 406 // do_stuff(); 407 // 408 if (!elseStmt) { 409 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 410 // But do not warn if the body is a macro that expands to nothing, e.g: 411 // 412 // #define CALL(x) 413 // if (condition) 414 // CALL(0); 415 // 416 if (!stmt->hasLeadingEmptyMacro()) 417 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 418 } 419 420 DiagnoseUnusedExprResult(elseStmt); 421 422 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 423 thenStmt, ElseLoc, elseStmt)); 424} 425 426/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 427/// the specified width and sign. If an overflow occurs, detect it and emit 428/// the specified diagnostic. 429void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 430 unsigned NewWidth, bool NewSign, 431 SourceLocation Loc, 432 unsigned DiagID) { 433 // Perform a conversion to the promoted condition type if needed. 434 if (NewWidth > Val.getBitWidth()) { 435 // If this is an extension, just do it. 436 Val = Val.extend(NewWidth); 437 Val.setIsSigned(NewSign); 438 439 // If the input was signed and negative and the output is 440 // unsigned, don't bother to warn: this is implementation-defined 441 // behavior. 442 // FIXME: Introduce a second, default-ignored warning for this case? 443 } else if (NewWidth < Val.getBitWidth()) { 444 // If this is a truncation, check for overflow. 445 llvm::APSInt ConvVal(Val); 446 ConvVal = ConvVal.trunc(NewWidth); 447 ConvVal.setIsSigned(NewSign); 448 ConvVal = ConvVal.extend(Val.getBitWidth()); 449 ConvVal.setIsSigned(Val.isSigned()); 450 if (ConvVal != Val) 451 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 452 453 // Regardless of whether a diagnostic was emitted, really do the 454 // truncation. 455 Val = Val.trunc(NewWidth); 456 Val.setIsSigned(NewSign); 457 } else if (NewSign != Val.isSigned()) { 458 // Convert the sign to match the sign of the condition. This can cause 459 // overflow as well: unsigned(INTMIN) 460 // We don't diagnose this overflow, because it is implementation-defined 461 // behavior. 462 // FIXME: Introduce a second, default-ignored warning for this case? 463 llvm::APSInt OldVal(Val); 464 Val.setIsSigned(NewSign); 465 } 466} 467 468namespace { 469 struct CaseCompareFunctor { 470 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 471 const llvm::APSInt &RHS) { 472 return LHS.first < RHS; 473 } 474 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 475 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 476 return LHS.first < RHS.first; 477 } 478 bool operator()(const llvm::APSInt &LHS, 479 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 480 return LHS < RHS.first; 481 } 482 }; 483} 484 485/// CmpCaseVals - Comparison predicate for sorting case values. 486/// 487static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 488 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 489 if (lhs.first < rhs.first) 490 return true; 491 492 if (lhs.first == rhs.first && 493 lhs.second->getCaseLoc().getRawEncoding() 494 < rhs.second->getCaseLoc().getRawEncoding()) 495 return true; 496 return false; 497} 498 499/// CmpEnumVals - Comparison predicate for sorting enumeration values. 500/// 501static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 502 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 503{ 504 return lhs.first < rhs.first; 505} 506 507/// EqEnumVals - Comparison preficate for uniqing enumeration values. 508/// 509static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 510 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 511{ 512 return lhs.first == rhs.first; 513} 514 515/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 516/// potentially integral-promoted expression @p expr. 517static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 518 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 519 expr = cleanups->getSubExpr(); 520 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 521 if (impcast->getCastKind() != CK_IntegralCast) break; 522 expr = impcast->getSubExpr(); 523 } 524 return expr->getType(); 525} 526 527StmtResult 528Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 529 Decl *CondVar) { 530 ExprResult CondResult; 531 532 VarDecl *ConditionVar = 0; 533 if (CondVar) { 534 ConditionVar = cast<VarDecl>(CondVar); 535 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 536 if (CondResult.isInvalid()) 537 return StmtError(); 538 539 Cond = CondResult.release(); 540 } 541 542 if (!Cond) 543 return StmtError(); 544 545 CondResult 546 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, 547 PDiag(diag::err_typecheck_statement_requires_integer), 548 PDiag(diag::err_switch_incomplete_class_type) 549 << Cond->getSourceRange(), 550 PDiag(diag::err_switch_explicit_conversion), 551 PDiag(diag::note_switch_conversion), 552 PDiag(diag::err_switch_multiple_conversions), 553 PDiag(diag::note_switch_conversion), 554 PDiag(0)); 555 if (CondResult.isInvalid()) return StmtError(); 556 Cond = CondResult.take(); 557 558 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 559 CondResult = UsualUnaryConversions(Cond); 560 if (CondResult.isInvalid()) return StmtError(); 561 Cond = CondResult.take(); 562 563 if (!CondVar) { 564 CheckImplicitConversions(Cond, SwitchLoc); 565 CondResult = MaybeCreateExprWithCleanups(Cond); 566 if (CondResult.isInvalid()) 567 return StmtError(); 568 Cond = CondResult.take(); 569 } 570 571 getCurFunction()->setHasBranchIntoScope(); 572 573 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 574 getCurFunction()->SwitchStack.push_back(SS); 575 return Owned(SS); 576} 577 578static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 579 if (Val.getBitWidth() < BitWidth) 580 Val = Val.extend(BitWidth); 581 else if (Val.getBitWidth() > BitWidth) 582 Val = Val.trunc(BitWidth); 583 Val.setIsSigned(IsSigned); 584} 585 586StmtResult 587Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 588 Stmt *BodyStmt) { 589 SwitchStmt *SS = cast<SwitchStmt>(Switch); 590 assert(SS == getCurFunction()->SwitchStack.back() && 591 "switch stack missing push/pop!"); 592 593 SS->setBody(BodyStmt, SwitchLoc); 594 getCurFunction()->SwitchStack.pop_back(); 595 596 Expr *CondExpr = SS->getCond(); 597 if (!CondExpr) return StmtError(); 598 599 QualType CondType = CondExpr->getType(); 600 601 Expr *CondExprBeforePromotion = CondExpr; 602 QualType CondTypeBeforePromotion = 603 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 604 605 // C++ 6.4.2.p2: 606 // Integral promotions are performed (on the switch condition). 607 // 608 // A case value unrepresentable by the original switch condition 609 // type (before the promotion) doesn't make sense, even when it can 610 // be represented by the promoted type. Therefore we need to find 611 // the pre-promotion type of the switch condition. 612 if (!CondExpr->isTypeDependent()) { 613 // We have already converted the expression to an integral or enumeration 614 // type, when we started the switch statement. If we don't have an 615 // appropriate type now, just return an error. 616 if (!CondType->isIntegralOrEnumerationType()) 617 return StmtError(); 618 619 if (CondExpr->isKnownToHaveBooleanValue()) { 620 // switch(bool_expr) {...} is often a programmer error, e.g. 621 // switch(n && mask) { ... } // Doh - should be "n & mask". 622 // One can always use an if statement instead of switch(bool_expr). 623 Diag(SwitchLoc, diag::warn_bool_switch_condition) 624 << CondExpr->getSourceRange(); 625 } 626 } 627 628 // Get the bitwidth of the switched-on value before promotions. We must 629 // convert the integer case values to this width before comparison. 630 bool HasDependentValue 631 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 632 unsigned CondWidth 633 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 634 bool CondIsSigned 635 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 636 637 // Accumulate all of the case values in a vector so that we can sort them 638 // and detect duplicates. This vector contains the APInt for the case after 639 // it has been converted to the condition type. 640 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 641 CaseValsTy CaseVals; 642 643 // Keep track of any GNU case ranges we see. The APSInt is the low value. 644 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 645 CaseRangesTy CaseRanges; 646 647 DefaultStmt *TheDefaultStmt = 0; 648 649 bool CaseListIsErroneous = false; 650 651 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 652 SC = SC->getNextSwitchCase()) { 653 654 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 655 if (TheDefaultStmt) { 656 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 657 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 658 659 // FIXME: Remove the default statement from the switch block so that 660 // we'll return a valid AST. This requires recursing down the AST and 661 // finding it, not something we are set up to do right now. For now, 662 // just lop the entire switch stmt out of the AST. 663 CaseListIsErroneous = true; 664 } 665 TheDefaultStmt = DS; 666 667 } else { 668 CaseStmt *CS = cast<CaseStmt>(SC); 669 670 // We already verified that the expression has a i-c-e value (C99 671 // 6.8.4.2p3) - get that value now. 672 Expr *Lo = CS->getLHS(); 673 674 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 675 HasDependentValue = true; 676 break; 677 } 678 679 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 680 681 // Convert the value to the same width/sign as the condition. 682 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 683 Lo->getLocStart(), 684 diag::warn_case_value_overflow); 685 686 // If the LHS is not the same type as the condition, insert an implicit 687 // cast. 688 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 689 CS->setLHS(Lo); 690 691 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 692 if (CS->getRHS()) { 693 if (CS->getRHS()->isTypeDependent() || 694 CS->getRHS()->isValueDependent()) { 695 HasDependentValue = true; 696 break; 697 } 698 CaseRanges.push_back(std::make_pair(LoVal, CS)); 699 } else 700 CaseVals.push_back(std::make_pair(LoVal, CS)); 701 } 702 } 703 704 if (!HasDependentValue) { 705 // If we don't have a default statement, check whether the 706 // condition is constant. 707 llvm::APSInt ConstantCondValue; 708 bool HasConstantCond = false; 709 bool ShouldCheckConstantCond = false; 710 if (!HasDependentValue && !TheDefaultStmt) { 711 Expr::EvalResult Result; 712 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context); 713 if (HasConstantCond) { 714 assert(Result.Val.isInt() && "switch condition evaluated to non-int"); 715 ConstantCondValue = Result.Val.getInt(); 716 ShouldCheckConstantCond = true; 717 718 assert(ConstantCondValue.getBitWidth() == CondWidth && 719 ConstantCondValue.isSigned() == CondIsSigned); 720 } 721 } 722 723 // Sort all the scalar case values so we can easily detect duplicates. 724 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 725 726 if (!CaseVals.empty()) { 727 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 728 if (ShouldCheckConstantCond && 729 CaseVals[i].first == ConstantCondValue) 730 ShouldCheckConstantCond = false; 731 732 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 733 // If we have a duplicate, report it. 734 Diag(CaseVals[i].second->getLHS()->getLocStart(), 735 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 736 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 737 diag::note_duplicate_case_prev); 738 // FIXME: We really want to remove the bogus case stmt from the 739 // substmt, but we have no way to do this right now. 740 CaseListIsErroneous = true; 741 } 742 } 743 } 744 745 // Detect duplicate case ranges, which usually don't exist at all in 746 // the first place. 747 if (!CaseRanges.empty()) { 748 // Sort all the case ranges by their low value so we can easily detect 749 // overlaps between ranges. 750 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 751 752 // Scan the ranges, computing the high values and removing empty ranges. 753 std::vector<llvm::APSInt> HiVals; 754 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 755 llvm::APSInt &LoVal = CaseRanges[i].first; 756 CaseStmt *CR = CaseRanges[i].second; 757 Expr *Hi = CR->getRHS(); 758 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 759 760 // Convert the value to the same width/sign as the condition. 761 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 762 Hi->getLocStart(), 763 diag::warn_case_value_overflow); 764 765 // If the LHS is not the same type as the condition, insert an implicit 766 // cast. 767 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 768 CR->setRHS(Hi); 769 770 // If the low value is bigger than the high value, the case is empty. 771 if (LoVal > HiVal) { 772 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 773 << SourceRange(CR->getLHS()->getLocStart(), 774 Hi->getLocEnd()); 775 CaseRanges.erase(CaseRanges.begin()+i); 776 --i, --e; 777 continue; 778 } 779 780 if (ShouldCheckConstantCond && 781 LoVal <= ConstantCondValue && 782 ConstantCondValue <= HiVal) 783 ShouldCheckConstantCond = false; 784 785 HiVals.push_back(HiVal); 786 } 787 788 // Rescan the ranges, looking for overlap with singleton values and other 789 // ranges. Since the range list is sorted, we only need to compare case 790 // ranges with their neighbors. 791 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 792 llvm::APSInt &CRLo = CaseRanges[i].first; 793 llvm::APSInt &CRHi = HiVals[i]; 794 CaseStmt *CR = CaseRanges[i].second; 795 796 // Check to see whether the case range overlaps with any 797 // singleton cases. 798 CaseStmt *OverlapStmt = 0; 799 llvm::APSInt OverlapVal(32); 800 801 // Find the smallest value >= the lower bound. If I is in the 802 // case range, then we have overlap. 803 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 804 CaseVals.end(), CRLo, 805 CaseCompareFunctor()); 806 if (I != CaseVals.end() && I->first < CRHi) { 807 OverlapVal = I->first; // Found overlap with scalar. 808 OverlapStmt = I->second; 809 } 810 811 // Find the smallest value bigger than the upper bound. 812 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 813 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 814 OverlapVal = (I-1)->first; // Found overlap with scalar. 815 OverlapStmt = (I-1)->second; 816 } 817 818 // Check to see if this case stmt overlaps with the subsequent 819 // case range. 820 if (i && CRLo <= HiVals[i-1]) { 821 OverlapVal = HiVals[i-1]; // Found overlap with range. 822 OverlapStmt = CaseRanges[i-1].second; 823 } 824 825 if (OverlapStmt) { 826 // If we have a duplicate, report it. 827 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 828 << OverlapVal.toString(10); 829 Diag(OverlapStmt->getLHS()->getLocStart(), 830 diag::note_duplicate_case_prev); 831 // FIXME: We really want to remove the bogus case stmt from the 832 // substmt, but we have no way to do this right now. 833 CaseListIsErroneous = true; 834 } 835 } 836 } 837 838 // Complain if we have a constant condition and we didn't find a match. 839 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 840 // TODO: it would be nice if we printed enums as enums, chars as 841 // chars, etc. 842 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 843 << ConstantCondValue.toString(10) 844 << CondExpr->getSourceRange(); 845 } 846 847 // Check to see if switch is over an Enum and handles all of its 848 // values. We only issue a warning if there is not 'default:', but 849 // we still do the analysis to preserve this information in the AST 850 // (which can be used by flow-based analyes). 851 // 852 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 853 854 // If switch has default case, then ignore it. 855 if (!CaseListIsErroneous && !HasConstantCond && ET) { 856 const EnumDecl *ED = ET->getDecl(); 857 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 858 EnumValsTy; 859 EnumValsTy EnumVals; 860 861 // Gather all enum values, set their type and sort them, 862 // allowing easier comparison with CaseVals. 863 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 864 EDI != ED->enumerator_end(); ++EDI) { 865 llvm::APSInt Val = EDI->getInitVal(); 866 AdjustAPSInt(Val, CondWidth, CondIsSigned); 867 EnumVals.push_back(std::make_pair(Val, *EDI)); 868 } 869 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 870 EnumValsTy::iterator EIend = 871 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 872 873 // See which case values aren't in enum. 874 // TODO: we might want to check whether case values are out of the 875 // enum even if we don't want to check whether all cases are handled. 876 if (!TheDefaultStmt) { 877 EnumValsTy::const_iterator EI = EnumVals.begin(); 878 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 879 CI != CaseVals.end(); CI++) { 880 while (EI != EIend && EI->first < CI->first) 881 EI++; 882 if (EI == EIend || EI->first > CI->first) 883 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 884 << ED->getDeclName(); 885 } 886 // See which of case ranges aren't in enum 887 EI = EnumVals.begin(); 888 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 889 RI != CaseRanges.end() && EI != EIend; RI++) { 890 while (EI != EIend && EI->first < RI->first) 891 EI++; 892 893 if (EI == EIend || EI->first != RI->first) { 894 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 895 << ED->getDeclName(); 896 } 897 898 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 899 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 900 while (EI != EIend && EI->first < Hi) 901 EI++; 902 if (EI == EIend || EI->first != Hi) 903 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 904 << ED->getDeclName(); 905 } 906 } 907 908 // Check which enum vals aren't in switch 909 CaseValsTy::const_iterator CI = CaseVals.begin(); 910 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 911 bool hasCasesNotInSwitch = false; 912 913 SmallVector<DeclarationName,8> UnhandledNames; 914 915 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 916 // Drop unneeded case values 917 llvm::APSInt CIVal; 918 while (CI != CaseVals.end() && CI->first < EI->first) 919 CI++; 920 921 if (CI != CaseVals.end() && CI->first == EI->first) 922 continue; 923 924 // Drop unneeded case ranges 925 for (; RI != CaseRanges.end(); RI++) { 926 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 927 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 928 if (EI->first <= Hi) 929 break; 930 } 931 932 if (RI == CaseRanges.end() || EI->first < RI->first) { 933 hasCasesNotInSwitch = true; 934 if (!TheDefaultStmt) 935 UnhandledNames.push_back(EI->second->getDeclName()); 936 } 937 } 938 939 // Produce a nice diagnostic if multiple values aren't handled. 940 switch (UnhandledNames.size()) { 941 case 0: break; 942 case 1: 943 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 944 << UnhandledNames[0]; 945 break; 946 case 2: 947 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 948 << UnhandledNames[0] << UnhandledNames[1]; 949 break; 950 case 3: 951 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 952 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 953 break; 954 default: 955 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 956 << (unsigned)UnhandledNames.size() 957 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 958 break; 959 } 960 961 if (!hasCasesNotInSwitch) 962 SS->setAllEnumCasesCovered(); 963 } 964 } 965 966 // FIXME: If the case list was broken is some way, we don't have a good system 967 // to patch it up. Instead, just return the whole substmt as broken. 968 if (CaseListIsErroneous) 969 return StmtError(); 970 971 return Owned(SS); 972} 973 974StmtResult 975Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 976 Decl *CondVar, Stmt *Body) { 977 ExprResult CondResult(Cond.release()); 978 979 VarDecl *ConditionVar = 0; 980 if (CondVar) { 981 ConditionVar = cast<VarDecl>(CondVar); 982 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 983 if (CondResult.isInvalid()) 984 return StmtError(); 985 } 986 Expr *ConditionExpr = CondResult.take(); 987 if (!ConditionExpr) 988 return StmtError(); 989 990 DiagnoseUnusedExprResult(Body); 991 992 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 993 Body, WhileLoc)); 994} 995 996StmtResult 997Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 998 SourceLocation WhileLoc, SourceLocation CondLParen, 999 Expr *Cond, SourceLocation CondRParen) { 1000 assert(Cond && "ActOnDoStmt(): missing expression"); 1001 1002 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 1003 if (CondResult.isInvalid() || CondResult.isInvalid()) 1004 return StmtError(); 1005 Cond = CondResult.take(); 1006 1007 CheckImplicitConversions(Cond, DoLoc); 1008 CondResult = MaybeCreateExprWithCleanups(Cond); 1009 if (CondResult.isInvalid()) 1010 return StmtError(); 1011 Cond = CondResult.take(); 1012 1013 DiagnoseUnusedExprResult(Body); 1014 1015 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 1016} 1017 1018StmtResult 1019Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1020 Stmt *First, FullExprArg second, Decl *secondVar, 1021 FullExprArg third, 1022 SourceLocation RParenLoc, Stmt *Body) { 1023 if (!getLangOptions().CPlusPlus) { 1024 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 1025 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1026 // declare identifiers for objects having storage class 'auto' or 1027 // 'register'. 1028 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 1029 DI!=DE; ++DI) { 1030 VarDecl *VD = dyn_cast<VarDecl>(*DI); 1031 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 1032 VD = 0; 1033 if (VD == 0) 1034 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 1035 // FIXME: mark decl erroneous! 1036 } 1037 } 1038 } 1039 1040 ExprResult SecondResult(second.release()); 1041 VarDecl *ConditionVar = 0; 1042 if (secondVar) { 1043 ConditionVar = cast<VarDecl>(secondVar); 1044 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1045 if (SecondResult.isInvalid()) 1046 return StmtError(); 1047 } 1048 1049 Expr *Third = third.release().takeAs<Expr>(); 1050 1051 DiagnoseUnusedExprResult(First); 1052 DiagnoseUnusedExprResult(Third); 1053 DiagnoseUnusedExprResult(Body); 1054 1055 return Owned(new (Context) ForStmt(Context, First, 1056 SecondResult.take(), ConditionVar, 1057 Third, Body, ForLoc, LParenLoc, 1058 RParenLoc)); 1059} 1060 1061/// In an Objective C collection iteration statement: 1062/// for (x in y) 1063/// x can be an arbitrary l-value expression. Bind it up as a 1064/// full-expression. 1065StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1066 CheckImplicitConversions(E); 1067 ExprResult Result = MaybeCreateExprWithCleanups(E); 1068 if (Result.isInvalid()) return StmtError(); 1069 return Owned(static_cast<Stmt*>(Result.get())); 1070} 1071 1072ExprResult 1073Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1074 assert(collection); 1075 1076 // Bail out early if we've got a type-dependent expression. 1077 if (collection->isTypeDependent()) return Owned(collection); 1078 1079 // Perform normal l-value conversion. 1080 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1081 if (result.isInvalid()) 1082 return ExprError(); 1083 collection = result.take(); 1084 1085 // The operand needs to have object-pointer type. 1086 // TODO: should we do a contextual conversion? 1087 const ObjCObjectPointerType *pointerType = 1088 collection->getType()->getAs<ObjCObjectPointerType>(); 1089 if (!pointerType) 1090 return Diag(forLoc, diag::err_collection_expr_type) 1091 << collection->getType() << collection->getSourceRange(); 1092 1093 // Check that the operand provides 1094 // - countByEnumeratingWithState:objects:count: 1095 const ObjCObjectType *objectType = pointerType->getObjectType(); 1096 ObjCInterfaceDecl *iface = objectType->getInterface(); 1097 1098 // If we have a forward-declared type, we can't do this check. 1099 if (iface && iface->isForwardDecl()) { 1100 // This is ill-formed under ARC. 1101 if (getLangOptions().ObjCAutoRefCount) { 1102 Diag(forLoc, diag::err_arc_collection_forward) 1103 << pointerType->getPointeeType() << collection->getSourceRange(); 1104 } 1105 1106 // Otherwise, if we have any useful type information, check that 1107 // the type declares the appropriate method. 1108 } else if (iface || !objectType->qual_empty()) { 1109 IdentifierInfo *selectorIdents[] = { 1110 &Context.Idents.get("countByEnumeratingWithState"), 1111 &Context.Idents.get("objects"), 1112 &Context.Idents.get("count") 1113 }; 1114 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1115 1116 ObjCMethodDecl *method = 0; 1117 1118 // If there's an interface, look in both the public and private APIs. 1119 if (iface) { 1120 method = iface->lookupInstanceMethod(selector); 1121 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 1122 } 1123 1124 // Also check protocol qualifiers. 1125 if (!method) 1126 method = LookupMethodInQualifiedType(selector, pointerType, 1127 /*instance*/ true); 1128 1129 // If we didn't find it anywhere, give up. 1130 if (!method) { 1131 Diag(forLoc, diag::warn_collection_expr_type) 1132 << collection->getType() << selector << collection->getSourceRange(); 1133 } 1134 1135 // TODO: check for an incompatible signature? 1136 } 1137 1138 // Wrap up any cleanups in the expression. 1139 return Owned(MaybeCreateExprWithCleanups(collection)); 1140} 1141 1142StmtResult 1143Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1144 SourceLocation LParenLoc, 1145 Stmt *First, Expr *Second, 1146 SourceLocation RParenLoc, Stmt *Body) { 1147 if (First) { 1148 QualType FirstType; 1149 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1150 if (!DS->isSingleDecl()) 1151 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1152 diag::err_toomany_element_decls)); 1153 1154 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1155 FirstType = D->getType(); 1156 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1157 // declare identifiers for objects having storage class 'auto' or 1158 // 'register'. 1159 if (!D->hasLocalStorage()) 1160 return StmtError(Diag(D->getLocation(), 1161 diag::err_non_variable_decl_in_for)); 1162 } else { 1163 Expr *FirstE = cast<Expr>(First); 1164 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1165 return StmtError(Diag(First->getLocStart(), 1166 diag::err_selector_element_not_lvalue) 1167 << First->getSourceRange()); 1168 1169 FirstType = static_cast<Expr*>(First)->getType(); 1170 } 1171 if (!FirstType->isDependentType() && 1172 !FirstType->isObjCObjectPointerType() && 1173 !FirstType->isBlockPointerType()) 1174 Diag(ForLoc, diag::err_selector_element_type) 1175 << FirstType << First->getSourceRange(); 1176 } 1177 1178 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1179 ForLoc, RParenLoc)); 1180} 1181 1182namespace { 1183 1184enum BeginEndFunction { 1185 BEF_begin, 1186 BEF_end 1187}; 1188 1189/// Build a variable declaration for a for-range statement. 1190static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1191 QualType Type, const char *Name) { 1192 DeclContext *DC = SemaRef.CurContext; 1193 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1194 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1195 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1196 TInfo, SC_Auto, SC_None); 1197 Decl->setImplicit(); 1198 return Decl; 1199} 1200 1201/// Finish building a variable declaration for a for-range statement. 1202/// \return true if an error occurs. 1203static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1204 SourceLocation Loc, int diag) { 1205 // Deduce the type for the iterator variable now rather than leaving it to 1206 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1207 TypeSourceInfo *InitTSI = 0; 1208 if (Init->getType()->isVoidType() || 1209 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI)) 1210 SemaRef.Diag(Loc, diag) << Init->getType(); 1211 if (!InitTSI) { 1212 Decl->setInvalidDecl(); 1213 return true; 1214 } 1215 Decl->setTypeSourceInfo(InitTSI); 1216 Decl->setType(InitTSI->getType()); 1217 1218 // In ARC, infer lifetime. 1219 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1220 // we're doing the equivalent of fast iteration. 1221 if (SemaRef.getLangOptions().ObjCAutoRefCount && 1222 SemaRef.inferObjCARCLifetime(Decl)) 1223 Decl->setInvalidDecl(); 1224 1225 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1226 /*TypeMayContainAuto=*/false); 1227 SemaRef.FinalizeDeclaration(Decl); 1228 SemaRef.CurContext->addHiddenDecl(Decl); 1229 return false; 1230} 1231 1232/// Produce a note indicating which begin/end function was implicitly called 1233/// by a C++0x for-range statement. This is often not obvious from the code, 1234/// nor from the diagnostics produced when analysing the implicit expressions 1235/// required in a for-range statement. 1236void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1237 BeginEndFunction BEF) { 1238 CallExpr *CE = dyn_cast<CallExpr>(E); 1239 if (!CE) 1240 return; 1241 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1242 if (!D) 1243 return; 1244 SourceLocation Loc = D->getLocation(); 1245 1246 std::string Description; 1247 bool IsTemplate = false; 1248 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1249 Description = SemaRef.getTemplateArgumentBindingsText( 1250 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1251 IsTemplate = true; 1252 } 1253 1254 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1255 << BEF << IsTemplate << Description << E->getType(); 1256} 1257 1258/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1259/// given LookupResult is non-empty, it is assumed to describe a member which 1260/// will be invoked. Otherwise, the function will be found via argument 1261/// dependent lookup. 1262static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1263 SourceLocation Loc, 1264 VarDecl *Decl, 1265 BeginEndFunction BEF, 1266 const DeclarationNameInfo &NameInfo, 1267 LookupResult &MemberLookup, 1268 Expr *Range) { 1269 ExprResult CallExpr; 1270 if (!MemberLookup.empty()) { 1271 ExprResult MemberRef = 1272 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1273 /*IsPtr=*/false, CXXScopeSpec(), 1274 /*Qualifier=*/0, MemberLookup, 1275 /*TemplateArgs=*/0); 1276 if (MemberRef.isInvalid()) 1277 return ExprError(); 1278 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1279 Loc, 0); 1280 if (CallExpr.isInvalid()) 1281 return ExprError(); 1282 } else { 1283 UnresolvedSet<0> FoundNames; 1284 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1285 // std is an associated namespace. 1286 UnresolvedLookupExpr *Fn = 1287 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1288 NestedNameSpecifierLoc(), NameInfo, 1289 /*NeedsADL=*/true, /*Overloaded=*/false, 1290 FoundNames.begin(), FoundNames.end(), 1291 /*LookInStdNamespace=*/true); 1292 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1293 0); 1294 if (CallExpr.isInvalid()) { 1295 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1296 << Range->getType(); 1297 return ExprError(); 1298 } 1299 } 1300 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1301 diag::err_for_range_iter_deduction_failure)) { 1302 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1303 return ExprError(); 1304 } 1305 return CallExpr; 1306} 1307 1308} 1309 1310/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1311/// 1312/// C++0x [stmt.ranged]: 1313/// A range-based for statement is equivalent to 1314/// 1315/// { 1316/// auto && __range = range-init; 1317/// for ( auto __begin = begin-expr, 1318/// __end = end-expr; 1319/// __begin != __end; 1320/// ++__begin ) { 1321/// for-range-declaration = *__begin; 1322/// statement 1323/// } 1324/// } 1325/// 1326/// The body of the loop is not available yet, since it cannot be analysed until 1327/// we have determined the type of the for-range-declaration. 1328StmtResult 1329Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1330 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1331 SourceLocation RParenLoc) { 1332 if (!First || !Range) 1333 return StmtError(); 1334 1335 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1336 assert(DS && "first part of for range not a decl stmt"); 1337 1338 if (!DS->isSingleDecl()) { 1339 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1340 return StmtError(); 1341 } 1342 if (DS->getSingleDecl()->isInvalidDecl()) 1343 return StmtError(); 1344 1345 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1346 return StmtError(); 1347 1348 // Build auto && __range = range-init 1349 SourceLocation RangeLoc = Range->getLocStart(); 1350 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1351 Context.getAutoRRefDeductType(), 1352 "__range"); 1353 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1354 diag::err_for_range_deduction_failure)) 1355 return StmtError(); 1356 1357 // Claim the type doesn't contain auto: we've already done the checking. 1358 DeclGroupPtrTy RangeGroup = 1359 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1360 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1361 if (RangeDecl.isInvalid()) 1362 return StmtError(); 1363 1364 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1365 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1366 RParenLoc); 1367} 1368 1369/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1370StmtResult 1371Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1372 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1373 Expr *Inc, Stmt *LoopVarDecl, 1374 SourceLocation RParenLoc) { 1375 Scope *S = getCurScope(); 1376 1377 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1378 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1379 QualType RangeVarType = RangeVar->getType(); 1380 1381 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1382 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1383 1384 StmtResult BeginEndDecl = BeginEnd; 1385 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1386 1387 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1388 SourceLocation RangeLoc = RangeVar->getLocation(); 1389 1390 ExprResult RangeRef = BuildDeclRefExpr(RangeVar, 1391 RangeVarType.getNonReferenceType(), 1392 VK_LValue, ColonLoc); 1393 if (RangeRef.isInvalid()) 1394 return StmtError(); 1395 1396 QualType AutoType = Context.getAutoDeductType(); 1397 Expr *Range = RangeVar->getInit(); 1398 if (!Range) 1399 return StmtError(); 1400 QualType RangeType = Range->getType(); 1401 1402 if (RequireCompleteType(RangeLoc, RangeType, 1403 PDiag(diag::err_for_range_incomplete_type))) 1404 return StmtError(); 1405 1406 // Build auto __begin = begin-expr, __end = end-expr. 1407 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1408 "__begin"); 1409 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1410 "__end"); 1411 1412 // Build begin-expr and end-expr and attach to __begin and __end variables. 1413 ExprResult BeginExpr, EndExpr; 1414 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1415 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1416 // __range + __bound, respectively, where __bound is the array bound. If 1417 // _RangeT is an array of unknown size or an array of incomplete type, 1418 // the program is ill-formed; 1419 1420 // begin-expr is __range. 1421 BeginExpr = RangeRef; 1422 if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc, 1423 diag::err_for_range_iter_deduction_failure)) { 1424 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1425 return StmtError(); 1426 } 1427 1428 // Find the array bound. 1429 ExprResult BoundExpr; 1430 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1431 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1432 Context.getPointerDiffType(), 1433 RangeLoc)); 1434 else if (const VariableArrayType *VAT = 1435 dyn_cast<VariableArrayType>(UnqAT)) 1436 BoundExpr = VAT->getSizeExpr(); 1437 else { 1438 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1439 // UnqAT is not incomplete and Range is not type-dependent. 1440 assert(0 && "Unexpected array type in for-range"); 1441 return StmtError(); 1442 } 1443 1444 // end-expr is __range + __bound. 1445 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(), 1446 BoundExpr.get()); 1447 if (EndExpr.isInvalid()) 1448 return StmtError(); 1449 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1450 diag::err_for_range_iter_deduction_failure)) { 1451 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1452 return StmtError(); 1453 } 1454 } else { 1455 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1456 ColonLoc); 1457 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1458 ColonLoc); 1459 1460 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1461 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1462 1463 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1464 // - if _RangeT is a class type, the unqualified-ids begin and end are 1465 // looked up in the scope of class _RangeT as if by class member access 1466 // lookup (3.4.5), and if either (or both) finds at least one 1467 // declaration, begin-expr and end-expr are __range.begin() and 1468 // __range.end(), respectively; 1469 LookupQualifiedName(BeginMemberLookup, D); 1470 LookupQualifiedName(EndMemberLookup, D); 1471 1472 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1473 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1474 << RangeType << BeginMemberLookup.empty(); 1475 return StmtError(); 1476 } 1477 } else { 1478 // - otherwise, begin-expr and end-expr are begin(__range) and 1479 // end(__range), respectively, where begin and end are looked up with 1480 // argument-dependent lookup (3.4.2). For the purposes of this name 1481 // lookup, namespace std is an associated namespace. 1482 } 1483 1484 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1485 BEF_begin, BeginNameInfo, 1486 BeginMemberLookup, RangeRef.get()); 1487 if (BeginExpr.isInvalid()) 1488 return StmtError(); 1489 1490 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1491 BEF_end, EndNameInfo, 1492 EndMemberLookup, RangeRef.get()); 1493 if (EndExpr.isInvalid()) 1494 return StmtError(); 1495 } 1496 1497 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1498 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1499 if (!Context.hasSameType(BeginType, EndType)) { 1500 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1501 << BeginType << EndType; 1502 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1503 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1504 } 1505 1506 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1507 // Claim the type doesn't contain auto: we've already done the checking. 1508 DeclGroupPtrTy BeginEndGroup = 1509 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1510 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1511 1512 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, 1513 BeginType.getNonReferenceType(), 1514 VK_LValue, ColonLoc); 1515 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1516 VK_LValue, ColonLoc); 1517 1518 // Build and check __begin != __end expression. 1519 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1520 BeginRef.get(), EndRef.get()); 1521 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1522 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1523 if (NotEqExpr.isInvalid()) { 1524 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1525 if (!Context.hasSameType(BeginType, EndType)) 1526 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1527 return StmtError(); 1528 } 1529 1530 // Build and check ++__begin expression. 1531 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1532 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1533 if (IncrExpr.isInvalid()) { 1534 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1535 return StmtError(); 1536 } 1537 1538 // Build and check *__begin expression. 1539 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1540 if (DerefExpr.isInvalid()) { 1541 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1542 return StmtError(); 1543 } 1544 1545 // Attach *__begin as initializer for VD. 1546 if (!LoopVar->isInvalidDecl()) { 1547 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1548 /*TypeMayContainAuto=*/true); 1549 if (LoopVar->isInvalidDecl()) 1550 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1551 } 1552 } else { 1553 // The range is implicitly used as a placeholder when it is dependent. 1554 RangeVar->setUsed(); 1555 } 1556 1557 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1558 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1559 NotEqExpr.take(), IncrExpr.take(), 1560 LoopVarDS, /*Body=*/0, ForLoc, 1561 ColonLoc, RParenLoc)); 1562} 1563 1564/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1565/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1566/// body cannot be performed until after the type of the range variable is 1567/// determined. 1568StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1569 if (!S || !B) 1570 return StmtError(); 1571 1572 cast<CXXForRangeStmt>(S)->setBody(B); 1573 return S; 1574} 1575 1576StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1577 SourceLocation LabelLoc, 1578 LabelDecl *TheDecl) { 1579 getCurFunction()->setHasBranchIntoScope(); 1580 TheDecl->setUsed(); 1581 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1582} 1583 1584StmtResult 1585Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1586 Expr *E) { 1587 // Convert operand to void* 1588 if (!E->isTypeDependent()) { 1589 QualType ETy = E->getType(); 1590 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1591 ExprResult ExprRes = Owned(E); 1592 AssignConvertType ConvTy = 1593 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1594 if (ExprRes.isInvalid()) 1595 return StmtError(); 1596 E = ExprRes.take(); 1597 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1598 return StmtError(); 1599 } 1600 1601 getCurFunction()->setHasIndirectGoto(); 1602 1603 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1604} 1605 1606StmtResult 1607Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1608 Scope *S = CurScope->getContinueParent(); 1609 if (!S) { 1610 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1611 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1612 } 1613 1614 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1615} 1616 1617StmtResult 1618Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1619 Scope *S = CurScope->getBreakParent(); 1620 if (!S) { 1621 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1622 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1623 } 1624 1625 return Owned(new (Context) BreakStmt(BreakLoc)); 1626} 1627 1628/// \brief Determine whether the given expression is a candidate for 1629/// copy elision in either a return statement or a throw expression. 1630/// 1631/// \param ReturnType If we're determining the copy elision candidate for 1632/// a return statement, this is the return type of the function. If we're 1633/// determining the copy elision candidate for a throw expression, this will 1634/// be a NULL type. 1635/// 1636/// \param E The expression being returned from the function or block, or 1637/// being thrown. 1638/// 1639/// \param AllowFunctionParameter Whether we allow function parameters to 1640/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1641/// we re-use this logic to determine whether we should try to move as part of 1642/// a return or throw (which does allow function parameters). 1643/// 1644/// \returns The NRVO candidate variable, if the return statement may use the 1645/// NRVO, or NULL if there is no such candidate. 1646const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1647 Expr *E, 1648 bool AllowFunctionParameter) { 1649 QualType ExprType = E->getType(); 1650 // - in a return statement in a function with ... 1651 // ... a class return type ... 1652 if (!ReturnType.isNull()) { 1653 if (!ReturnType->isRecordType()) 1654 return 0; 1655 // ... the same cv-unqualified type as the function return type ... 1656 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1657 return 0; 1658 } 1659 1660 // ... the expression is the name of a non-volatile automatic object 1661 // (other than a function or catch-clause parameter)) ... 1662 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1663 if (!DR) 1664 return 0; 1665 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1666 if (!VD) 1667 return 0; 1668 1669 if (VD->hasLocalStorage() && !VD->isExceptionVariable() && 1670 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1671 !VD->getType().isVolatileQualified() && 1672 ((VD->getKind() == Decl::Var) || 1673 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar))) 1674 return VD; 1675 1676 return 0; 1677} 1678 1679/// \brief Perform the initialization of a potentially-movable value, which 1680/// is the result of return value. 1681/// 1682/// This routine implements C++0x [class.copy]p33, which attempts to treat 1683/// returned lvalues as rvalues in certain cases (to prefer move construction), 1684/// then falls back to treating them as lvalues if that failed. 1685ExprResult 1686Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1687 const VarDecl *NRVOCandidate, 1688 QualType ResultType, 1689 Expr *Value, 1690 bool AllowNRVO) { 1691 // C++0x [class.copy]p33: 1692 // When the criteria for elision of a copy operation are met or would 1693 // be met save for the fact that the source object is a function 1694 // parameter, and the object to be copied is designated by an lvalue, 1695 // overload resolution to select the constructor for the copy is first 1696 // performed as if the object were designated by an rvalue. 1697 ExprResult Res = ExprError(); 1698 if (AllowNRVO && 1699 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 1700 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1701 Value->getType(), CK_LValueToRValue, 1702 Value, VK_XValue); 1703 1704 Expr *InitExpr = &AsRvalue; 1705 InitializationKind Kind 1706 = InitializationKind::CreateCopy(Value->getLocStart(), 1707 Value->getLocStart()); 1708 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1709 1710 // [...] If overload resolution fails, or if the type of the first 1711 // parameter of the selected constructor is not an rvalue reference 1712 // to the object's type (possibly cv-qualified), overload resolution 1713 // is performed again, considering the object as an lvalue. 1714 if (Seq) { 1715 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1716 StepEnd = Seq.step_end(); 1717 Step != StepEnd; ++Step) { 1718 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 1719 continue; 1720 1721 CXXConstructorDecl *Constructor 1722 = cast<CXXConstructorDecl>(Step->Function.Function); 1723 1724 const RValueReferenceType *RRefType 1725 = Constructor->getParamDecl(0)->getType() 1726 ->getAs<RValueReferenceType>(); 1727 1728 // If we don't meet the criteria, break out now. 1729 if (!RRefType || 1730 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1731 Context.getTypeDeclType(Constructor->getParent()))) 1732 break; 1733 1734 // Promote "AsRvalue" to the heap, since we now need this 1735 // expression node to persist. 1736 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1737 CK_LValueToRValue, Value, 0, 1738 VK_XValue); 1739 1740 // Complete type-checking the initialization of the return type 1741 // using the constructor we found. 1742 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1743 } 1744 } 1745 } 1746 1747 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1748 // above, or overload resolution failed. Either way, we need to try 1749 // (again) now with the return value expression as written. 1750 if (Res.isInvalid()) 1751 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1752 1753 return Res; 1754} 1755 1756/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1757/// 1758StmtResult 1759Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1760 // If this is the first return we've seen in the block, infer the type of 1761 // the block from it. 1762 BlockScopeInfo *CurBlock = getCurBlock(); 1763 if (CurBlock->ReturnType.isNull()) { 1764 if (RetValExp) { 1765 // Don't call UsualUnaryConversions(), since we don't want to do 1766 // integer promotions here. 1767 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1768 if (Result.isInvalid()) 1769 return StmtError(); 1770 RetValExp = Result.take(); 1771 1772 if (!RetValExp->isTypeDependent()) { 1773 CurBlock->ReturnType = RetValExp->getType(); 1774 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1775 // We have to remove a 'const' added to copied-in variable which was 1776 // part of the implementation spec. and not the actual qualifier for 1777 // the variable. 1778 if (CDRE->isConstQualAdded()) 1779 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1780 } 1781 } else 1782 CurBlock->ReturnType = Context.DependentTy; 1783 } else 1784 CurBlock->ReturnType = Context.VoidTy; 1785 } 1786 QualType FnRetType = CurBlock->ReturnType; 1787 1788 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1789 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1790 << getCurFunctionOrMethodDecl()->getDeclName(); 1791 return StmtError(); 1792 } 1793 1794 // Otherwise, verify that this result type matches the previous one. We are 1795 // pickier with blocks than for normal functions because we don't have GCC 1796 // compatibility to worry about here. 1797 ReturnStmt *Result = 0; 1798 if (CurBlock->ReturnType->isVoidType()) { 1799 if (RetValExp && !RetValExp->isTypeDependent() && 1800 (!getLangOptions().CPlusPlus || !RetValExp->getType()->isVoidType())) { 1801 Diag(ReturnLoc, diag::err_return_block_has_expr); 1802 RetValExp = 0; 1803 } 1804 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1805 } else if (!RetValExp) { 1806 if (!CurBlock->ReturnType->isDependentType()) 1807 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1808 1809 Result = new (Context) ReturnStmt(ReturnLoc, 0, 0); 1810 } else { 1811 const VarDecl *NRVOCandidate = 0; 1812 1813 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1814 // we have a non-void block with an expression, continue checking 1815 1816 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1817 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1818 // function return. 1819 1820 // In C++ the return statement is handled via a copy initialization. 1821 // the C version of which boils down to CheckSingleAssignmentConstraints. 1822 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1823 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1824 FnRetType, 1825 NRVOCandidate != 0); 1826 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1827 FnRetType, RetValExp); 1828 if (Res.isInvalid()) { 1829 // FIXME: Cleanup temporaries here, anyway? 1830 return StmtError(); 1831 } 1832 1833 if (RetValExp) { 1834 CheckImplicitConversions(RetValExp, ReturnLoc); 1835 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1836 } 1837 1838 RetValExp = Res.takeAs<Expr>(); 1839 if (RetValExp) 1840 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1841 } 1842 1843 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1844 } 1845 1846 // If we need to check for the named return value optimization, save the 1847 // return statement in our scope for later processing. 1848 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1849 !CurContext->isDependentContext()) 1850 FunctionScopes.back()->Returns.push_back(Result); 1851 1852 return Owned(Result); 1853} 1854 1855StmtResult 1856Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1857 // Check for unexpanded parameter packs. 1858 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 1859 return StmtError(); 1860 1861 if (getCurBlock()) 1862 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1863 1864 QualType FnRetType; 1865 QualType DeclaredRetType; 1866 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1867 FnRetType = FD->getResultType(); 1868 DeclaredRetType = FnRetType; 1869 if (FD->hasAttr<NoReturnAttr>() || 1870 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1871 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1872 << getCurFunctionOrMethodDecl()->getDeclName(); 1873 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1874 DeclaredRetType = MD->getResultType(); 1875 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 1876 // In the implementation of a method with a related return type, the 1877 // type used to type-check the validity of return statements within the 1878 // method body is a pointer to the type of the class being implemented. 1879 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 1880 FnRetType = Context.getObjCObjectPointerType(FnRetType); 1881 } else { 1882 FnRetType = DeclaredRetType; 1883 } 1884 } else // If we don't have a function/method context, bail. 1885 return StmtError(); 1886 1887 ReturnStmt *Result = 0; 1888 if (FnRetType->isVoidType()) { 1889 if (RetValExp) { 1890 if (!RetValExp->isTypeDependent()) { 1891 // C99 6.8.6.4p1 (ext_ since GCC warns) 1892 unsigned D = diag::ext_return_has_expr; 1893 if (RetValExp->getType()->isVoidType()) 1894 D = diag::ext_return_has_void_expr; 1895 else { 1896 ExprResult Result = Owned(RetValExp); 1897 Result = IgnoredValueConversions(Result.take()); 1898 if (Result.isInvalid()) 1899 return StmtError(); 1900 RetValExp = Result.take(); 1901 RetValExp = ImpCastExprToType(RetValExp, 1902 Context.VoidTy, CK_ToVoid).take(); 1903 } 1904 1905 // return (some void expression); is legal in C++. 1906 if (D != diag::ext_return_has_void_expr || 1907 !getLangOptions().CPlusPlus) { 1908 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1909 1910 int FunctionKind = 0; 1911 if (isa<ObjCMethodDecl>(CurDecl)) 1912 FunctionKind = 1; 1913 else if (isa<CXXConstructorDecl>(CurDecl)) 1914 FunctionKind = 2; 1915 else if (isa<CXXDestructorDecl>(CurDecl)) 1916 FunctionKind = 3; 1917 1918 Diag(ReturnLoc, D) 1919 << CurDecl->getDeclName() << FunctionKind 1920 << RetValExp->getSourceRange(); 1921 } 1922 } 1923 1924 CheckImplicitConversions(RetValExp, ReturnLoc); 1925 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1926 } 1927 1928 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1929 } else if (!RetValExp && !FnRetType->isDependentType()) { 1930 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1931 // C99 6.8.6.4p1 (ext_ since GCC warns) 1932 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1933 1934 if (FunctionDecl *FD = getCurFunctionDecl()) 1935 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1936 else 1937 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1938 Result = new (Context) ReturnStmt(ReturnLoc); 1939 } else { 1940 const VarDecl *NRVOCandidate = 0; 1941 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1942 // we have a non-void function with an expression, continue checking 1943 1944 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1945 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1946 // function return. 1947 1948 // In C++ the return statement is handled via a copy initialization, 1949 // the C version of which boils down to CheckSingleAssignmentConstraints. 1950 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1951 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1952 FnRetType, 1953 NRVOCandidate != 0); 1954 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1955 FnRetType, RetValExp); 1956 if (Res.isInvalid()) { 1957 // FIXME: Cleanup temporaries here, anyway? 1958 return StmtError(); 1959 } 1960 1961 RetValExp = Res.takeAs<Expr>(); 1962 if (RetValExp) 1963 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1964 } 1965 1966 if (RetValExp) { 1967 // If we type-checked an Objective-C method's return type based 1968 // on a related return type, we may need to adjust the return 1969 // type again. Do so now. 1970 if (DeclaredRetType != FnRetType) { 1971 ExprResult result = PerformImplicitConversion(RetValExp, 1972 DeclaredRetType, 1973 AA_Returning); 1974 if (result.isInvalid()) return StmtError(); 1975 RetValExp = result.take(); 1976 } 1977 1978 CheckImplicitConversions(RetValExp, ReturnLoc); 1979 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1980 } 1981 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1982 } 1983 1984 // If we need to check for the named return value optimization, save the 1985 // return statement in our scope for later processing. 1986 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1987 !CurContext->isDependentContext()) 1988 FunctionScopes.back()->Returns.push_back(Result); 1989 1990 return Owned(Result); 1991} 1992 1993/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1994/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1995/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1996/// provide a strong guidance to not use it. 1997/// 1998/// This method checks to see if the argument is an acceptable l-value and 1999/// returns false if it is a case we can handle. 2000static bool CheckAsmLValue(const Expr *E, Sema &S) { 2001 // Type dependent expressions will be checked during instantiation. 2002 if (E->isTypeDependent()) 2003 return false; 2004 2005 if (E->isLValue()) 2006 return false; // Cool, this is an lvalue. 2007 2008 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 2009 // are supposed to allow. 2010 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 2011 if (E != E2 && E2->isLValue()) { 2012 if (!S.getLangOptions().HeinousExtensions) 2013 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 2014 << E->getSourceRange(); 2015 else 2016 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 2017 << E->getSourceRange(); 2018 // Accept, even if we emitted an error diagnostic. 2019 return false; 2020 } 2021 2022 // None of the above, just randomly invalid non-lvalue. 2023 return true; 2024} 2025 2026/// isOperandMentioned - Return true if the specified operand # is mentioned 2027/// anywhere in the decomposed asm string. 2028static bool isOperandMentioned(unsigned OpNo, 2029 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 2030 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 2031 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 2032 if (!Piece.isOperand()) continue; 2033 2034 // If this is a reference to the input and if the input was the smaller 2035 // one, then we have to reject this asm. 2036 if (Piece.getOperandNo() == OpNo) 2037 return true; 2038 } 2039 2040 return false; 2041} 2042 2043StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2044 bool IsVolatile, unsigned NumOutputs, 2045 unsigned NumInputs, IdentifierInfo **Names, 2046 MultiExprArg constraints, MultiExprArg exprs, 2047 Expr *asmString, MultiExprArg clobbers, 2048 SourceLocation RParenLoc, bool MSAsm) { 2049 unsigned NumClobbers = clobbers.size(); 2050 StringLiteral **Constraints = 2051 reinterpret_cast<StringLiteral**>(constraints.get()); 2052 Expr **Exprs = exprs.get(); 2053 StringLiteral *AsmString = cast<StringLiteral>(asmString); 2054 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 2055 2056 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2057 2058 // The parser verifies that there is a string literal here. 2059 if (!AsmString->isAscii()) 2060 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 2061 << AsmString->getSourceRange()); 2062 2063 for (unsigned i = 0; i != NumOutputs; i++) { 2064 StringLiteral *Literal = Constraints[i]; 2065 if (!Literal->isAscii()) 2066 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2067 << Literal->getSourceRange()); 2068 2069 StringRef OutputName; 2070 if (Names[i]) 2071 OutputName = Names[i]->getName(); 2072 2073 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 2074 if (!Context.Target.validateOutputConstraint(Info)) 2075 return StmtError(Diag(Literal->getLocStart(), 2076 diag::err_asm_invalid_output_constraint) 2077 << Info.getConstraintStr()); 2078 2079 // Check that the output exprs are valid lvalues. 2080 Expr *OutputExpr = Exprs[i]; 2081 if (CheckAsmLValue(OutputExpr, *this)) { 2082 return StmtError(Diag(OutputExpr->getLocStart(), 2083 diag::err_asm_invalid_lvalue_in_output) 2084 << OutputExpr->getSourceRange()); 2085 } 2086 2087 OutputConstraintInfos.push_back(Info); 2088 } 2089 2090 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2091 2092 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 2093 StringLiteral *Literal = Constraints[i]; 2094 if (!Literal->isAscii()) 2095 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2096 << Literal->getSourceRange()); 2097 2098 StringRef InputName; 2099 if (Names[i]) 2100 InputName = Names[i]->getName(); 2101 2102 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 2103 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 2104 NumOutputs, Info)) { 2105 return StmtError(Diag(Literal->getLocStart(), 2106 diag::err_asm_invalid_input_constraint) 2107 << Info.getConstraintStr()); 2108 } 2109 2110 Expr *InputExpr = Exprs[i]; 2111 2112 // Only allow void types for memory constraints. 2113 if (Info.allowsMemory() && !Info.allowsRegister()) { 2114 if (CheckAsmLValue(InputExpr, *this)) 2115 return StmtError(Diag(InputExpr->getLocStart(), 2116 diag::err_asm_invalid_lvalue_in_input) 2117 << Info.getConstraintStr() 2118 << InputExpr->getSourceRange()); 2119 } 2120 2121 if (Info.allowsRegister()) { 2122 if (InputExpr->getType()->isVoidType()) { 2123 return StmtError(Diag(InputExpr->getLocStart(), 2124 diag::err_asm_invalid_type_in_input) 2125 << InputExpr->getType() << Info.getConstraintStr() 2126 << InputExpr->getSourceRange()); 2127 } 2128 } 2129 2130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 2131 if (Result.isInvalid()) 2132 return StmtError(); 2133 2134 Exprs[i] = Result.take(); 2135 InputConstraintInfos.push_back(Info); 2136 } 2137 2138 // Check that the clobbers are valid. 2139 for (unsigned i = 0; i != NumClobbers; i++) { 2140 StringLiteral *Literal = Clobbers[i]; 2141 if (!Literal->isAscii()) 2142 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2143 << Literal->getSourceRange()); 2144 2145 StringRef Clobber = Literal->getString(); 2146 2147 if (!Context.Target.isValidClobber(Clobber)) 2148 return StmtError(Diag(Literal->getLocStart(), 2149 diag::err_asm_unknown_register_name) << Clobber); 2150 } 2151 2152 AsmStmt *NS = 2153 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 2154 NumOutputs, NumInputs, Names, Constraints, Exprs, 2155 AsmString, NumClobbers, Clobbers, RParenLoc); 2156 // Validate the asm string, ensuring it makes sense given the operands we 2157 // have. 2158 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 2159 unsigned DiagOffs; 2160 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 2161 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 2162 << AsmString->getSourceRange(); 2163 return StmtError(); 2164 } 2165 2166 // Validate tied input operands for type mismatches. 2167 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 2168 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2169 2170 // If this is a tied constraint, verify that the output and input have 2171 // either exactly the same type, or that they are int/ptr operands with the 2172 // same size (int/long, int*/long, are ok etc). 2173 if (!Info.hasTiedOperand()) continue; 2174 2175 unsigned TiedTo = Info.getTiedOperand(); 2176 unsigned InputOpNo = i+NumOutputs; 2177 Expr *OutputExpr = Exprs[TiedTo]; 2178 Expr *InputExpr = Exprs[InputOpNo]; 2179 QualType InTy = InputExpr->getType(); 2180 QualType OutTy = OutputExpr->getType(); 2181 if (Context.hasSameType(InTy, OutTy)) 2182 continue; // All types can be tied to themselves. 2183 2184 // Decide if the input and output are in the same domain (integer/ptr or 2185 // floating point. 2186 enum AsmDomain { 2187 AD_Int, AD_FP, AD_Other 2188 } InputDomain, OutputDomain; 2189 2190 if (InTy->isIntegerType() || InTy->isPointerType()) 2191 InputDomain = AD_Int; 2192 else if (InTy->isRealFloatingType()) 2193 InputDomain = AD_FP; 2194 else 2195 InputDomain = AD_Other; 2196 2197 if (OutTy->isIntegerType() || OutTy->isPointerType()) 2198 OutputDomain = AD_Int; 2199 else if (OutTy->isRealFloatingType()) 2200 OutputDomain = AD_FP; 2201 else 2202 OutputDomain = AD_Other; 2203 2204 // They are ok if they are the same size and in the same domain. This 2205 // allows tying things like: 2206 // void* to int* 2207 // void* to int if they are the same size. 2208 // double to long double if they are the same size. 2209 // 2210 uint64_t OutSize = Context.getTypeSize(OutTy); 2211 uint64_t InSize = Context.getTypeSize(InTy); 2212 if (OutSize == InSize && InputDomain == OutputDomain && 2213 InputDomain != AD_Other) 2214 continue; 2215 2216 // If the smaller input/output operand is not mentioned in the asm string, 2217 // then we can promote the smaller one to a larger input and the asm string 2218 // won't notice. 2219 bool SmallerValueMentioned = false; 2220 2221 // If this is a reference to the input and if the input was the smaller 2222 // one, then we have to reject this asm. 2223 if (isOperandMentioned(InputOpNo, Pieces)) { 2224 // This is a use in the asm string of the smaller operand. Since we 2225 // codegen this by promoting to a wider value, the asm will get printed 2226 // "wrong". 2227 SmallerValueMentioned |= InSize < OutSize; 2228 } 2229 if (isOperandMentioned(TiedTo, Pieces)) { 2230 // If this is a reference to the output, and if the output is the larger 2231 // value, then it's ok because we'll promote the input to the larger type. 2232 SmallerValueMentioned |= OutSize < InSize; 2233 } 2234 2235 // If the smaller value wasn't mentioned in the asm string, and if the 2236 // output was a register, just extend the shorter one to the size of the 2237 // larger one. 2238 if (!SmallerValueMentioned && InputDomain != AD_Other && 2239 OutputConstraintInfos[TiedTo].allowsRegister()) 2240 continue; 2241 2242 // Either both of the operands were mentioned or the smaller one was 2243 // mentioned. One more special case that we'll allow: if the tied input is 2244 // integer, unmentioned, and is a constant, then we'll allow truncating it 2245 // down to the size of the destination. 2246 if (InputDomain == AD_Int && OutputDomain == AD_Int && 2247 !isOperandMentioned(InputOpNo, Pieces) && 2248 InputExpr->isEvaluatable(Context)) { 2249 CastKind castKind = 2250 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 2251 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 2252 Exprs[InputOpNo] = InputExpr; 2253 NS->setInputExpr(i, InputExpr); 2254 continue; 2255 } 2256 2257 Diag(InputExpr->getLocStart(), 2258 diag::err_asm_tying_incompatible_types) 2259 << InTy << OutTy << OutputExpr->getSourceRange() 2260 << InputExpr->getSourceRange(); 2261 return StmtError(); 2262 } 2263 2264 return Owned(NS); 2265} 2266 2267StmtResult 2268Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2269 SourceLocation RParen, Decl *Parm, 2270 Stmt *Body) { 2271 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2272 if (Var && Var->isInvalidDecl()) 2273 return StmtError(); 2274 2275 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2276} 2277 2278StmtResult 2279Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2280 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2281} 2282 2283StmtResult 2284Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2285 MultiStmtArg CatchStmts, Stmt *Finally) { 2286 if (!getLangOptions().ObjCExceptions) 2287 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2288 2289 getCurFunction()->setHasBranchProtectedScope(); 2290 unsigned NumCatchStmts = CatchStmts.size(); 2291 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2292 CatchStmts.release(), 2293 NumCatchStmts, 2294 Finally)); 2295} 2296 2297StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 2298 Expr *Throw) { 2299 if (Throw) { 2300 Throw = MaybeCreateExprWithCleanups(Throw); 2301 ExprResult Result = DefaultLvalueConversion(Throw); 2302 if (Result.isInvalid()) 2303 return StmtError(); 2304 2305 Throw = Result.take(); 2306 QualType ThrowType = Throw->getType(); 2307 // Make sure the expression type is an ObjC pointer or "void *". 2308 if (!ThrowType->isDependentType() && 2309 !ThrowType->isObjCObjectPointerType()) { 2310 const PointerType *PT = ThrowType->getAs<PointerType>(); 2311 if (!PT || !PT->getPointeeType()->isVoidType()) 2312 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2313 << Throw->getType() << Throw->getSourceRange()); 2314 } 2315 } 2316 2317 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2318} 2319 2320StmtResult 2321Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2322 Scope *CurScope) { 2323 if (!getLangOptions().ObjCExceptions) 2324 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2325 2326 if (!Throw) { 2327 // @throw without an expression designates a rethrow (which much occur 2328 // in the context of an @catch clause). 2329 Scope *AtCatchParent = CurScope; 2330 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2331 AtCatchParent = AtCatchParent->getParent(); 2332 if (!AtCatchParent) 2333 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2334 } 2335 2336 return BuildObjCAtThrowStmt(AtLoc, Throw); 2337} 2338 2339ExprResult 2340Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 2341 ExprResult result = DefaultLvalueConversion(operand); 2342 if (result.isInvalid()) 2343 return ExprError(); 2344 operand = result.take(); 2345 2346 // Make sure the expression type is an ObjC pointer or "void *". 2347 QualType type = operand->getType(); 2348 if (!type->isDependentType() && 2349 !type->isObjCObjectPointerType()) { 2350 const PointerType *pointerType = type->getAs<PointerType>(); 2351 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 2352 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 2353 << type << operand->getSourceRange(); 2354 } 2355 2356 // The operand to @synchronized is a full-expression. 2357 return MaybeCreateExprWithCleanups(operand); 2358} 2359 2360StmtResult 2361Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2362 Stmt *SyncBody) { 2363 // We can't jump into or indirect-jump out of a @synchronized block. 2364 getCurFunction()->setHasBranchProtectedScope(); 2365 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2366} 2367 2368/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2369/// and creates a proper catch handler from them. 2370StmtResult 2371Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2372 Stmt *HandlerBlock) { 2373 // There's nothing to test that ActOnExceptionDecl didn't already test. 2374 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2375 cast_or_null<VarDecl>(ExDecl), 2376 HandlerBlock)); 2377} 2378 2379StmtResult 2380Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 2381 getCurFunction()->setHasBranchProtectedScope(); 2382 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 2383} 2384 2385namespace { 2386 2387class TypeWithHandler { 2388 QualType t; 2389 CXXCatchStmt *stmt; 2390public: 2391 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2392 : t(type), stmt(statement) {} 2393 2394 // An arbitrary order is fine as long as it places identical 2395 // types next to each other. 2396 bool operator<(const TypeWithHandler &y) const { 2397 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2398 return true; 2399 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2400 return false; 2401 else 2402 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2403 } 2404 2405 bool operator==(const TypeWithHandler& other) const { 2406 return t == other.t; 2407 } 2408 2409 CXXCatchStmt *getCatchStmt() const { return stmt; } 2410 SourceLocation getTypeSpecStartLoc() const { 2411 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2412 } 2413}; 2414 2415} 2416 2417/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2418/// handlers and creates a try statement from them. 2419StmtResult 2420Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2421 MultiStmtArg RawHandlers) { 2422 // Don't report an error if 'try' is used in system headers. 2423 if (!getLangOptions().CXXExceptions && 2424 !getSourceManager().isInSystemHeader(TryLoc)) 2425 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2426 2427 unsigned NumHandlers = RawHandlers.size(); 2428 assert(NumHandlers > 0 && 2429 "The parser shouldn't call this if there are no handlers."); 2430 Stmt **Handlers = RawHandlers.get(); 2431 2432 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2433 2434 for (unsigned i = 0; i < NumHandlers; ++i) { 2435 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 2436 if (!Handler->getExceptionDecl()) { 2437 if (i < NumHandlers - 1) 2438 return StmtError(Diag(Handler->getLocStart(), 2439 diag::err_early_catch_all)); 2440 2441 continue; 2442 } 2443 2444 const QualType CaughtType = Handler->getCaughtType(); 2445 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2446 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2447 } 2448 2449 // Detect handlers for the same type as an earlier one. 2450 if (NumHandlers > 1) { 2451 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2452 2453 TypeWithHandler prev = TypesWithHandlers[0]; 2454 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2455 TypeWithHandler curr = TypesWithHandlers[i]; 2456 2457 if (curr == prev) { 2458 Diag(curr.getTypeSpecStartLoc(), 2459 diag::warn_exception_caught_by_earlier_handler) 2460 << curr.getCatchStmt()->getCaughtType().getAsString(); 2461 Diag(prev.getTypeSpecStartLoc(), 2462 diag::note_previous_exception_handler) 2463 << prev.getCatchStmt()->getCaughtType().getAsString(); 2464 } 2465 2466 prev = curr; 2467 } 2468 } 2469 2470 getCurFunction()->setHasBranchProtectedScope(); 2471 2472 // FIXME: We should detect handlers that cannot catch anything because an 2473 // earlier handler catches a superclass. Need to find a method that is not 2474 // quadratic for this. 2475 // Neither of these are explicitly forbidden, but every compiler detects them 2476 // and warns. 2477 2478 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2479 Handlers, NumHandlers)); 2480} 2481 2482StmtResult 2483Sema::ActOnSEHTryBlock(bool IsCXXTry, 2484 SourceLocation TryLoc, 2485 Stmt *TryBlock, 2486 Stmt *Handler) { 2487 assert(TryBlock && Handler); 2488 2489 getCurFunction()->setHasBranchProtectedScope(); 2490 2491 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2492} 2493 2494StmtResult 2495Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2496 Expr *FilterExpr, 2497 Stmt *Block) { 2498 assert(FilterExpr && Block); 2499 2500 if(!FilterExpr->getType()->isIntegerType()) { 2501 return StmtError(Diag(FilterExpr->getExprLoc(), 2502 diag::err_filter_expression_integral) 2503 << FilterExpr->getType()); 2504 } 2505 2506 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2507} 2508 2509StmtResult 2510Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2511 Stmt *Block) { 2512 assert(Block); 2513 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2514} 2515