Home | History | Annotate | Download | only in Sema
      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/AST/ASTContext.h"
     16 #include "clang/AST/ASTDiagnostic.h"
     17 #include "clang/AST/CharUnits.h"
     18 #include "clang/AST/DeclObjC.h"
     19 #include "clang/AST/EvaluatedExprVisitor.h"
     20 #include "clang/AST/ExprCXX.h"
     21 #include "clang/AST/ExprObjC.h"
     22 #include "clang/AST/StmtCXX.h"
     23 #include "clang/AST/StmtObjC.h"
     24 #include "clang/AST/TypeLoc.h"
     25 #include "clang/Basic/TargetInfo.h"
     26 #include "clang/Lex/Preprocessor.h"
     27 #include "clang/Sema/Initialization.h"
     28 #include "clang/Sema/Lookup.h"
     29 #include "clang/Sema/Scope.h"
     30 #include "clang/Sema/ScopeInfo.h"
     31 #include "llvm/ADT/ArrayRef.h"
     32 #include "llvm/ADT/STLExtras.h"
     33 #include "llvm/ADT/SmallPtrSet.h"
     34 #include "llvm/ADT/SmallString.h"
     35 #include "llvm/ADT/SmallVector.h"
     36 using namespace clang;
     37 using namespace sema;
     38 
     39 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
     40   if (FE.isInvalid())
     41     return StmtError();
     42 
     43   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
     44                            /*DiscardedValue*/ true);
     45   if (FE.isInvalid())
     46     return StmtError();
     47 
     48   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
     49   // void expression for its side effects.  Conversion to void allows any
     50   // operand, even incomplete types.
     51 
     52   // Same thing in for stmt first clause (when expr) and third clause.
     53   return Owned(static_cast<Stmt*>(FE.take()));
     54 }
     55 
     56 
     57 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
     58                                bool HasLeadingEmptyMacro) {
     59   return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
     60 }
     61 
     62 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
     63                                SourceLocation EndLoc) {
     64   DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
     65 
     66   // If we have an invalid decl, just return an error.
     67   if (DG.isNull()) return StmtError();
     68 
     69   return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
     70 }
     71 
     72 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
     73   DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
     74 
     75   // If we have an invalid decl, just return.
     76   if (DG.isNull() || !DG.isSingleDecl()) return;
     77   VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
     78 
     79   // suppress any potential 'unused variable' warning.
     80   var->setUsed();
     81 
     82   // foreach variables are never actually initialized in the way that
     83   // the parser came up with.
     84   var->setInit(0);
     85 
     86   // In ARC, we don't need to retain the iteration variable of a fast
     87   // enumeration loop.  Rather than actually trying to catch that
     88   // during declaration processing, we remove the consequences here.
     89   if (getLangOpts().ObjCAutoRefCount) {
     90     QualType type = var->getType();
     91 
     92     // Only do this if we inferred the lifetime.  Inferred lifetime
     93     // will show up as a local qualifier because explicit lifetime
     94     // should have shown up as an AttributedType instead.
     95     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
     96       // Add 'const' and mark the variable as pseudo-strong.
     97       var->setType(type.withConst());
     98       var->setARCPseudoStrong(true);
     99     }
    100   }
    101 }
    102 
    103 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
    104 ///
    105 /// Adding a cast to void (or other expression wrappers) will prevent the
    106 /// warning from firing.
    107 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
    108   SourceLocation Loc;
    109   bool IsNotEqual, CanAssign;
    110 
    111   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
    112     if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
    113       return false;
    114 
    115     Loc = Op->getOperatorLoc();
    116     IsNotEqual = Op->getOpcode() == BO_NE;
    117     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
    118   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
    119     if (Op->getOperator() != OO_EqualEqual &&
    120         Op->getOperator() != OO_ExclaimEqual)
    121       return false;
    122 
    123     Loc = Op->getOperatorLoc();
    124     IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
    125     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
    126   } else {
    127     // Not a typo-prone comparison.
    128     return false;
    129   }
    130 
    131   // Suppress warnings when the operator, suspicious as it may be, comes from
    132   // a macro expansion.
    133   if (S.SourceMgr.isMacroBodyExpansion(Loc))
    134     return false;
    135 
    136   S.Diag(Loc, diag::warn_unused_comparison)
    137     << (unsigned)IsNotEqual << E->getSourceRange();
    138 
    139   // If the LHS is a plausible entity to assign to, provide a fixit hint to
    140   // correct common typos.
    141   if (CanAssign) {
    142     if (IsNotEqual)
    143       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
    144         << FixItHint::CreateReplacement(Loc, "|=");
    145     else
    146       S.Diag(Loc, diag::note_equality_comparison_to_assign)
    147         << FixItHint::CreateReplacement(Loc, "=");
    148   }
    149 
    150   return true;
    151 }
    152 
    153 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
    154   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
    155     return DiagnoseUnusedExprResult(Label->getSubStmt());
    156 
    157   const Expr *E = dyn_cast_or_null<Expr>(S);
    158   if (!E)
    159     return;
    160   SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
    161   // In most cases, we don't want to warn if the expression is written in a
    162   // macro body, or if the macro comes from a system header. If the offending
    163   // expression is a call to a function with the warn_unused_result attribute,
    164   // we warn no matter the location. Because of the order in which the various
    165   // checks need to happen, we factor out the macro-related test here.
    166   bool ShouldSuppress =
    167       SourceMgr.isMacroBodyExpansion(ExprLoc) ||
    168       SourceMgr.isInSystemMacro(ExprLoc);
    169 
    170   const Expr *WarnExpr;
    171   SourceLocation Loc;
    172   SourceRange R1, R2;
    173   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
    174     return;
    175 
    176   // If this is a GNU statement expression expanded from a macro, it is probably
    177   // unused because it is a function-like macro that can be used as either an
    178   // expression or statement.  Don't warn, because it is almost certainly a
    179   // false positive.
    180   if (isa<StmtExpr>(E) && Loc.isMacroID())
    181     return;
    182 
    183   // Okay, we have an unused result.  Depending on what the base expression is,
    184   // we might want to make a more specific diagnostic.  Check for one of these
    185   // cases now.
    186   unsigned DiagID = diag::warn_unused_expr;
    187   if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
    188     E = Temps->getSubExpr();
    189   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
    190     E = TempExpr->getSubExpr();
    191 
    192   if (DiagnoseUnusedComparison(*this, E))
    193     return;
    194 
    195   E = WarnExpr;
    196   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
    197     if (E->getType()->isVoidType())
    198       return;
    199 
    200     // If the callee has attribute pure, const, or warn_unused_result, warn with
    201     // a more specific message to make it clear what is happening. If the call
    202     // is written in a macro body, only warn if it has the warn_unused_result
    203     // attribute.
    204     if (const Decl *FD = CE->getCalleeDecl()) {
    205       if (FD->getAttr<WarnUnusedResultAttr>()) {
    206         Diag(Loc, diag::warn_unused_result) << R1 << R2;
    207         return;
    208       }
    209       if (ShouldSuppress)
    210         return;
    211       if (FD->getAttr<PureAttr>()) {
    212         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
    213         return;
    214       }
    215       if (FD->getAttr<ConstAttr>()) {
    216         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
    217         return;
    218       }
    219     }
    220   } else if (ShouldSuppress)
    221     return;
    222 
    223   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
    224     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
    225       Diag(Loc, diag::err_arc_unused_init_message) << R1;
    226       return;
    227     }
    228     const ObjCMethodDecl *MD = ME->getMethodDecl();
    229     if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
    230       Diag(Loc, diag::warn_unused_result) << R1 << R2;
    231       return;
    232     }
    233   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
    234     const Expr *Source = POE->getSyntacticForm();
    235     if (isa<ObjCSubscriptRefExpr>(Source))
    236       DiagID = diag::warn_unused_container_subscript_expr;
    237     else
    238       DiagID = diag::warn_unused_property_expr;
    239   } else if (const CXXFunctionalCastExpr *FC
    240                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
    241     if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
    242         isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
    243       return;
    244   }
    245   // Diagnose "(void*) blah" as a typo for "(void) blah".
    246   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
    247     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
    248     QualType T = TI->getType();
    249 
    250     // We really do want to use the non-canonical type here.
    251     if (T == Context.VoidPtrTy) {
    252       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
    253 
    254       Diag(Loc, diag::warn_unused_voidptr)
    255         << FixItHint::CreateRemoval(TL.getStarLoc());
    256       return;
    257     }
    258   }
    259 
    260   if (E->isGLValue() && E->getType().isVolatileQualified()) {
    261     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
    262     return;
    263   }
    264 
    265   DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
    266 }
    267 
    268 void Sema::ActOnStartOfCompoundStmt() {
    269   PushCompoundScope();
    270 }
    271 
    272 void Sema::ActOnFinishOfCompoundStmt() {
    273   PopCompoundScope();
    274 }
    275 
    276 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
    277   return getCurFunction()->CompoundScopes.back();
    278 }
    279 
    280 StmtResult
    281 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
    282                         MultiStmtArg elts, bool isStmtExpr) {
    283   unsigned NumElts = elts.size();
    284   Stmt **Elts = elts.data();
    285   // If we're in C89 mode, check that we don't have any decls after stmts.  If
    286   // so, emit an extension diagnostic.
    287   if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
    288     // Note that __extension__ can be around a decl.
    289     unsigned i = 0;
    290     // Skip over all declarations.
    291     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
    292       /*empty*/;
    293 
    294     // We found the end of the list or a statement.  Scan for another declstmt.
    295     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
    296       /*empty*/;
    297 
    298     if (i != NumElts) {
    299       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
    300       Diag(D->getLocation(), diag::ext_mixed_decls_code);
    301     }
    302   }
    303   // Warn about unused expressions in statements.
    304   for (unsigned i = 0; i != NumElts; ++i) {
    305     // Ignore statements that are last in a statement expression.
    306     if (isStmtExpr && i == NumElts - 1)
    307       continue;
    308 
    309     DiagnoseUnusedExprResult(Elts[i]);
    310   }
    311 
    312   // Check for suspicious empty body (null statement) in `for' and `while'
    313   // statements.  Don't do anything for template instantiations, this just adds
    314   // noise.
    315   if (NumElts != 0 && !CurrentInstantiationScope &&
    316       getCurCompoundScope().HasEmptyLoopBodies) {
    317     for (unsigned i = 0; i != NumElts - 1; ++i)
    318       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
    319   }
    320 
    321   return Owned(new (Context) CompoundStmt(Context,
    322                                           llvm::makeArrayRef(Elts, NumElts),
    323                                           L, R));
    324 }
    325 
    326 StmtResult
    327 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
    328                     SourceLocation DotDotDotLoc, Expr *RHSVal,
    329                     SourceLocation ColonLoc) {
    330   assert((LHSVal != 0) && "missing expression in case statement");
    331 
    332   if (getCurFunction()->SwitchStack.empty()) {
    333     Diag(CaseLoc, diag::err_case_not_in_switch);
    334     return StmtError();
    335   }
    336 
    337   if (!getLangOpts().CPlusPlus11) {
    338     // C99 6.8.4.2p3: The expression shall be an integer constant.
    339     // However, GCC allows any evaluatable integer expression.
    340     if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
    341       LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
    342       if (!LHSVal)
    343         return StmtError();
    344     }
    345 
    346     // GCC extension: The expression shall be an integer constant.
    347 
    348     if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
    349       RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
    350       // Recover from an error by just forgetting about it.
    351     }
    352   }
    353 
    354   LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
    355                                getLangOpts().CPlusPlus11).take();
    356   if (RHSVal)
    357     RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
    358                                  getLangOpts().CPlusPlus11).take();
    359 
    360   CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
    361                                         ColonLoc);
    362   getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
    363   return Owned(CS);
    364 }
    365 
    366 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
    367 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
    368   DiagnoseUnusedExprResult(SubStmt);
    369 
    370   CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
    371   CS->setSubStmt(SubStmt);
    372 }
    373 
    374 StmtResult
    375 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
    376                        Stmt *SubStmt, Scope *CurScope) {
    377   DiagnoseUnusedExprResult(SubStmt);
    378 
    379   if (getCurFunction()->SwitchStack.empty()) {
    380     Diag(DefaultLoc, diag::err_default_not_in_switch);
    381     return Owned(SubStmt);
    382   }
    383 
    384   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
    385   getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
    386   return Owned(DS);
    387 }
    388 
    389 StmtResult
    390 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
    391                      SourceLocation ColonLoc, Stmt *SubStmt) {
    392   // If the label was multiply defined, reject it now.
    393   if (TheDecl->getStmt()) {
    394     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
    395     Diag(TheDecl->getLocation(), diag::note_previous_definition);
    396     return Owned(SubStmt);
    397   }
    398 
    399   // Otherwise, things are good.  Fill in the declaration and return it.
    400   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
    401   TheDecl->setStmt(LS);
    402   if (!TheDecl->isGnuLocal()) {
    403     TheDecl->setLocStart(IdentLoc);
    404     TheDecl->setLocation(IdentLoc);
    405   }
    406   return Owned(LS);
    407 }
    408 
    409 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
    410                                      ArrayRef<const Attr*> Attrs,
    411                                      Stmt *SubStmt) {
    412   // Fill in the declaration and return it.
    413   AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
    414   return Owned(LS);
    415 }
    416 
    417 StmtResult
    418 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
    419                   Stmt *thenStmt, SourceLocation ElseLoc,
    420                   Stmt *elseStmt) {
    421   // If the condition was invalid, discard the if statement.  We could recover
    422   // better by replacing it with a valid expr, but don't do that yet.
    423   if (!CondVal.get() && !CondVar) {
    424     getCurFunction()->setHasDroppedStmt();
    425     return StmtError();
    426   }
    427 
    428   ExprResult CondResult(CondVal.release());
    429 
    430   VarDecl *ConditionVar = 0;
    431   if (CondVar) {
    432     ConditionVar = cast<VarDecl>(CondVar);
    433     CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
    434     if (CondResult.isInvalid())
    435       return StmtError();
    436   }
    437   Expr *ConditionExpr = CondResult.takeAs<Expr>();
    438   if (!ConditionExpr)
    439     return StmtError();
    440 
    441   DiagnoseUnusedExprResult(thenStmt);
    442 
    443   if (!elseStmt) {
    444     DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
    445                           diag::warn_empty_if_body);
    446   }
    447 
    448   DiagnoseUnusedExprResult(elseStmt);
    449 
    450   return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
    451                                     thenStmt, ElseLoc, elseStmt));
    452 }
    453 
    454 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
    455 /// the specified width and sign.  If an overflow occurs, detect it and emit
    456 /// the specified diagnostic.
    457 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
    458                                               unsigned NewWidth, bool NewSign,
    459                                               SourceLocation Loc,
    460                                               unsigned DiagID) {
    461   // Perform a conversion to the promoted condition type if needed.
    462   if (NewWidth > Val.getBitWidth()) {
    463     // If this is an extension, just do it.
    464     Val = Val.extend(NewWidth);
    465     Val.setIsSigned(NewSign);
    466 
    467     // If the input was signed and negative and the output is
    468     // unsigned, don't bother to warn: this is implementation-defined
    469     // behavior.
    470     // FIXME: Introduce a second, default-ignored warning for this case?
    471   } else if (NewWidth < Val.getBitWidth()) {
    472     // If this is a truncation, check for overflow.
    473     llvm::APSInt ConvVal(Val);
    474     ConvVal = ConvVal.trunc(NewWidth);
    475     ConvVal.setIsSigned(NewSign);
    476     ConvVal = ConvVal.extend(Val.getBitWidth());
    477     ConvVal.setIsSigned(Val.isSigned());
    478     if (ConvVal != Val)
    479       Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
    480 
    481     // Regardless of whether a diagnostic was emitted, really do the
    482     // truncation.
    483     Val = Val.trunc(NewWidth);
    484     Val.setIsSigned(NewSign);
    485   } else if (NewSign != Val.isSigned()) {
    486     // Convert the sign to match the sign of the condition.  This can cause
    487     // overflow as well: unsigned(INTMIN)
    488     // We don't diagnose this overflow, because it is implementation-defined
    489     // behavior.
    490     // FIXME: Introduce a second, default-ignored warning for this case?
    491     llvm::APSInt OldVal(Val);
    492     Val.setIsSigned(NewSign);
    493   }
    494 }
    495 
    496 namespace {
    497   struct CaseCompareFunctor {
    498     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
    499                     const llvm::APSInt &RHS) {
    500       return LHS.first < RHS;
    501     }
    502     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
    503                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
    504       return LHS.first < RHS.first;
    505     }
    506     bool operator()(const llvm::APSInt &LHS,
    507                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
    508       return LHS < RHS.first;
    509     }
    510   };
    511 }
    512 
    513 /// CmpCaseVals - Comparison predicate for sorting case values.
    514 ///
    515 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
    516                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
    517   if (lhs.first < rhs.first)
    518     return true;
    519 
    520   if (lhs.first == rhs.first &&
    521       lhs.second->getCaseLoc().getRawEncoding()
    522        < rhs.second->getCaseLoc().getRawEncoding())
    523     return true;
    524   return false;
    525 }
    526 
    527 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
    528 ///
    529 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
    530                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
    531 {
    532   return lhs.first < rhs.first;
    533 }
    534 
    535 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
    536 ///
    537 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
    538                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
    539 {
    540   return lhs.first == rhs.first;
    541 }
    542 
    543 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
    544 /// potentially integral-promoted expression @p expr.
    545 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
    546   if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
    547     expr = cleanups->getSubExpr();
    548   while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
    549     if (impcast->getCastKind() != CK_IntegralCast) break;
    550     expr = impcast->getSubExpr();
    551   }
    552   return expr->getType();
    553 }
    554 
    555 StmtResult
    556 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
    557                              Decl *CondVar) {
    558   ExprResult CondResult;
    559 
    560   VarDecl *ConditionVar = 0;
    561   if (CondVar) {
    562     ConditionVar = cast<VarDecl>(CondVar);
    563     CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
    564     if (CondResult.isInvalid())
    565       return StmtError();
    566 
    567     Cond = CondResult.release();
    568   }
    569 
    570   if (!Cond)
    571     return StmtError();
    572 
    573   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
    574     Expr *Cond;
    575 
    576   public:
    577     SwitchConvertDiagnoser(Expr *Cond)
    578       : ICEConvertDiagnoser(false, true), Cond(Cond) { }
    579 
    580     virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
    581                                              QualType T) {
    582       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
    583     }
    584 
    585     virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
    586                                                  QualType T) {
    587       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
    588                << T << Cond->getSourceRange();
    589     }
    590 
    591     virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
    592                                                    QualType T,
    593                                                    QualType ConvTy) {
    594       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
    595     }
    596 
    597     virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
    598                                                QualType ConvTy) {
    599       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
    600         << ConvTy->isEnumeralType() << ConvTy;
    601     }
    602 
    603     virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
    604                                                 QualType T) {
    605       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
    606     }
    607 
    608     virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
    609                                             QualType ConvTy) {
    610       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
    611       << ConvTy->isEnumeralType() << ConvTy;
    612     }
    613 
    614     virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
    615                                                  QualType T,
    616                                                  QualType ConvTy) {
    617       return DiagnosticBuilder::getEmpty();
    618     }
    619   } SwitchDiagnoser(Cond);
    620 
    621   CondResult
    622     = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
    623                                          /*AllowScopedEnumerations*/ true);
    624   if (CondResult.isInvalid()) return StmtError();
    625   Cond = CondResult.take();
    626 
    627   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
    628   CondResult = UsualUnaryConversions(Cond);
    629   if (CondResult.isInvalid()) return StmtError();
    630   Cond = CondResult.take();
    631 
    632   if (!CondVar) {
    633     CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
    634     if (CondResult.isInvalid())
    635       return StmtError();
    636     Cond = CondResult.take();
    637   }
    638 
    639   getCurFunction()->setHasBranchIntoScope();
    640 
    641   SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
    642   getCurFunction()->SwitchStack.push_back(SS);
    643   return Owned(SS);
    644 }
    645 
    646 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
    647   if (Val.getBitWidth() < BitWidth)
    648     Val = Val.extend(BitWidth);
    649   else if (Val.getBitWidth() > BitWidth)
    650     Val = Val.trunc(BitWidth);
    651   Val.setIsSigned(IsSigned);
    652 }
    653 
    654 StmtResult
    655 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
    656                             Stmt *BodyStmt) {
    657   SwitchStmt *SS = cast<SwitchStmt>(Switch);
    658   assert(SS == getCurFunction()->SwitchStack.back() &&
    659          "switch stack missing push/pop!");
    660 
    661   SS->setBody(BodyStmt, SwitchLoc);
    662   getCurFunction()->SwitchStack.pop_back();
    663 
    664   Expr *CondExpr = SS->getCond();
    665   if (!CondExpr) return StmtError();
    666 
    667   QualType CondType = CondExpr->getType();
    668 
    669   Expr *CondExprBeforePromotion = CondExpr;
    670   QualType CondTypeBeforePromotion =
    671       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
    672 
    673   // C++ 6.4.2.p2:
    674   // Integral promotions are performed (on the switch condition).
    675   //
    676   // A case value unrepresentable by the original switch condition
    677   // type (before the promotion) doesn't make sense, even when it can
    678   // be represented by the promoted type.  Therefore we need to find
    679   // the pre-promotion type of the switch condition.
    680   if (!CondExpr->isTypeDependent()) {
    681     // We have already converted the expression to an integral or enumeration
    682     // type, when we started the switch statement. If we don't have an
    683     // appropriate type now, just return an error.
    684     if (!CondType->isIntegralOrEnumerationType())
    685       return StmtError();
    686 
    687     if (CondExpr->isKnownToHaveBooleanValue()) {
    688       // switch(bool_expr) {...} is often a programmer error, e.g.
    689       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
    690       // One can always use an if statement instead of switch(bool_expr).
    691       Diag(SwitchLoc, diag::warn_bool_switch_condition)
    692           << CondExpr->getSourceRange();
    693     }
    694   }
    695 
    696   // Get the bitwidth of the switched-on value before promotions.  We must
    697   // convert the integer case values to this width before comparison.
    698   bool HasDependentValue
    699     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
    700   unsigned CondWidth
    701     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
    702   bool CondIsSigned
    703     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
    704 
    705   // Accumulate all of the case values in a vector so that we can sort them
    706   // and detect duplicates.  This vector contains the APInt for the case after
    707   // it has been converted to the condition type.
    708   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
    709   CaseValsTy CaseVals;
    710 
    711   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
    712   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
    713   CaseRangesTy CaseRanges;
    714 
    715   DefaultStmt *TheDefaultStmt = 0;
    716 
    717   bool CaseListIsErroneous = false;
    718 
    719   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
    720        SC = SC->getNextSwitchCase()) {
    721 
    722     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
    723       if (TheDefaultStmt) {
    724         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
    725         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
    726 
    727         // FIXME: Remove the default statement from the switch block so that
    728         // we'll return a valid AST.  This requires recursing down the AST and
    729         // finding it, not something we are set up to do right now.  For now,
    730         // just lop the entire switch stmt out of the AST.
    731         CaseListIsErroneous = true;
    732       }
    733       TheDefaultStmt = DS;
    734 
    735     } else {
    736       CaseStmt *CS = cast<CaseStmt>(SC);
    737 
    738       Expr *Lo = CS->getLHS();
    739 
    740       if (Lo->isTypeDependent() || Lo->isValueDependent()) {
    741         HasDependentValue = true;
    742         break;
    743       }
    744 
    745       llvm::APSInt LoVal;
    746 
    747       if (getLangOpts().CPlusPlus11) {
    748         // C++11 [stmt.switch]p2: the constant-expression shall be a converted
    749         // constant expression of the promoted type of the switch condition.
    750         ExprResult ConvLo =
    751           CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
    752         if (ConvLo.isInvalid()) {
    753           CaseListIsErroneous = true;
    754           continue;
    755         }
    756         Lo = ConvLo.take();
    757       } else {
    758         // We already verified that the expression has a i-c-e value (C99
    759         // 6.8.4.2p3) - get that value now.
    760         LoVal = Lo->EvaluateKnownConstInt(Context);
    761 
    762         // If the LHS is not the same type as the condition, insert an implicit
    763         // cast.
    764         Lo = DefaultLvalueConversion(Lo).take();
    765         Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
    766       }
    767 
    768       // Convert the value to the same width/sign as the condition had prior to
    769       // integral promotions.
    770       //
    771       // FIXME: This causes us to reject valid code:
    772       //   switch ((char)c) { case 256: case 0: return 0; }
    773       // Here we claim there is a duplicated condition value, but there is not.
    774       ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
    775                                          Lo->getLocStart(),
    776                                          diag::warn_case_value_overflow);
    777 
    778       CS->setLHS(Lo);
    779 
    780       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
    781       if (CS->getRHS()) {
    782         if (CS->getRHS()->isTypeDependent() ||
    783             CS->getRHS()->isValueDependent()) {
    784           HasDependentValue = true;
    785           break;
    786         }
    787         CaseRanges.push_back(std::make_pair(LoVal, CS));
    788       } else
    789         CaseVals.push_back(std::make_pair(LoVal, CS));
    790     }
    791   }
    792 
    793   if (!HasDependentValue) {
    794     // If we don't have a default statement, check whether the
    795     // condition is constant.
    796     llvm::APSInt ConstantCondValue;
    797     bool HasConstantCond = false;
    798     if (!HasDependentValue && !TheDefaultStmt) {
    799       HasConstantCond
    800         = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
    801                                                  Expr::SE_AllowSideEffects);
    802       assert(!HasConstantCond ||
    803              (ConstantCondValue.getBitWidth() == CondWidth &&
    804               ConstantCondValue.isSigned() == CondIsSigned));
    805     }
    806     bool ShouldCheckConstantCond = HasConstantCond;
    807 
    808     // Sort all the scalar case values so we can easily detect duplicates.
    809     std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
    810 
    811     if (!CaseVals.empty()) {
    812       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
    813         if (ShouldCheckConstantCond &&
    814             CaseVals[i].first == ConstantCondValue)
    815           ShouldCheckConstantCond = false;
    816 
    817         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
    818           // If we have a duplicate, report it.
    819           // First, determine if either case value has a name
    820           StringRef PrevString, CurrString;
    821           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
    822           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
    823           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
    824             PrevString = DeclRef->getDecl()->getName();
    825           }
    826           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
    827             CurrString = DeclRef->getDecl()->getName();
    828           }
    829           SmallString<16> CaseValStr;
    830           CaseVals[i-1].first.toString(CaseValStr);
    831 
    832           if (PrevString == CurrString)
    833             Diag(CaseVals[i].second->getLHS()->getLocStart(),
    834                  diag::err_duplicate_case) <<
    835                  (PrevString.empty() ? CaseValStr.str() : PrevString);
    836           else
    837             Diag(CaseVals[i].second->getLHS()->getLocStart(),
    838                  diag::err_duplicate_case_differing_expr) <<
    839                  (PrevString.empty() ? CaseValStr.str() : PrevString) <<
    840                  (CurrString.empty() ? CaseValStr.str() : CurrString) <<
    841                  CaseValStr;
    842 
    843           Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
    844                diag::note_duplicate_case_prev);
    845           // FIXME: We really want to remove the bogus case stmt from the
    846           // substmt, but we have no way to do this right now.
    847           CaseListIsErroneous = true;
    848         }
    849       }
    850     }
    851 
    852     // Detect duplicate case ranges, which usually don't exist at all in
    853     // the first place.
    854     if (!CaseRanges.empty()) {
    855       // Sort all the case ranges by their low value so we can easily detect
    856       // overlaps between ranges.
    857       std::stable_sort(CaseRanges.begin(), CaseRanges.end());
    858 
    859       // Scan the ranges, computing the high values and removing empty ranges.
    860       std::vector<llvm::APSInt> HiVals;
    861       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
    862         llvm::APSInt &LoVal = CaseRanges[i].first;
    863         CaseStmt *CR = CaseRanges[i].second;
    864         Expr *Hi = CR->getRHS();
    865         llvm::APSInt HiVal;
    866 
    867         if (getLangOpts().CPlusPlus11) {
    868           // C++11 [stmt.switch]p2: the constant-expression shall be a converted
    869           // constant expression of the promoted type of the switch condition.
    870           ExprResult ConvHi =
    871             CheckConvertedConstantExpression(Hi, CondType, HiVal,
    872                                              CCEK_CaseValue);
    873           if (ConvHi.isInvalid()) {
    874             CaseListIsErroneous = true;
    875             continue;
    876           }
    877           Hi = ConvHi.take();
    878         } else {
    879           HiVal = Hi->EvaluateKnownConstInt(Context);
    880 
    881           // If the RHS is not the same type as the condition, insert an
    882           // implicit cast.
    883           Hi = DefaultLvalueConversion(Hi).take();
    884           Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
    885         }
    886 
    887         // Convert the value to the same width/sign as the condition.
    888         ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
    889                                            Hi->getLocStart(),
    890                                            diag::warn_case_value_overflow);
    891 
    892         CR->setRHS(Hi);
    893 
    894         // If the low value is bigger than the high value, the case is empty.
    895         if (LoVal > HiVal) {
    896           Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
    897             << SourceRange(CR->getLHS()->getLocStart(),
    898                            Hi->getLocEnd());
    899           CaseRanges.erase(CaseRanges.begin()+i);
    900           --i, --e;
    901           continue;
    902         }
    903 
    904         if (ShouldCheckConstantCond &&
    905             LoVal <= ConstantCondValue &&
    906             ConstantCondValue <= HiVal)
    907           ShouldCheckConstantCond = false;
    908 
    909         HiVals.push_back(HiVal);
    910       }
    911 
    912       // Rescan the ranges, looking for overlap with singleton values and other
    913       // ranges.  Since the range list is sorted, we only need to compare case
    914       // ranges with their neighbors.
    915       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
    916         llvm::APSInt &CRLo = CaseRanges[i].first;
    917         llvm::APSInt &CRHi = HiVals[i];
    918         CaseStmt *CR = CaseRanges[i].second;
    919 
    920         // Check to see whether the case range overlaps with any
    921         // singleton cases.
    922         CaseStmt *OverlapStmt = 0;
    923         llvm::APSInt OverlapVal(32);
    924 
    925         // Find the smallest value >= the lower bound.  If I is in the
    926         // case range, then we have overlap.
    927         CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
    928                                                   CaseVals.end(), CRLo,
    929                                                   CaseCompareFunctor());
    930         if (I != CaseVals.end() && I->first < CRHi) {
    931           OverlapVal  = I->first;   // Found overlap with scalar.
    932           OverlapStmt = I->second;
    933         }
    934 
    935         // Find the smallest value bigger than the upper bound.
    936         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
    937         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
    938           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
    939           OverlapStmt = (I-1)->second;
    940         }
    941 
    942         // Check to see if this case stmt overlaps with the subsequent
    943         // case range.
    944         if (i && CRLo <= HiVals[i-1]) {
    945           OverlapVal  = HiVals[i-1];       // Found overlap with range.
    946           OverlapStmt = CaseRanges[i-1].second;
    947         }
    948 
    949         if (OverlapStmt) {
    950           // If we have a duplicate, report it.
    951           Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
    952             << OverlapVal.toString(10);
    953           Diag(OverlapStmt->getLHS()->getLocStart(),
    954                diag::note_duplicate_case_prev);
    955           // FIXME: We really want to remove the bogus case stmt from the
    956           // substmt, but we have no way to do this right now.
    957           CaseListIsErroneous = true;
    958         }
    959       }
    960     }
    961 
    962     // Complain if we have a constant condition and we didn't find a match.
    963     if (!CaseListIsErroneous && ShouldCheckConstantCond) {
    964       // TODO: it would be nice if we printed enums as enums, chars as
    965       // chars, etc.
    966       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
    967         << ConstantCondValue.toString(10)
    968         << CondExpr->getSourceRange();
    969     }
    970 
    971     // Check to see if switch is over an Enum and handles all of its
    972     // values.  We only issue a warning if there is not 'default:', but
    973     // we still do the analysis to preserve this information in the AST
    974     // (which can be used by flow-based analyes).
    975     //
    976     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
    977 
    978     // If switch has default case, then ignore it.
    979     if (!CaseListIsErroneous  && !HasConstantCond && ET) {
    980       const EnumDecl *ED = ET->getDecl();
    981       typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
    982         EnumValsTy;
    983       EnumValsTy EnumVals;
    984 
    985       // Gather all enum values, set their type and sort them,
    986       // allowing easier comparison with CaseVals.
    987       for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
    988            EDI != ED->enumerator_end(); ++EDI) {
    989         llvm::APSInt Val = EDI->getInitVal();
    990         AdjustAPSInt(Val, CondWidth, CondIsSigned);
    991         EnumVals.push_back(std::make_pair(Val, *EDI));
    992       }
    993       std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
    994       EnumValsTy::iterator EIend =
    995         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
    996 
    997       // See which case values aren't in enum.
    998       EnumValsTy::const_iterator EI = EnumVals.begin();
    999       for (CaseValsTy::const_iterator CI = CaseVals.begin();
   1000            CI != CaseVals.end(); CI++) {
   1001         while (EI != EIend && EI->first < CI->first)
   1002           EI++;
   1003         if (EI == EIend || EI->first > CI->first)
   1004           Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
   1005             << CondTypeBeforePromotion;
   1006       }
   1007       // See which of case ranges aren't in enum
   1008       EI = EnumVals.begin();
   1009       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
   1010            RI != CaseRanges.end() && EI != EIend; RI++) {
   1011         while (EI != EIend && EI->first < RI->first)
   1012           EI++;
   1013 
   1014         if (EI == EIend || EI->first != RI->first) {
   1015           Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
   1016             << CondTypeBeforePromotion;
   1017         }
   1018 
   1019         llvm::APSInt Hi =
   1020           RI->second->getRHS()->EvaluateKnownConstInt(Context);
   1021         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
   1022         while (EI != EIend && EI->first < Hi)
   1023           EI++;
   1024         if (EI == EIend || EI->first != Hi)
   1025           Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
   1026             << CondTypeBeforePromotion;
   1027       }
   1028 
   1029       // Check which enum vals aren't in switch
   1030       CaseValsTy::const_iterator CI = CaseVals.begin();
   1031       CaseRangesTy::const_iterator RI = CaseRanges.begin();
   1032       bool hasCasesNotInSwitch = false;
   1033 
   1034       SmallVector<DeclarationName,8> UnhandledNames;
   1035 
   1036       for (EI = EnumVals.begin(); EI != EIend; EI++){
   1037         // Drop unneeded case values
   1038         llvm::APSInt CIVal;
   1039         while (CI != CaseVals.end() && CI->first < EI->first)
   1040           CI++;
   1041 
   1042         if (CI != CaseVals.end() && CI->first == EI->first)
   1043           continue;
   1044 
   1045         // Drop unneeded case ranges
   1046         for (; RI != CaseRanges.end(); RI++) {
   1047           llvm::APSInt Hi =
   1048             RI->second->getRHS()->EvaluateKnownConstInt(Context);
   1049           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
   1050           if (EI->first <= Hi)
   1051             break;
   1052         }
   1053 
   1054         if (RI == CaseRanges.end() || EI->first < RI->first) {
   1055           hasCasesNotInSwitch = true;
   1056           UnhandledNames.push_back(EI->second->getDeclName());
   1057         }
   1058       }
   1059 
   1060       if (TheDefaultStmt && UnhandledNames.empty())
   1061         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
   1062 
   1063       // Produce a nice diagnostic if multiple values aren't handled.
   1064       switch (UnhandledNames.size()) {
   1065       case 0: break;
   1066       case 1:
   1067         Diag(CondExpr->getExprLoc(), TheDefaultStmt
   1068           ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
   1069           << UnhandledNames[0];
   1070         break;
   1071       case 2:
   1072         Diag(CondExpr->getExprLoc(), TheDefaultStmt
   1073           ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
   1074           << UnhandledNames[0] << UnhandledNames[1];
   1075         break;
   1076       case 3:
   1077         Diag(CondExpr->getExprLoc(), TheDefaultStmt
   1078           ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
   1079           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
   1080         break;
   1081       default:
   1082         Diag(CondExpr->getExprLoc(), TheDefaultStmt
   1083           ? diag::warn_def_missing_cases : diag::warn_missing_cases)
   1084           << (unsigned)UnhandledNames.size()
   1085           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
   1086         break;
   1087       }
   1088 
   1089       if (!hasCasesNotInSwitch)
   1090         SS->setAllEnumCasesCovered();
   1091     }
   1092   }
   1093 
   1094   DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
   1095                         diag::warn_empty_switch_body);
   1096 
   1097   // FIXME: If the case list was broken is some way, we don't have a good system
   1098   // to patch it up.  Instead, just return the whole substmt as broken.
   1099   if (CaseListIsErroneous)
   1100     return StmtError();
   1101 
   1102   return Owned(SS);
   1103 }
   1104 
   1105 void
   1106 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
   1107                              Expr *SrcExpr) {
   1108   unsigned DIAG = diag::warn_not_in_enum_assignement;
   1109   if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
   1110       == DiagnosticsEngine::Ignored)
   1111     return;
   1112 
   1113   if (const EnumType *ET = DstType->getAs<EnumType>())
   1114     if (!Context.hasSameType(SrcType, DstType) &&
   1115         SrcType->isIntegerType()) {
   1116       if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
   1117           SrcExpr->isIntegerConstantExpr(Context)) {
   1118         // Get the bitwidth of the enum value before promotions.
   1119         unsigned DstWith = Context.getIntWidth(DstType);
   1120         bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
   1121 
   1122         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
   1123         const EnumDecl *ED = ET->getDecl();
   1124         typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
   1125         EnumValsTy;
   1126         EnumValsTy EnumVals;
   1127 
   1128         // Gather all enum values, set their type and sort them,
   1129         // allowing easier comparison with rhs constant.
   1130         for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
   1131              EDI != ED->enumerator_end(); ++EDI) {
   1132           llvm::APSInt Val = EDI->getInitVal();
   1133           AdjustAPSInt(Val, DstWith, DstIsSigned);
   1134           EnumVals.push_back(std::make_pair(Val, *EDI));
   1135         }
   1136         if (EnumVals.empty())
   1137           return;
   1138         std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
   1139         EnumValsTy::iterator EIend =
   1140         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
   1141 
   1142         // See which case values aren't in enum.
   1143         EnumValsTy::const_iterator EI = EnumVals.begin();
   1144         while (EI != EIend && EI->first < RhsVal)
   1145           EI++;
   1146         if (EI == EIend || EI->first != RhsVal) {
   1147           Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
   1148           << DstType;
   1149         }
   1150       }
   1151     }
   1152 }
   1153 
   1154 StmtResult
   1155 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
   1156                      Decl *CondVar, Stmt *Body) {
   1157   ExprResult CondResult(Cond.release());
   1158 
   1159   VarDecl *ConditionVar = 0;
   1160   if (CondVar) {
   1161     ConditionVar = cast<VarDecl>(CondVar);
   1162     CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
   1163     if (CondResult.isInvalid())
   1164       return StmtError();
   1165   }
   1166   Expr *ConditionExpr = CondResult.take();
   1167   if (!ConditionExpr)
   1168     return StmtError();
   1169 
   1170   DiagnoseUnusedExprResult(Body);
   1171 
   1172   if (isa<NullStmt>(Body))
   1173     getCurCompoundScope().setHasEmptyLoopBodies();
   1174 
   1175   return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
   1176                                        Body, WhileLoc));
   1177 }
   1178 
   1179 StmtResult
   1180 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
   1181                   SourceLocation WhileLoc, SourceLocation CondLParen,
   1182                   Expr *Cond, SourceLocation CondRParen) {
   1183   assert(Cond && "ActOnDoStmt(): missing expression");
   1184 
   1185   ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
   1186   if (CondResult.isInvalid())
   1187     return StmtError();
   1188   Cond = CondResult.take();
   1189 
   1190   CondResult = ActOnFinishFullExpr(Cond, DoLoc);
   1191   if (CondResult.isInvalid())
   1192     return StmtError();
   1193   Cond = CondResult.take();
   1194 
   1195   DiagnoseUnusedExprResult(Body);
   1196 
   1197   return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
   1198 }
   1199 
   1200 namespace {
   1201   // This visitor will traverse a conditional statement and store all
   1202   // the evaluated decls into a vector.  Simple is set to true if none
   1203   // of the excluded constructs are used.
   1204   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
   1205     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
   1206     SmallVector<SourceRange, 10> &Ranges;
   1207     bool Simple;
   1208 public:
   1209   typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
   1210 
   1211   DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
   1212                 SmallVector<SourceRange, 10> &Ranges) :
   1213       Inherited(S.Context),
   1214       Decls(Decls),
   1215       Ranges(Ranges),
   1216       Simple(true) {}
   1217 
   1218   bool isSimple() { return Simple; }
   1219 
   1220   // Replaces the method in EvaluatedExprVisitor.
   1221   void VisitMemberExpr(MemberExpr* E) {
   1222     Simple = false;
   1223   }
   1224 
   1225   // Any Stmt not whitelisted will cause the condition to be marked complex.
   1226   void VisitStmt(Stmt *S) {
   1227     Simple = false;
   1228   }
   1229 
   1230   void VisitBinaryOperator(BinaryOperator *E) {
   1231     Visit(E->getLHS());
   1232     Visit(E->getRHS());
   1233   }
   1234 
   1235   void VisitCastExpr(CastExpr *E) {
   1236     Visit(E->getSubExpr());
   1237   }
   1238 
   1239   void VisitUnaryOperator(UnaryOperator *E) {
   1240     // Skip checking conditionals with derefernces.
   1241     if (E->getOpcode() == UO_Deref)
   1242       Simple = false;
   1243     else
   1244       Visit(E->getSubExpr());
   1245   }
   1246 
   1247   void VisitConditionalOperator(ConditionalOperator *E) {
   1248     Visit(E->getCond());
   1249     Visit(E->getTrueExpr());
   1250     Visit(E->getFalseExpr());
   1251   }
   1252 
   1253   void VisitParenExpr(ParenExpr *E) {
   1254     Visit(E->getSubExpr());
   1255   }
   1256 
   1257   void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
   1258     Visit(E->getOpaqueValue()->getSourceExpr());
   1259     Visit(E->getFalseExpr());
   1260   }
   1261 
   1262   void VisitIntegerLiteral(IntegerLiteral *E) { }
   1263   void VisitFloatingLiteral(FloatingLiteral *E) { }
   1264   void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
   1265   void VisitCharacterLiteral(CharacterLiteral *E) { }
   1266   void VisitGNUNullExpr(GNUNullExpr *E) { }
   1267   void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
   1268 
   1269   void VisitDeclRefExpr(DeclRefExpr *E) {
   1270     VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
   1271     if (!VD) return;
   1272 
   1273     Ranges.push_back(E->getSourceRange());
   1274 
   1275     Decls.insert(VD);
   1276   }
   1277 
   1278   }; // end class DeclExtractor
   1279 
   1280   // DeclMatcher checks to see if the decls are used in a non-evauluated
   1281   // context.
   1282   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
   1283     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
   1284     bool FoundDecl;
   1285 
   1286 public:
   1287   typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
   1288 
   1289   DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
   1290       Inherited(S.Context), Decls(Decls), FoundDecl(false) {
   1291     if (!Statement) return;
   1292 
   1293     Visit(Statement);
   1294   }
   1295 
   1296   void VisitReturnStmt(ReturnStmt *S) {
   1297     FoundDecl = true;
   1298   }
   1299 
   1300   void VisitBreakStmt(BreakStmt *S) {
   1301     FoundDecl = true;
   1302   }
   1303 
   1304   void VisitGotoStmt(GotoStmt *S) {
   1305     FoundDecl = true;
   1306   }
   1307 
   1308   void VisitCastExpr(CastExpr *E) {
   1309     if (E->getCastKind() == CK_LValueToRValue)
   1310       CheckLValueToRValueCast(E->getSubExpr());
   1311     else
   1312       Visit(E->getSubExpr());
   1313   }
   1314 
   1315   void CheckLValueToRValueCast(Expr *E) {
   1316     E = E->IgnoreParenImpCasts();
   1317 
   1318     if (isa<DeclRefExpr>(E)) {
   1319       return;
   1320     }
   1321 
   1322     if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
   1323       Visit(CO->getCond());
   1324       CheckLValueToRValueCast(CO->getTrueExpr());
   1325       CheckLValueToRValueCast(CO->getFalseExpr());
   1326       return;
   1327     }
   1328 
   1329     if (BinaryConditionalOperator *BCO =
   1330             dyn_cast<BinaryConditionalOperator>(E)) {
   1331       CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
   1332       CheckLValueToRValueCast(BCO->getFalseExpr());
   1333       return;
   1334     }
   1335 
   1336     Visit(E);
   1337   }
   1338 
   1339   void VisitDeclRefExpr(DeclRefExpr *E) {
   1340     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
   1341       if (Decls.count(VD))
   1342         FoundDecl = true;
   1343   }
   1344 
   1345   bool FoundDeclInUse() { return FoundDecl; }
   1346 
   1347   };  // end class DeclMatcher
   1348 
   1349   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
   1350                                         Expr *Third, Stmt *Body) {
   1351     // Condition is empty
   1352     if (!Second) return;
   1353 
   1354     if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
   1355                                    Second->getLocStart())
   1356         == DiagnosticsEngine::Ignored)
   1357       return;
   1358 
   1359     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
   1360     llvm::SmallPtrSet<VarDecl*, 8> Decls;
   1361     SmallVector<SourceRange, 10> Ranges;
   1362     DeclExtractor DE(S, Decls, Ranges);
   1363     DE.Visit(Second);
   1364 
   1365     // Don't analyze complex conditionals.
   1366     if (!DE.isSimple()) return;
   1367 
   1368     // No decls found.
   1369     if (Decls.size() == 0) return;
   1370 
   1371     // Don't warn on volatile, static, or global variables.
   1372     for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
   1373                                                   E = Decls.end();
   1374          I != E; ++I)
   1375       if ((*I)->getType().isVolatileQualified() ||
   1376           (*I)->hasGlobalStorage()) return;
   1377 
   1378     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
   1379         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
   1380         DeclMatcher(S, Decls, Body).FoundDeclInUse())
   1381       return;
   1382 
   1383     // Load decl names into diagnostic.
   1384     if (Decls.size() > 4)
   1385       PDiag << 0;
   1386     else {
   1387       PDiag << Decls.size();
   1388       for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
   1389                                                     E = Decls.end();
   1390            I != E; ++I)
   1391         PDiag << (*I)->getDeclName();
   1392     }
   1393 
   1394     // Load SourceRanges into diagnostic if there is room.
   1395     // Otherwise, load the SourceRange of the conditional expression.
   1396     if (Ranges.size() <= PartialDiagnostic::MaxArguments)
   1397       for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
   1398                                                   E = Ranges.end();
   1399            I != E; ++I)
   1400         PDiag << *I;
   1401     else
   1402       PDiag << Second->getSourceRange();
   1403 
   1404     S.Diag(Ranges.begin()->getBegin(), PDiag);
   1405   }
   1406 
   1407 } // end namespace
   1408 
   1409 StmtResult
   1410 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
   1411                    Stmt *First, FullExprArg second, Decl *secondVar,
   1412                    FullExprArg third,
   1413                    SourceLocation RParenLoc, Stmt *Body) {
   1414   if (!getLangOpts().CPlusPlus) {
   1415     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
   1416       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
   1417       // declare identifiers for objects having storage class 'auto' or
   1418       // 'register'.
   1419       for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
   1420            DI!=DE; ++DI) {
   1421         VarDecl *VD = dyn_cast<VarDecl>(*DI);
   1422         if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
   1423           VD = 0;
   1424         if (VD == 0)
   1425           Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
   1426         // FIXME: mark decl erroneous!
   1427       }
   1428     }
   1429   }
   1430 
   1431   CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
   1432 
   1433   ExprResult SecondResult(second.release());
   1434   VarDecl *ConditionVar = 0;
   1435   if (secondVar) {
   1436     ConditionVar = cast<VarDecl>(secondVar);
   1437     SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
   1438     if (SecondResult.isInvalid())
   1439       return StmtError();
   1440   }
   1441 
   1442   Expr *Third  = third.release().takeAs<Expr>();
   1443 
   1444   DiagnoseUnusedExprResult(First);
   1445   DiagnoseUnusedExprResult(Third);
   1446   DiagnoseUnusedExprResult(Body);
   1447 
   1448   if (isa<NullStmt>(Body))
   1449     getCurCompoundScope().setHasEmptyLoopBodies();
   1450 
   1451   return Owned(new (Context) ForStmt(Context, First,
   1452                                      SecondResult.take(), ConditionVar,
   1453                                      Third, Body, ForLoc, LParenLoc,
   1454                                      RParenLoc));
   1455 }
   1456 
   1457 /// In an Objective C collection iteration statement:
   1458 ///   for (x in y)
   1459 /// x can be an arbitrary l-value expression.  Bind it up as a
   1460 /// full-expression.
   1461 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
   1462   // Reduce placeholder expressions here.  Note that this rejects the
   1463   // use of pseudo-object l-values in this position.
   1464   ExprResult result = CheckPlaceholderExpr(E);
   1465   if (result.isInvalid()) return StmtError();
   1466   E = result.take();
   1467 
   1468   ExprResult FullExpr = ActOnFinishFullExpr(E);
   1469   if (FullExpr.isInvalid())
   1470     return StmtError();
   1471   return StmtResult(static_cast<Stmt*>(FullExpr.take()));
   1472 }
   1473 
   1474 ExprResult
   1475 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
   1476   if (!collection)
   1477     return ExprError();
   1478 
   1479   // Bail out early if we've got a type-dependent expression.
   1480   if (collection->isTypeDependent()) return Owned(collection);
   1481 
   1482   // Perform normal l-value conversion.
   1483   ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
   1484   if (result.isInvalid())
   1485     return ExprError();
   1486   collection = result.take();
   1487 
   1488   // The operand needs to have object-pointer type.
   1489   // TODO: should we do a contextual conversion?
   1490   const ObjCObjectPointerType *pointerType =
   1491     collection->getType()->getAs<ObjCObjectPointerType>();
   1492   if (!pointerType)
   1493     return Diag(forLoc, diag::err_collection_expr_type)
   1494              << collection->getType() << collection->getSourceRange();
   1495 
   1496   // Check that the operand provides
   1497   //   - countByEnumeratingWithState:objects:count:
   1498   const ObjCObjectType *objectType = pointerType->getObjectType();
   1499   ObjCInterfaceDecl *iface = objectType->getInterface();
   1500 
   1501   // If we have a forward-declared type, we can't do this check.
   1502   // Under ARC, it is an error not to have a forward-declared class.
   1503   if (iface &&
   1504       RequireCompleteType(forLoc, QualType(objectType, 0),
   1505                           getLangOpts().ObjCAutoRefCount
   1506                             ? diag::err_arc_collection_forward
   1507                             : 0,
   1508                           collection)) {
   1509     // Otherwise, if we have any useful type information, check that
   1510     // the type declares the appropriate method.
   1511   } else if (iface || !objectType->qual_empty()) {
   1512     IdentifierInfo *selectorIdents[] = {
   1513       &Context.Idents.get("countByEnumeratingWithState"),
   1514       &Context.Idents.get("objects"),
   1515       &Context.Idents.get("count")
   1516     };
   1517     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
   1518 
   1519     ObjCMethodDecl *method = 0;
   1520 
   1521     // If there's an interface, look in both the public and private APIs.
   1522     if (iface) {
   1523       method = iface->lookupInstanceMethod(selector);
   1524       if (!method) method = iface->lookupPrivateMethod(selector);
   1525     }
   1526 
   1527     // Also check protocol qualifiers.
   1528     if (!method)
   1529       method = LookupMethodInQualifiedType(selector, pointerType,
   1530                                            /*instance*/ true);
   1531 
   1532     // If we didn't find it anywhere, give up.
   1533     if (!method) {
   1534       Diag(forLoc, diag::warn_collection_expr_type)
   1535         << collection->getType() << selector << collection->getSourceRange();
   1536     }
   1537 
   1538     // TODO: check for an incompatible signature?
   1539   }
   1540 
   1541   // Wrap up any cleanups in the expression.
   1542   return Owned(collection);
   1543 }
   1544 
   1545 StmtResult
   1546 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
   1547                                  Stmt *First, Expr *collection,
   1548                                  SourceLocation RParenLoc) {
   1549 
   1550   ExprResult CollectionExprResult =
   1551     CheckObjCForCollectionOperand(ForLoc, collection);
   1552 
   1553   if (First) {
   1554     QualType FirstType;
   1555     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
   1556       if (!DS->isSingleDecl())
   1557         return StmtError(Diag((*DS->decl_begin())->getLocation(),
   1558                          diag::err_toomany_element_decls));
   1559 
   1560       VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
   1561       FirstType = D->getType();
   1562       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
   1563       // declare identifiers for objects having storage class 'auto' or
   1564       // 'register'.
   1565       if (!D->hasLocalStorage())
   1566         return StmtError(Diag(D->getLocation(),
   1567                               diag::err_non_variable_decl_in_for));
   1568     } else {
   1569       Expr *FirstE = cast<Expr>(First);
   1570       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
   1571         return StmtError(Diag(First->getLocStart(),
   1572                    diag::err_selector_element_not_lvalue)
   1573           << First->getSourceRange());
   1574 
   1575       FirstType = static_cast<Expr*>(First)->getType();
   1576     }
   1577     if (!FirstType->isDependentType() &&
   1578         !FirstType->isObjCObjectPointerType() &&
   1579         !FirstType->isBlockPointerType())
   1580         return StmtError(Diag(ForLoc, diag::err_selector_element_type)
   1581                            << FirstType << First->getSourceRange());
   1582   }
   1583 
   1584   if (CollectionExprResult.isInvalid())
   1585     return StmtError();
   1586 
   1587   CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
   1588   if (CollectionExprResult.isInvalid())
   1589     return StmtError();
   1590 
   1591   return Owned(new (Context) ObjCForCollectionStmt(First,
   1592                                                    CollectionExprResult.take(), 0,
   1593                                                    ForLoc, RParenLoc));
   1594 }
   1595 
   1596 /// Finish building a variable declaration for a for-range statement.
   1597 /// \return true if an error occurs.
   1598 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
   1599                                   SourceLocation Loc, int diag) {
   1600   // Deduce the type for the iterator variable now rather than leaving it to
   1601   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
   1602   TypeSourceInfo *InitTSI = 0;
   1603   if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
   1604       SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
   1605           Sema::DAR_Failed)
   1606     SemaRef.Diag(Loc, diag) << Init->getType();
   1607   if (!InitTSI) {
   1608     Decl->setInvalidDecl();
   1609     return true;
   1610   }
   1611   Decl->setTypeSourceInfo(InitTSI);
   1612   Decl->setType(InitTSI->getType());
   1613 
   1614   // In ARC, infer lifetime.
   1615   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
   1616   // we're doing the equivalent of fast iteration.
   1617   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
   1618       SemaRef.inferObjCARCLifetime(Decl))
   1619     Decl->setInvalidDecl();
   1620 
   1621   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
   1622                                /*TypeMayContainAuto=*/false);
   1623   SemaRef.FinalizeDeclaration(Decl);
   1624   SemaRef.CurContext->addHiddenDecl(Decl);
   1625   return false;
   1626 }
   1627 
   1628 namespace {
   1629 
   1630 /// Produce a note indicating which begin/end function was implicitly called
   1631 /// by a C++11 for-range statement. This is often not obvious from the code,
   1632 /// nor from the diagnostics produced when analysing the implicit expressions
   1633 /// required in a for-range statement.
   1634 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
   1635                                   Sema::BeginEndFunction BEF) {
   1636   CallExpr *CE = dyn_cast<CallExpr>(E);
   1637   if (!CE)
   1638     return;
   1639   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
   1640   if (!D)
   1641     return;
   1642   SourceLocation Loc = D->getLocation();
   1643 
   1644   std::string Description;
   1645   bool IsTemplate = false;
   1646   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
   1647     Description = SemaRef.getTemplateArgumentBindingsText(
   1648       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
   1649     IsTemplate = true;
   1650   }
   1651 
   1652   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
   1653     << BEF << IsTemplate << Description << E->getType();
   1654 }
   1655 
   1656 /// Build a variable declaration for a for-range statement.
   1657 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
   1658                               QualType Type, const char *Name) {
   1659   DeclContext *DC = SemaRef.CurContext;
   1660   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
   1661   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
   1662   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
   1663                                   TInfo, SC_Auto, SC_None);
   1664   Decl->setImplicit();
   1665   return Decl;
   1666 }
   1667 
   1668 }
   1669 
   1670 static bool ObjCEnumerationCollection(Expr *Collection) {
   1671   return !Collection->isTypeDependent()
   1672           && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
   1673 }
   1674 
   1675 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
   1676 ///
   1677 /// C++11 [stmt.ranged]:
   1678 ///   A range-based for statement is equivalent to
   1679 ///
   1680 ///   {
   1681 ///     auto && __range = range-init;
   1682 ///     for ( auto __begin = begin-expr,
   1683 ///           __end = end-expr;
   1684 ///           __begin != __end;
   1685 ///           ++__begin ) {
   1686 ///       for-range-declaration = *__begin;
   1687 ///       statement
   1688 ///     }
   1689 ///   }
   1690 ///
   1691 /// The body of the loop is not available yet, since it cannot be analysed until
   1692 /// we have determined the type of the for-range-declaration.
   1693 StmtResult
   1694 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
   1695                            Stmt *First, SourceLocation ColonLoc, Expr *Range,
   1696                            SourceLocation RParenLoc, BuildForRangeKind Kind) {
   1697   if (!First || !Range)
   1698     return StmtError();
   1699 
   1700   if (ObjCEnumerationCollection(Range))
   1701     return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
   1702 
   1703   DeclStmt *DS = dyn_cast<DeclStmt>(First);
   1704   assert(DS && "first part of for range not a decl stmt");
   1705 
   1706   if (!DS->isSingleDecl()) {
   1707     Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
   1708     return StmtError();
   1709   }
   1710   if (DS->getSingleDecl()->isInvalidDecl())
   1711     return StmtError();
   1712 
   1713   if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
   1714     return StmtError();
   1715 
   1716   // Build  auto && __range = range-init
   1717   SourceLocation RangeLoc = Range->getLocStart();
   1718   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
   1719                                            Context.getAutoRRefDeductType(),
   1720                                            "__range");
   1721   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
   1722                             diag::err_for_range_deduction_failure))
   1723     return StmtError();
   1724 
   1725   // Claim the type doesn't contain auto: we've already done the checking.
   1726   DeclGroupPtrTy RangeGroup =
   1727     BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
   1728   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
   1729   if (RangeDecl.isInvalid())
   1730     return StmtError();
   1731 
   1732   return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
   1733                               /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
   1734                               RParenLoc, Kind);
   1735 }
   1736 
   1737 /// \brief Create the initialization, compare, and increment steps for
   1738 /// the range-based for loop expression.
   1739 /// This function does not handle array-based for loops,
   1740 /// which are created in Sema::BuildCXXForRangeStmt.
   1741 ///
   1742 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
   1743 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
   1744 /// CandidateSet and BEF are set and some non-success value is returned on
   1745 /// failure.
   1746 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
   1747                                             Expr *BeginRange, Expr *EndRange,
   1748                                             QualType RangeType,
   1749                                             VarDecl *BeginVar,
   1750                                             VarDecl *EndVar,
   1751                                             SourceLocation ColonLoc,
   1752                                             OverloadCandidateSet *CandidateSet,
   1753                                             ExprResult *BeginExpr,
   1754                                             ExprResult *EndExpr,
   1755                                             Sema::BeginEndFunction *BEF) {
   1756   DeclarationNameInfo BeginNameInfo(
   1757       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
   1758   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
   1759                                   ColonLoc);
   1760 
   1761   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
   1762                                  Sema::LookupMemberName);
   1763   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
   1764 
   1765   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
   1766     // - if _RangeT is a class type, the unqualified-ids begin and end are
   1767     //   looked up in the scope of class _RangeT as if by class member access
   1768     //   lookup (3.4.5), and if either (or both) finds at least one
   1769     //   declaration, begin-expr and end-expr are __range.begin() and
   1770     //   __range.end(), respectively;
   1771     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
   1772     SemaRef.LookupQualifiedName(EndMemberLookup, D);
   1773 
   1774     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
   1775       SourceLocation RangeLoc = BeginVar->getLocation();
   1776       *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
   1777 
   1778       SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
   1779           << RangeLoc << BeginRange->getType() << *BEF;
   1780       return Sema::FRS_DiagnosticIssued;
   1781     }
   1782   } else {
   1783     // - otherwise, begin-expr and end-expr are begin(__range) and
   1784     //   end(__range), respectively, where begin and end are looked up with
   1785     //   argument-dependent lookup (3.4.2). For the purposes of this name
   1786     //   lookup, namespace std is an associated namespace.
   1787 
   1788   }
   1789 
   1790   *BEF = Sema::BEF_begin;
   1791   Sema::ForRangeStatus RangeStatus =
   1792       SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
   1793                                         Sema::BEF_begin, BeginNameInfo,
   1794                                         BeginMemberLookup, CandidateSet,
   1795                                         BeginRange, BeginExpr);
   1796 
   1797   if (RangeStatus != Sema::FRS_Success)
   1798     return RangeStatus;
   1799   if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
   1800                             diag::err_for_range_iter_deduction_failure)) {
   1801     NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
   1802     return Sema::FRS_DiagnosticIssued;
   1803   }
   1804 
   1805   *BEF = Sema::BEF_end;
   1806   RangeStatus =
   1807       SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
   1808                                         Sema::BEF_end, EndNameInfo,
   1809                                         EndMemberLookup, CandidateSet,
   1810                                         EndRange, EndExpr);
   1811   if (RangeStatus != Sema::FRS_Success)
   1812     return RangeStatus;
   1813   if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
   1814                             diag::err_for_range_iter_deduction_failure)) {
   1815     NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
   1816     return Sema::FRS_DiagnosticIssued;
   1817   }
   1818   return Sema::FRS_Success;
   1819 }
   1820 
   1821 /// Speculatively attempt to dereference an invalid range expression.
   1822 /// If the attempt fails, this function will return a valid, null StmtResult
   1823 /// and emit no diagnostics.
   1824 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
   1825                                                  SourceLocation ForLoc,
   1826                                                  Stmt *LoopVarDecl,
   1827                                                  SourceLocation ColonLoc,
   1828                                                  Expr *Range,
   1829                                                  SourceLocation RangeLoc,
   1830                                                  SourceLocation RParenLoc) {
   1831   // Determine whether we can rebuild the for-range statement with a
   1832   // dereferenced range expression.
   1833   ExprResult AdjustedRange;
   1834   {
   1835     Sema::SFINAETrap Trap(SemaRef);
   1836 
   1837     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
   1838     if (AdjustedRange.isInvalid())
   1839       return StmtResult();
   1840 
   1841     StmtResult SR =
   1842       SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
   1843                                    AdjustedRange.get(), RParenLoc,
   1844                                    Sema::BFRK_Check);
   1845     if (SR.isInvalid())
   1846       return StmtResult();
   1847   }
   1848 
   1849   // The attempt to dereference worked well enough that it could produce a valid
   1850   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
   1851   // case there are any other (non-fatal) problems with it.
   1852   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
   1853     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
   1854   return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
   1855                                       AdjustedRange.get(), RParenLoc,
   1856                                       Sema::BFRK_Rebuild);
   1857 }
   1858 
   1859 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
   1860 StmtResult
   1861 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
   1862                            Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
   1863                            Expr *Inc, Stmt *LoopVarDecl,
   1864                            SourceLocation RParenLoc, BuildForRangeKind Kind) {
   1865   Scope *S = getCurScope();
   1866 
   1867   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
   1868   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
   1869   QualType RangeVarType = RangeVar->getType();
   1870 
   1871   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
   1872   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
   1873 
   1874   StmtResult BeginEndDecl = BeginEnd;
   1875   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
   1876 
   1877   if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
   1878     SourceLocation RangeLoc = RangeVar->getLocation();
   1879 
   1880     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
   1881 
   1882     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
   1883                                                 VK_LValue, ColonLoc);
   1884     if (BeginRangeRef.isInvalid())
   1885       return StmtError();
   1886 
   1887     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
   1888                                               VK_LValue, ColonLoc);
   1889     if (EndRangeRef.isInvalid())
   1890       return StmtError();
   1891 
   1892     QualType AutoType = Context.getAutoDeductType();
   1893     Expr *Range = RangeVar->getInit();
   1894     if (!Range)
   1895       return StmtError();
   1896     QualType RangeType = Range->getType();
   1897 
   1898     if (RequireCompleteType(RangeLoc, RangeType,
   1899                             diag::err_for_range_incomplete_type))
   1900       return StmtError();
   1901 
   1902     // Build auto __begin = begin-expr, __end = end-expr.
   1903     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
   1904                                              "__begin");
   1905     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
   1906                                            "__end");
   1907 
   1908     // Build begin-expr and end-expr and attach to __begin and __end variables.
   1909     ExprResult BeginExpr, EndExpr;
   1910     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
   1911       // - if _RangeT is an array type, begin-expr and end-expr are __range and
   1912       //   __range + __bound, respectively, where __bound is the array bound. If
   1913       //   _RangeT is an array of unknown size or an array of incomplete type,
   1914       //   the program is ill-formed;
   1915 
   1916       // begin-expr is __range.
   1917       BeginExpr = BeginRangeRef;
   1918       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
   1919                                 diag::err_for_range_iter_deduction_failure)) {
   1920         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   1921         return StmtError();
   1922       }
   1923 
   1924       // Find the array bound.
   1925       ExprResult BoundExpr;
   1926       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
   1927         BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
   1928                                                  Context.getPointerDiffType(),
   1929                                                  RangeLoc));
   1930       else if (const VariableArrayType *VAT =
   1931                dyn_cast<VariableArrayType>(UnqAT))
   1932         BoundExpr = VAT->getSizeExpr();
   1933       else {
   1934         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
   1935         // UnqAT is not incomplete and Range is not type-dependent.
   1936         llvm_unreachable("Unexpected array type in for-range");
   1937       }
   1938 
   1939       // end-expr is __range + __bound.
   1940       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
   1941                            BoundExpr.get());
   1942       if (EndExpr.isInvalid())
   1943         return StmtError();
   1944       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
   1945                                 diag::err_for_range_iter_deduction_failure)) {
   1946         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
   1947         return StmtError();
   1948       }
   1949     } else {
   1950       OverloadCandidateSet CandidateSet(RangeLoc);
   1951       Sema::BeginEndFunction BEFFailure;
   1952       ForRangeStatus RangeStatus =
   1953           BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
   1954                                 EndRangeRef.get(), RangeType,
   1955                                 BeginVar, EndVar, ColonLoc, &CandidateSet,
   1956                                 &BeginExpr, &EndExpr, &BEFFailure);
   1957 
   1958       // If building the range failed, try dereferencing the range expression
   1959       // unless a diagnostic was issued or the end function is problematic.
   1960       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
   1961           BEFFailure == BEF_begin) {
   1962         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
   1963                                                        LoopVarDecl, ColonLoc,
   1964                                                        Range, RangeLoc,
   1965                                                        RParenLoc);
   1966         if (SR.isInvalid() || SR.isUsable())
   1967           return SR;
   1968       }
   1969 
   1970       // Otherwise, emit diagnostics if we haven't already.
   1971       if (RangeStatus == FRS_NoViableFunction) {
   1972         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
   1973         Diag(Range->getLocStart(), diag::err_for_range_invalid)
   1974             << RangeLoc << Range->getType() << BEFFailure;
   1975         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
   1976       }
   1977       // Return an error if no fix was discovered.
   1978       if (RangeStatus != FRS_Success)
   1979         return StmtError();
   1980     }
   1981 
   1982     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
   1983            "invalid range expression in for loop");
   1984 
   1985     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
   1986     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
   1987     if (!Context.hasSameType(BeginType, EndType)) {
   1988       Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
   1989         << BeginType << EndType;
   1990       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   1991       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
   1992     }
   1993 
   1994     Decl *BeginEndDecls[] = { BeginVar, EndVar };
   1995     // Claim the type doesn't contain auto: we've already done the checking.
   1996     DeclGroupPtrTy BeginEndGroup =
   1997       BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
   1998     BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
   1999 
   2000     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
   2001     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
   2002                                            VK_LValue, ColonLoc);
   2003     if (BeginRef.isInvalid())
   2004       return StmtError();
   2005 
   2006     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
   2007                                          VK_LValue, ColonLoc);
   2008     if (EndRef.isInvalid())
   2009       return StmtError();
   2010 
   2011     // Build and check __begin != __end expression.
   2012     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
   2013                            BeginRef.get(), EndRef.get());
   2014     NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
   2015     NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
   2016     if (NotEqExpr.isInvalid()) {
   2017       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
   2018         << RangeLoc << 0 << BeginRangeRef.get()->getType();
   2019       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   2020       if (!Context.hasSameType(BeginType, EndType))
   2021         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
   2022       return StmtError();
   2023     }
   2024 
   2025     // Build and check ++__begin expression.
   2026     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
   2027                                 VK_LValue, ColonLoc);
   2028     if (BeginRef.isInvalid())
   2029       return StmtError();
   2030 
   2031     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
   2032     IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
   2033     if (IncrExpr.isInvalid()) {
   2034       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
   2035         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
   2036       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   2037       return StmtError();
   2038     }
   2039 
   2040     // Build and check *__begin  expression.
   2041     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
   2042                                 VK_LValue, ColonLoc);
   2043     if (BeginRef.isInvalid())
   2044       return StmtError();
   2045 
   2046     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
   2047     if (DerefExpr.isInvalid()) {
   2048       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
   2049         << RangeLoc << 1 << BeginRangeRef.get()->getType();
   2050       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   2051       return StmtError();
   2052     }
   2053 
   2054     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
   2055     // trying to determine whether this would be a valid range.
   2056     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
   2057       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
   2058                            /*TypeMayContainAuto=*/true);
   2059       if (LoopVar->isInvalidDecl())
   2060         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
   2061     }
   2062   } else {
   2063     // The range is implicitly used as a placeholder when it is dependent.
   2064     RangeVar->setUsed();
   2065   }
   2066 
   2067   // Don't bother to actually allocate the result if we're just trying to
   2068   // determine whether it would be valid.
   2069   if (Kind == BFRK_Check)
   2070     return StmtResult();
   2071 
   2072   return Owned(new (Context) CXXForRangeStmt(RangeDS,
   2073                                      cast_or_null<DeclStmt>(BeginEndDecl.get()),
   2074                                              NotEqExpr.take(), IncrExpr.take(),
   2075                                              LoopVarDS, /*Body=*/0, ForLoc,
   2076                                              ColonLoc, RParenLoc));
   2077 }
   2078 
   2079 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
   2080 /// statement.
   2081 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
   2082   if (!S || !B)
   2083     return StmtError();
   2084   ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
   2085 
   2086   ForStmt->setBody(B);
   2087   return S;
   2088 }
   2089 
   2090 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
   2091 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
   2092 /// body cannot be performed until after the type of the range variable is
   2093 /// determined.
   2094 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
   2095   if (!S || !B)
   2096     return StmtError();
   2097 
   2098   if (isa<ObjCForCollectionStmt>(S))
   2099     return FinishObjCForCollectionStmt(S, B);
   2100 
   2101   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
   2102   ForStmt->setBody(B);
   2103 
   2104   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
   2105                         diag::warn_empty_range_based_for_body);
   2106 
   2107   return S;
   2108 }
   2109 
   2110 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
   2111                                SourceLocation LabelLoc,
   2112                                LabelDecl *TheDecl) {
   2113   getCurFunction()->setHasBranchIntoScope();
   2114   TheDecl->setUsed();
   2115   return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
   2116 }
   2117 
   2118 StmtResult
   2119 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
   2120                             Expr *E) {
   2121   // Convert operand to void*
   2122   if (!E->isTypeDependent()) {
   2123     QualType ETy = E->getType();
   2124     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
   2125     ExprResult ExprRes = Owned(E);
   2126     AssignConvertType ConvTy =
   2127       CheckSingleAssignmentConstraints(DestTy, ExprRes);
   2128     if (ExprRes.isInvalid())
   2129       return StmtError();
   2130     E = ExprRes.take();
   2131     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
   2132       return StmtError();
   2133   }
   2134 
   2135   ExprResult ExprRes = ActOnFinishFullExpr(E);
   2136   if (ExprRes.isInvalid())
   2137     return StmtError();
   2138   E = ExprRes.take();
   2139 
   2140   getCurFunction()->setHasIndirectGoto();
   2141 
   2142   return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
   2143 }
   2144 
   2145 StmtResult
   2146 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
   2147   Scope *S = CurScope->getContinueParent();
   2148   if (!S) {
   2149     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
   2150     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
   2151   }
   2152 
   2153   return Owned(new (Context) ContinueStmt(ContinueLoc));
   2154 }
   2155 
   2156 StmtResult
   2157 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
   2158   Scope *S = CurScope->getBreakParent();
   2159   if (!S) {
   2160     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
   2161     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
   2162   }
   2163 
   2164   return Owned(new (Context) BreakStmt(BreakLoc));
   2165 }
   2166 
   2167 /// \brief Determine whether the given expression is a candidate for
   2168 /// copy elision in either a return statement or a throw expression.
   2169 ///
   2170 /// \param ReturnType If we're determining the copy elision candidate for
   2171 /// a return statement, this is the return type of the function. If we're
   2172 /// determining the copy elision candidate for a throw expression, this will
   2173 /// be a NULL type.
   2174 ///
   2175 /// \param E The expression being returned from the function or block, or
   2176 /// being thrown.
   2177 ///
   2178 /// \param AllowFunctionParameter Whether we allow function parameters to
   2179 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
   2180 /// we re-use this logic to determine whether we should try to move as part of
   2181 /// a return or throw (which does allow function parameters).
   2182 ///
   2183 /// \returns The NRVO candidate variable, if the return statement may use the
   2184 /// NRVO, or NULL if there is no such candidate.
   2185 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
   2186                                              Expr *E,
   2187                                              bool AllowFunctionParameter) {
   2188   QualType ExprType = E->getType();
   2189   // - in a return statement in a function with ...
   2190   // ... a class return type ...
   2191   if (!ReturnType.isNull()) {
   2192     if (!ReturnType->isRecordType())
   2193       return 0;
   2194     // ... the same cv-unqualified type as the function return type ...
   2195     if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
   2196       return 0;
   2197   }
   2198 
   2199   // ... the expression is the name of a non-volatile automatic object
   2200   // (other than a function or catch-clause parameter)) ...
   2201   const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
   2202   if (!DR || DR->refersToEnclosingLocal())
   2203     return 0;
   2204   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
   2205   if (!VD)
   2206     return 0;
   2207 
   2208   // ...object (other than a function or catch-clause parameter)...
   2209   if (VD->getKind() != Decl::Var &&
   2210       !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
   2211     return 0;
   2212   if (VD->isExceptionVariable()) return 0;
   2213 
   2214   // ...automatic...
   2215   if (!VD->hasLocalStorage()) return 0;
   2216 
   2217   // ...non-volatile...
   2218   if (VD->getType().isVolatileQualified()) return 0;
   2219   if (VD->getType()->isReferenceType()) return 0;
   2220 
   2221   // __block variables can't be allocated in a way that permits NRVO.
   2222   if (VD->hasAttr<BlocksAttr>()) return 0;
   2223 
   2224   // Variables with higher required alignment than their type's ABI
   2225   // alignment cannot use NRVO.
   2226   if (VD->hasAttr<AlignedAttr>() &&
   2227       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
   2228     return 0;
   2229 
   2230   return VD;
   2231 }
   2232 
   2233 /// \brief Perform the initialization of a potentially-movable value, which
   2234 /// is the result of return value.
   2235 ///
   2236 /// This routine implements C++0x [class.copy]p33, which attempts to treat
   2237 /// returned lvalues as rvalues in certain cases (to prefer move construction),
   2238 /// then falls back to treating them as lvalues if that failed.
   2239 ExprResult
   2240 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
   2241                                       const VarDecl *NRVOCandidate,
   2242                                       QualType ResultType,
   2243                                       Expr *Value,
   2244                                       bool AllowNRVO) {
   2245   // C++0x [class.copy]p33:
   2246   //   When the criteria for elision of a copy operation are met or would
   2247   //   be met save for the fact that the source object is a function
   2248   //   parameter, and the object to be copied is designated by an lvalue,
   2249   //   overload resolution to select the constructor for the copy is first
   2250   //   performed as if the object were designated by an rvalue.
   2251   ExprResult Res = ExprError();
   2252   if (AllowNRVO &&
   2253       (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
   2254     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
   2255                               Value->getType(), CK_NoOp, Value, VK_XValue);
   2256 
   2257     Expr *InitExpr = &AsRvalue;
   2258     InitializationKind Kind
   2259       = InitializationKind::CreateCopy(Value->getLocStart(),
   2260                                        Value->getLocStart());
   2261     InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
   2262 
   2263     //   [...] If overload resolution fails, or if the type of the first
   2264     //   parameter of the selected constructor is not an rvalue reference
   2265     //   to the object's type (possibly cv-qualified), overload resolution
   2266     //   is performed again, considering the object as an lvalue.
   2267     if (Seq) {
   2268       for (InitializationSequence::step_iterator Step = Seq.step_begin(),
   2269            StepEnd = Seq.step_end();
   2270            Step != StepEnd; ++Step) {
   2271         if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
   2272           continue;
   2273 
   2274         CXXConstructorDecl *Constructor
   2275         = cast<CXXConstructorDecl>(Step->Function.Function);
   2276 
   2277         const RValueReferenceType *RRefType
   2278           = Constructor->getParamDecl(0)->getType()
   2279                                                  ->getAs<RValueReferenceType>();
   2280 
   2281         // If we don't meet the criteria, break out now.
   2282         if (!RRefType ||
   2283             !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
   2284                             Context.getTypeDeclType(Constructor->getParent())))
   2285           break;
   2286 
   2287         // Promote "AsRvalue" to the heap, since we now need this
   2288         // expression node to persist.
   2289         Value = ImplicitCastExpr::Create(Context, Value->getType(),
   2290                                          CK_NoOp, Value, 0, VK_XValue);
   2291 
   2292         // Complete type-checking the initialization of the return type
   2293         // using the constructor we found.
   2294         Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
   2295       }
   2296     }
   2297   }
   2298 
   2299   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
   2300   // above, or overload resolution failed. Either way, we need to try
   2301   // (again) now with the return value expression as written.
   2302   if (Res.isInvalid())
   2303     Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
   2304 
   2305   return Res;
   2306 }
   2307 
   2308 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
   2309 /// for capturing scopes.
   2310 ///
   2311 StmtResult
   2312 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
   2313   // If this is the first return we've seen, infer the return type.
   2314   // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
   2315   // rules which allows multiple return statements.
   2316   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
   2317   QualType FnRetType = CurCap->ReturnType;
   2318 
   2319   // For blocks/lambdas with implicit return types, we check each return
   2320   // statement individually, and deduce the common return type when the block
   2321   // or lambda is completed.
   2322   if (CurCap->HasImplicitReturnType) {
   2323     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
   2324       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
   2325       if (Result.isInvalid())
   2326         return StmtError();
   2327       RetValExp = Result.take();
   2328 
   2329       if (!RetValExp->isTypeDependent())
   2330         FnRetType = RetValExp->getType();
   2331       else
   2332         FnRetType = CurCap->ReturnType = Context.DependentTy;
   2333     } else {
   2334       if (RetValExp) {
   2335         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
   2336         // initializer list, because it is not an expression (even
   2337         // though we represent it as one). We still deduce 'void'.
   2338         Diag(ReturnLoc, diag::err_lambda_return_init_list)
   2339           << RetValExp->getSourceRange();
   2340       }
   2341 
   2342       FnRetType = Context.VoidTy;
   2343     }
   2344 
   2345     // Although we'll properly infer the type of the block once it's completed,
   2346     // make sure we provide a return type now for better error recovery.
   2347     if (CurCap->ReturnType.isNull())
   2348       CurCap->ReturnType = FnRetType;
   2349   }
   2350   assert(!FnRetType.isNull());
   2351 
   2352   if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
   2353     if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
   2354       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
   2355       return StmtError();
   2356     }
   2357   } else {
   2358     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
   2359     if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
   2360       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
   2361       return StmtError();
   2362     }
   2363   }
   2364 
   2365   // Otherwise, verify that this result type matches the previous one.  We are
   2366   // pickier with blocks than for normal functions because we don't have GCC
   2367   // compatibility to worry about here.
   2368   const VarDecl *NRVOCandidate = 0;
   2369   if (FnRetType->isDependentType()) {
   2370     // Delay processing for now.  TODO: there are lots of dependent
   2371     // types we can conclusively prove aren't void.
   2372   } else if (FnRetType->isVoidType()) {
   2373     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
   2374         !(getLangOpts().CPlusPlus &&
   2375           (RetValExp->isTypeDependent() ||
   2376            RetValExp->getType()->isVoidType()))) {
   2377       if (!getLangOpts().CPlusPlus &&
   2378           RetValExp->getType()->isVoidType())
   2379         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
   2380       else {
   2381         Diag(ReturnLoc, diag::err_return_block_has_expr);
   2382         RetValExp = 0;
   2383       }
   2384     }
   2385   } else if (!RetValExp) {
   2386     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
   2387   } else if (!RetValExp->isTypeDependent()) {
   2388     // we have a non-void block with an expression, continue checking
   2389 
   2390     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
   2391     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
   2392     // function return.
   2393 
   2394     // In C++ the return statement is handled via a copy initialization.
   2395     // the C version of which boils down to CheckSingleAssignmentConstraints.
   2396     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
   2397     InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
   2398                                                                    FnRetType,
   2399                                                           NRVOCandidate != 0);
   2400     ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
   2401                                                      FnRetType, RetValExp);
   2402     if (Res.isInvalid()) {
   2403       // FIXME: Cleanup temporaries here, anyway?
   2404       return StmtError();
   2405     }
   2406     RetValExp = Res.take();
   2407     CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
   2408   }
   2409 
   2410   if (RetValExp) {
   2411     ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
   2412     if (ER.isInvalid())
   2413       return StmtError();
   2414     RetValExp = ER.take();
   2415   }
   2416   ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
   2417                                                 NRVOCandidate);
   2418 
   2419   // If we need to check for the named return value optimization,
   2420   // or if we need to infer the return type,
   2421   // save the return statement in our scope for later processing.
   2422   if (CurCap->HasImplicitReturnType ||
   2423       (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
   2424        !CurContext->isDependentContext()))
   2425     FunctionScopes.back()->Returns.push_back(Result);
   2426 
   2427   return Owned(Result);
   2428 }
   2429 
   2430 StmtResult
   2431 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
   2432   // Check for unexpanded parameter packs.
   2433   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
   2434     return StmtError();
   2435 
   2436   if (isa<CapturingScopeInfo>(getCurFunction()))
   2437     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
   2438 
   2439   QualType FnRetType;
   2440   QualType RelatedRetType;
   2441   if (const FunctionDecl *FD = getCurFunctionDecl()) {
   2442     FnRetType = FD->getResultType();
   2443     if (FD->isNoReturn())
   2444       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
   2445         << FD->getDeclName();
   2446   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
   2447     FnRetType = MD->getResultType();
   2448     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
   2449       // In the implementation of a method with a related return type, the
   2450       // type used to type-check the validity of return statements within the
   2451       // method body is a pointer to the type of the class being implemented.
   2452       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
   2453       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
   2454     }
   2455   } else // If we don't have a function/method context, bail.
   2456     return StmtError();
   2457 
   2458   ReturnStmt *Result = 0;
   2459   if (FnRetType->isVoidType()) {
   2460     if (RetValExp) {
   2461       if (isa<InitListExpr>(RetValExp)) {
   2462         // We simply never allow init lists as the return value of void
   2463         // functions. This is compatible because this was never allowed before,
   2464         // so there's no legacy code to deal with.
   2465         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
   2466         int FunctionKind = 0;
   2467         if (isa<ObjCMethodDecl>(CurDecl))
   2468           FunctionKind = 1;
   2469         else if (isa<CXXConstructorDecl>(CurDecl))
   2470           FunctionKind = 2;
   2471         else if (isa<CXXDestructorDecl>(CurDecl))
   2472           FunctionKind = 3;
   2473 
   2474         Diag(ReturnLoc, diag::err_return_init_list)
   2475           << CurDecl->getDeclName() << FunctionKind
   2476           << RetValExp->getSourceRange();
   2477 
   2478         // Drop the expression.
   2479         RetValExp = 0;
   2480       } else if (!RetValExp->isTypeDependent()) {
   2481         // C99 6.8.6.4p1 (ext_ since GCC warns)
   2482         unsigned D = diag::ext_return_has_expr;
   2483         if (RetValExp->getType()->isVoidType())
   2484           D = diag::ext_return_has_void_expr;
   2485         else {
   2486           ExprResult Result = Owned(RetValExp);
   2487           Result = IgnoredValueConversions(Result.take());
   2488           if (Result.isInvalid())
   2489             return StmtError();
   2490           RetValExp = Result.take();
   2491           RetValExp = ImpCastExprToType(RetValExp,
   2492                                         Context.VoidTy, CK_ToVoid).take();
   2493         }
   2494 
   2495         // return (some void expression); is legal in C++.
   2496         if (D != diag::ext_return_has_void_expr ||
   2497             !getLangOpts().CPlusPlus) {
   2498           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
   2499 
   2500           int FunctionKind = 0;
   2501           if (isa<ObjCMethodDecl>(CurDecl))
   2502             FunctionKind = 1;
   2503           else if (isa<CXXConstructorDecl>(CurDecl))
   2504             FunctionKind = 2;
   2505           else if (isa<CXXDestructorDecl>(CurDecl))
   2506             FunctionKind = 3;
   2507 
   2508           Diag(ReturnLoc, D)
   2509             << CurDecl->getDeclName() << FunctionKind
   2510             << RetValExp->getSourceRange();
   2511         }
   2512       }
   2513 
   2514       if (RetValExp) {
   2515         ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
   2516         if (ER.isInvalid())
   2517           return StmtError();
   2518         RetValExp = ER.take();
   2519       }
   2520     }
   2521 
   2522     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
   2523   } else if (!RetValExp && !FnRetType->isDependentType()) {
   2524     unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
   2525     // C99 6.8.6.4p1 (ext_ since GCC warns)
   2526     if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
   2527 
   2528     if (FunctionDecl *FD = getCurFunctionDecl())
   2529       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
   2530     else
   2531       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
   2532     Result = new (Context) ReturnStmt(ReturnLoc);
   2533   } else {
   2534     assert(RetValExp || FnRetType->isDependentType());
   2535     const VarDecl *NRVOCandidate = 0;
   2536     if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
   2537       // we have a non-void function with an expression, continue checking
   2538 
   2539       if (!RelatedRetType.isNull()) {
   2540         // If we have a related result type, perform an extra conversion here.
   2541         // FIXME: The diagnostics here don't really describe what is happening.
   2542         InitializedEntity Entity =
   2543             InitializedEntity::InitializeTemporary(RelatedRetType);
   2544 
   2545         ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
   2546                                                    RetValExp);
   2547         if (Res.isInvalid()) {
   2548           // FIXME: Cleanup temporaries here, anyway?
   2549           return StmtError();
   2550         }
   2551         RetValExp = Res.takeAs<Expr>();
   2552       }
   2553 
   2554       // C99 6.8.6.4p3(136): The return statement is not an assignment. The
   2555       // overlap restriction of subclause 6.5.16.1 does not apply to the case of
   2556       // function return.
   2557 
   2558       // In C++ the return statement is handled via a copy initialization,
   2559       // the C version of which boils down to CheckSingleAssignmentConstraints.
   2560       NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
   2561       InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
   2562                                                                      FnRetType,
   2563                                                             NRVOCandidate != 0);
   2564       ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
   2565                                                        FnRetType, RetValExp);
   2566       if (Res.isInvalid()) {
   2567         // FIXME: Cleanup temporaries here, anyway?
   2568         return StmtError();
   2569       }
   2570 
   2571       RetValExp = Res.takeAs<Expr>();
   2572       if (RetValExp)
   2573         CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
   2574     }
   2575 
   2576     if (RetValExp) {
   2577       ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
   2578       if (ER.isInvalid())
   2579         return StmtError();
   2580       RetValExp = ER.take();
   2581     }
   2582     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
   2583   }
   2584 
   2585   // If we need to check for the named return value optimization, save the
   2586   // return statement in our scope for later processing.
   2587   if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
   2588       !CurContext->isDependentContext())
   2589     FunctionScopes.back()->Returns.push_back(Result);
   2590 
   2591   return Owned(Result);
   2592 }
   2593 
   2594 StmtResult
   2595 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
   2596                            SourceLocation RParen, Decl *Parm,
   2597                            Stmt *Body) {
   2598   VarDecl *Var = cast_or_null<VarDecl>(Parm);
   2599   if (Var && Var->isInvalidDecl())
   2600     return StmtError();
   2601 
   2602   return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
   2603 }
   2604 
   2605 StmtResult
   2606 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
   2607   return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
   2608 }
   2609 
   2610 StmtResult
   2611 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
   2612                          MultiStmtArg CatchStmts, Stmt *Finally) {
   2613   if (!getLangOpts().ObjCExceptions)
   2614     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
   2615 
   2616   getCurFunction()->setHasBranchProtectedScope();
   2617   unsigned NumCatchStmts = CatchStmts.size();
   2618   return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
   2619                                      CatchStmts.data(),
   2620                                      NumCatchStmts,
   2621                                      Finally));
   2622 }
   2623 
   2624 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
   2625   if (Throw) {
   2626     ExprResult Result = DefaultLvalueConversion(Throw);
   2627     if (Result.isInvalid())
   2628       return StmtError();
   2629 
   2630     Result = ActOnFinishFullExpr(Result.take());
   2631     if (Result.isInvalid())
   2632       return StmtError();
   2633     Throw = Result.take();
   2634 
   2635     QualType ThrowType = Throw->getType();
   2636     // Make sure the expression type is an ObjC pointer or "void *".
   2637     if (!ThrowType->isDependentType() &&
   2638         !ThrowType->isObjCObjectPointerType()) {
   2639       const PointerType *PT = ThrowType->getAs<PointerType>();
   2640       if (!PT || !PT->getPointeeType()->isVoidType())
   2641         return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
   2642                          << Throw->getType() << Throw->getSourceRange());
   2643     }
   2644   }
   2645 
   2646   return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
   2647 }
   2648 
   2649 StmtResult
   2650 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
   2651                            Scope *CurScope) {
   2652   if (!getLangOpts().ObjCExceptions)
   2653     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
   2654 
   2655   if (!Throw) {
   2656     // @throw without an expression designates a rethrow (which much occur
   2657     // in the context of an @catch clause).
   2658     Scope *AtCatchParent = CurScope;
   2659     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
   2660       AtCatchParent = AtCatchParent->getParent();
   2661     if (!AtCatchParent)
   2662       return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
   2663   }
   2664   return BuildObjCAtThrowStmt(AtLoc, Throw);
   2665 }
   2666 
   2667 ExprResult
   2668 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
   2669   ExprResult result = DefaultLvalueConversion(operand);
   2670   if (result.isInvalid())
   2671     return ExprError();
   2672   operand = result.take();
   2673 
   2674   // Make sure the expression type is an ObjC pointer or "void *".
   2675   QualType type = operand->getType();
   2676   if (!type->isDependentType() &&
   2677       !type->isObjCObjectPointerType()) {
   2678     const PointerType *pointerType = type->getAs<PointerType>();
   2679     if (!pointerType || !pointerType->getPointeeType()->isVoidType())
   2680       return Diag(atLoc, diag::error_objc_synchronized_expects_object)
   2681                << type << operand->getSourceRange();
   2682   }
   2683 
   2684   // The operand to @synchronized is a full-expression.
   2685   return ActOnFinishFullExpr(operand);
   2686 }
   2687 
   2688 StmtResult
   2689 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
   2690                                   Stmt *SyncBody) {
   2691   // We can't jump into or indirect-jump out of a @synchronized block.
   2692   getCurFunction()->setHasBranchProtectedScope();
   2693   return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
   2694 }
   2695 
   2696 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
   2697 /// and creates a proper catch handler from them.
   2698 StmtResult
   2699 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
   2700                          Stmt *HandlerBlock) {
   2701   // There's nothing to test that ActOnExceptionDecl didn't already test.
   2702   return Owned(new (Context) CXXCatchStmt(CatchLoc,
   2703                                           cast_or_null<VarDecl>(ExDecl),
   2704                                           HandlerBlock));
   2705 }
   2706 
   2707 StmtResult
   2708 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
   2709   getCurFunction()->setHasBranchProtectedScope();
   2710   return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
   2711 }
   2712 
   2713 namespace {
   2714 
   2715 class TypeWithHandler {
   2716   QualType t;
   2717   CXXCatchStmt *stmt;
   2718 public:
   2719   TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
   2720   : t(type), stmt(statement) {}
   2721 
   2722   // An arbitrary order is fine as long as it places identical
   2723   // types next to each other.
   2724   bool operator<(const TypeWithHandler &y) const {
   2725     if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
   2726       return true;
   2727     if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
   2728       return false;
   2729     else
   2730       return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
   2731   }
   2732 
   2733   bool operator==(const TypeWithHandler& other) const {
   2734     return t == other.t;
   2735   }
   2736 
   2737   CXXCatchStmt *getCatchStmt() const { return stmt; }
   2738   SourceLocation getTypeSpecStartLoc() const {
   2739     return stmt->getExceptionDecl()->getTypeSpecStartLoc();
   2740   }
   2741 };
   2742 
   2743 }
   2744 
   2745 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
   2746 /// handlers and creates a try statement from them.
   2747 StmtResult
   2748 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
   2749                        MultiStmtArg RawHandlers) {
   2750   // Don't report an error if 'try' is used in system headers.
   2751   if (!getLangOpts().CXXExceptions &&
   2752       !getSourceManager().isInSystemHeader(TryLoc))
   2753       Diag(TryLoc, diag::err_exceptions_disabled) << "try";
   2754 
   2755   unsigned NumHandlers = RawHandlers.size();
   2756   assert(NumHandlers > 0 &&
   2757          "The parser shouldn't call this if there are no handlers.");
   2758   Stmt **Handlers = RawHandlers.data();
   2759 
   2760   SmallVector<TypeWithHandler, 8> TypesWithHandlers;
   2761 
   2762   for (unsigned i = 0; i < NumHandlers; ++i) {
   2763     CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
   2764     if (!Handler->getExceptionDecl()) {
   2765       if (i < NumHandlers - 1)
   2766         return StmtError(Diag(Handler->getLocStart(),
   2767                               diag::err_early_catch_all));
   2768 
   2769       continue;
   2770     }
   2771 
   2772     const QualType CaughtType = Handler->getCaughtType();
   2773     const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
   2774     TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
   2775   }
   2776 
   2777   // Detect handlers for the same type as an earlier one.
   2778   if (NumHandlers > 1) {
   2779     llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
   2780 
   2781     TypeWithHandler prev = TypesWithHandlers[0];
   2782     for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
   2783       TypeWithHandler curr = TypesWithHandlers[i];
   2784 
   2785       if (curr == prev) {
   2786         Diag(curr.getTypeSpecStartLoc(),
   2787              diag::warn_exception_caught_by_earlier_handler)
   2788           << curr.getCatchStmt()->getCaughtType().getAsString();
   2789         Diag(prev.getTypeSpecStartLoc(),
   2790              diag::note_previous_exception_handler)
   2791           << prev.getCatchStmt()->getCaughtType().getAsString();
   2792       }
   2793 
   2794       prev = curr;
   2795     }
   2796   }
   2797 
   2798   getCurFunction()->setHasBranchProtectedScope();
   2799 
   2800   // FIXME: We should detect handlers that cannot catch anything because an
   2801   // earlier handler catches a superclass. Need to find a method that is not
   2802   // quadratic for this.
   2803   // Neither of these are explicitly forbidden, but every compiler detects them
   2804   // and warns.
   2805 
   2806   return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
   2807                                   llvm::makeArrayRef(Handlers, NumHandlers)));
   2808 }
   2809 
   2810 StmtResult
   2811 Sema::ActOnSEHTryBlock(bool IsCXXTry,
   2812                        SourceLocation TryLoc,
   2813                        Stmt *TryBlock,
   2814                        Stmt *Handler) {
   2815   assert(TryBlock && Handler);
   2816 
   2817   getCurFunction()->setHasBranchProtectedScope();
   2818 
   2819   return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
   2820 }
   2821 
   2822 StmtResult
   2823 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
   2824                           Expr *FilterExpr,
   2825                           Stmt *Block) {
   2826   assert(FilterExpr && Block);
   2827 
   2828   if(!FilterExpr->getType()->isIntegerType()) {
   2829     return StmtError(Diag(FilterExpr->getExprLoc(),
   2830                      diag::err_filter_expression_integral)
   2831                      << FilterExpr->getType());
   2832   }
   2833 
   2834   return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
   2835 }
   2836 
   2837 StmtResult
   2838 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
   2839                            Stmt *Block) {
   2840   assert(Block);
   2841   return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
   2842 }
   2843 
   2844 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
   2845                                             bool IsIfExists,
   2846                                             NestedNameSpecifierLoc QualifierLoc,
   2847                                             DeclarationNameInfo NameInfo,
   2848                                             Stmt *Nested)
   2849 {
   2850   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
   2851                                              QualifierLoc, NameInfo,
   2852                                              cast<CompoundStmt>(Nested));
   2853 }
   2854 
   2855 
   2856 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
   2857                                             bool IsIfExists,
   2858                                             CXXScopeSpec &SS,
   2859                                             UnqualifiedId &Name,
   2860                                             Stmt *Nested) {
   2861   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
   2862                                     SS.getWithLocInContext(Context),
   2863                                     GetNameFromUnqualifiedId(Name),
   2864                                     Nested);
   2865 }
   2866