Home | History | Annotate | Download | only in Sema
      1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
      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 expressions.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Sema/SemaInternal.h"
     15 #include "clang/Sema/DelayedDiagnostic.h"
     16 #include "clang/Sema/Initialization.h"
     17 #include "clang/Sema/Lookup.h"
     18 #include "clang/Sema/ScopeInfo.h"
     19 #include "clang/Sema/AnalysisBasedWarnings.h"
     20 #include "clang/AST/ASTContext.h"
     21 #include "clang/AST/ASTConsumer.h"
     22 #include "clang/AST/ASTMutationListener.h"
     23 #include "clang/AST/CXXInheritance.h"
     24 #include "clang/AST/DeclObjC.h"
     25 #include "clang/AST/DeclTemplate.h"
     26 #include "clang/AST/EvaluatedExprVisitor.h"
     27 #include "clang/AST/Expr.h"
     28 #include "clang/AST/ExprCXX.h"
     29 #include "clang/AST/ExprObjC.h"
     30 #include "clang/AST/RecursiveASTVisitor.h"
     31 #include "clang/AST/TypeLoc.h"
     32 #include "clang/Basic/PartialDiagnostic.h"
     33 #include "clang/Basic/SourceManager.h"
     34 #include "clang/Basic/TargetInfo.h"
     35 #include "clang/Lex/LiteralSupport.h"
     36 #include "clang/Lex/Preprocessor.h"
     37 #include "clang/Sema/DeclSpec.h"
     38 #include "clang/Sema/Designator.h"
     39 #include "clang/Sema/Scope.h"
     40 #include "clang/Sema/ScopeInfo.h"
     41 #include "clang/Sema/ParsedTemplate.h"
     42 #include "clang/Sema/SemaFixItUtils.h"
     43 #include "clang/Sema/Template.h"
     44 #include "TreeTransform.h"
     45 using namespace clang;
     46 using namespace sema;
     47 
     48 /// \brief Determine whether the use of this declaration is valid, without
     49 /// emitting diagnostics.
     50 bool Sema::CanUseDecl(NamedDecl *D) {
     51   // See if this is an auto-typed variable whose initializer we are parsing.
     52   if (ParsingInitForAutoVars.count(D))
     53     return false;
     54 
     55   // See if this is a deleted function.
     56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
     57     if (FD->isDeleted())
     58       return false;
     59   }
     60 
     61   // See if this function is unavailable.
     62   if (D->getAvailability() == AR_Unavailable &&
     63       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
     64     return false;
     65 
     66   return true;
     67 }
     68 
     69 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
     70   // Warn if this is used but marked unused.
     71   if (D->hasAttr<UnusedAttr>()) {
     72     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
     73     if (!DC->hasAttr<UnusedAttr>())
     74       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
     75   }
     76 }
     77 
     78 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
     79                               NamedDecl *D, SourceLocation Loc,
     80                               const ObjCInterfaceDecl *UnknownObjCClass) {
     81   // See if this declaration is unavailable or deprecated.
     82   std::string Message;
     83   AvailabilityResult Result = D->getAvailability(&Message);
     84   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
     85     if (Result == AR_Available) {
     86       const DeclContext *DC = ECD->getDeclContext();
     87       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
     88         Result = TheEnumDecl->getAvailability(&Message);
     89     }
     90 
     91   switch (Result) {
     92     case AR_Available:
     93     case AR_NotYetIntroduced:
     94       break;
     95 
     96     case AR_Deprecated:
     97       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
     98       break;
     99 
    100     case AR_Unavailable:
    101       if (S.getCurContextAvailability() != AR_Unavailable) {
    102         if (Message.empty()) {
    103           if (!UnknownObjCClass)
    104             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
    105           else
    106             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
    107               << D->getDeclName();
    108         }
    109         else
    110           S.Diag(Loc, diag::err_unavailable_message)
    111             << D->getDeclName() << Message;
    112           S.Diag(D->getLocation(), diag::note_unavailable_here)
    113           << isa<FunctionDecl>(D) << false;
    114       }
    115       break;
    116     }
    117     return Result;
    118 }
    119 
    120 /// \brief Emit a note explaining that this function is deleted or unavailable.
    121 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
    122   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
    123 
    124   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
    125     // If the method was explicitly defaulted, point at that declaration.
    126     if (!Method->isImplicit())
    127       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
    128 
    129     // Try to diagnose why this special member function was implicitly
    130     // deleted. This might fail, if that reason no longer applies.
    131     CXXSpecialMember CSM = getSpecialMember(Method);
    132     if (CSM != CXXInvalid)
    133       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
    134 
    135     return;
    136   }
    137 
    138   Diag(Decl->getLocation(), diag::note_unavailable_here)
    139     << 1 << Decl->isDeleted();
    140 }
    141 
    142 /// \brief Determine whether a FunctionDecl was ever declared with an
    143 /// explicit storage class.
    144 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
    145   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
    146                                      E = D->redecls_end();
    147        I != E; ++I) {
    148     if (I->getStorageClassAsWritten() != SC_None)
    149       return true;
    150   }
    151   return false;
    152 }
    153 
    154 /// \brief Check whether we're in an extern inline function and referring to a
    155 /// variable or function with internal linkage (C11 6.7.4p3).
    156 ///
    157 /// This is only a warning because we used to silently accept this code, but
    158 /// in many cases it will not behave correctly. This is not enabled in C++ mode
    159 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
    160 /// and so while there may still be user mistakes, most of the time we can't
    161 /// prove that there are errors.
    162 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
    163                                                       const NamedDecl *D,
    164                                                       SourceLocation Loc) {
    165   // This is disabled under C++; there are too many ways for this to fire in
    166   // contexts where the warning is a false positive, or where it is technically
    167   // correct but benign.
    168   if (S.getLangOpts().CPlusPlus)
    169     return;
    170 
    171   // Check if this is an inlined function or method.
    172   FunctionDecl *Current = S.getCurFunctionDecl();
    173   if (!Current)
    174     return;
    175   if (!Current->isInlined())
    176     return;
    177   if (Current->getLinkage() != ExternalLinkage)
    178     return;
    179 
    180   // Check if the decl has internal linkage.
    181   if (D->getLinkage() != InternalLinkage)
    182     return;
    183 
    184   // Downgrade from ExtWarn to Extension if
    185   //  (1) the supposedly external inline function is in the main file,
    186   //      and probably won't be included anywhere else.
    187   //  (2) the thing we're referencing is a pure function.
    188   //  (3) the thing we're referencing is another inline function.
    189   // This last can give us false negatives, but it's better than warning on
    190   // wrappers for simple C library functions.
    191   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
    192   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
    193   if (!DowngradeWarning && UsedFn)
    194     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
    195 
    196   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
    197                                : diag::warn_internal_in_extern_inline)
    198     << /*IsVar=*/!UsedFn << D;
    199 
    200   // Suggest "static" on the inline function, if possible.
    201   if (!hasAnyExplicitStorageClass(Current)) {
    202     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
    203     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
    204     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
    205       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
    206   }
    207 
    208   S.Diag(D->getCanonicalDecl()->getLocation(),
    209          diag::note_internal_decl_declared_here)
    210     << D;
    211 }
    212 
    213 /// \brief Determine whether the use of this declaration is valid, and
    214 /// emit any corresponding diagnostics.
    215 ///
    216 /// This routine diagnoses various problems with referencing
    217 /// declarations that can occur when using a declaration. For example,
    218 /// it might warn if a deprecated or unavailable declaration is being
    219 /// used, or produce an error (and return true) if a C++0x deleted
    220 /// function is being used.
    221 ///
    222 /// \returns true if there was an error (this declaration cannot be
    223 /// referenced), false otherwise.
    224 ///
    225 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
    226                              const ObjCInterfaceDecl *UnknownObjCClass) {
    227   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
    228     // If there were any diagnostics suppressed by template argument deduction,
    229     // emit them now.
    230     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
    231       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
    232     if (Pos != SuppressedDiagnostics.end()) {
    233       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
    234       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
    235         Diag(Suppressed[I].first, Suppressed[I].second);
    236 
    237       // Clear out the list of suppressed diagnostics, so that we don't emit
    238       // them again for this specialization. However, we don't obsolete this
    239       // entry from the table, because we want to avoid ever emitting these
    240       // diagnostics again.
    241       Suppressed.clear();
    242     }
    243   }
    244 
    245   // See if this is an auto-typed variable whose initializer we are parsing.
    246   if (ParsingInitForAutoVars.count(D)) {
    247     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
    248       << D->getDeclName();
    249     return true;
    250   }
    251 
    252   // See if this is a deleted function.
    253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    254     if (FD->isDeleted()) {
    255       Diag(Loc, diag::err_deleted_function_use);
    256       NoteDeletedFunction(FD);
    257       return true;
    258     }
    259   }
    260   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
    261 
    262   DiagnoseUnusedOfDecl(*this, D, Loc);
    263 
    264   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
    265 
    266   return false;
    267 }
    268 
    269 /// \brief Retrieve the message suffix that should be added to a
    270 /// diagnostic complaining about the given function being deleted or
    271 /// unavailable.
    272 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
    273   // FIXME: C++0x implicitly-deleted special member functions could be
    274   // detected here so that we could improve diagnostics to say, e.g.,
    275   // "base class 'A' had a deleted copy constructor".
    276   if (FD->isDeleted())
    277     return std::string();
    278 
    279   std::string Message;
    280   if (FD->getAvailability(&Message))
    281     return ": " + Message;
    282 
    283   return std::string();
    284 }
    285 
    286 /// DiagnoseSentinelCalls - This routine checks whether a call or
    287 /// message-send is to a declaration with the sentinel attribute, and
    288 /// if so, it checks that the requirements of the sentinel are
    289 /// satisfied.
    290 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
    291                                  Expr **args, unsigned numArgs) {
    292   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
    293   if (!attr)
    294     return;
    295 
    296   // The number of formal parameters of the declaration.
    297   unsigned numFormalParams;
    298 
    299   // The kind of declaration.  This is also an index into a %select in
    300   // the diagnostic.
    301   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
    302 
    303   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
    304     numFormalParams = MD->param_size();
    305     calleeType = CT_Method;
    306   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    307     numFormalParams = FD->param_size();
    308     calleeType = CT_Function;
    309   } else if (isa<VarDecl>(D)) {
    310     QualType type = cast<ValueDecl>(D)->getType();
    311     const FunctionType *fn = 0;
    312     if (const PointerType *ptr = type->getAs<PointerType>()) {
    313       fn = ptr->getPointeeType()->getAs<FunctionType>();
    314       if (!fn) return;
    315       calleeType = CT_Function;
    316     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
    317       fn = ptr->getPointeeType()->castAs<FunctionType>();
    318       calleeType = CT_Block;
    319     } else {
    320       return;
    321     }
    322 
    323     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
    324       numFormalParams = proto->getNumArgs();
    325     } else {
    326       numFormalParams = 0;
    327     }
    328   } else {
    329     return;
    330   }
    331 
    332   // "nullPos" is the number of formal parameters at the end which
    333   // effectively count as part of the variadic arguments.  This is
    334   // useful if you would prefer to not have *any* formal parameters,
    335   // but the language forces you to have at least one.
    336   unsigned nullPos = attr->getNullPos();
    337   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
    338   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
    339 
    340   // The number of arguments which should follow the sentinel.
    341   unsigned numArgsAfterSentinel = attr->getSentinel();
    342 
    343   // If there aren't enough arguments for all the formal parameters,
    344   // the sentinel, and the args after the sentinel, complain.
    345   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
    346     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
    347     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
    348     return;
    349   }
    350 
    351   // Otherwise, find the sentinel expression.
    352   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
    353   if (!sentinelExpr) return;
    354   if (sentinelExpr->isValueDependent()) return;
    355   if (Context.isSentinelNullExpr(sentinelExpr)) return;
    356 
    357   // Pick a reasonable string to insert.  Optimistically use 'nil' or
    358   // 'NULL' if those are actually defined in the context.  Only use
    359   // 'nil' for ObjC methods, where it's much more likely that the
    360   // variadic arguments form a list of object pointers.
    361   SourceLocation MissingNilLoc
    362     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
    363   std::string NullValue;
    364   if (calleeType == CT_Method &&
    365       PP.getIdentifierInfo("nil")->hasMacroDefinition())
    366     NullValue = "nil";
    367   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
    368     NullValue = "NULL";
    369   else
    370     NullValue = "(void*) 0";
    371 
    372   if (MissingNilLoc.isInvalid())
    373     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
    374   else
    375     Diag(MissingNilLoc, diag::warn_missing_sentinel)
    376       << calleeType
    377       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
    378   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
    379 }
    380 
    381 SourceRange Sema::getExprRange(Expr *E) const {
    382   return E ? E->getSourceRange() : SourceRange();
    383 }
    384 
    385 //===----------------------------------------------------------------------===//
    386 //  Standard Promotions and Conversions
    387 //===----------------------------------------------------------------------===//
    388 
    389 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
    390 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
    391   // Handle any placeholder expressions which made it here.
    392   if (E->getType()->isPlaceholderType()) {
    393     ExprResult result = CheckPlaceholderExpr(E);
    394     if (result.isInvalid()) return ExprError();
    395     E = result.take();
    396   }
    397 
    398   QualType Ty = E->getType();
    399   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
    400 
    401   if (Ty->isFunctionType())
    402     E = ImpCastExprToType(E, Context.getPointerType(Ty),
    403                           CK_FunctionToPointerDecay).take();
    404   else if (Ty->isArrayType()) {
    405     // In C90 mode, arrays only promote to pointers if the array expression is
    406     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
    407     // type 'array of type' is converted to an expression that has type 'pointer
    408     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
    409     // that has type 'array of type' ...".  The relevant change is "an lvalue"
    410     // (C90) to "an expression" (C99).
    411     //
    412     // C++ 4.2p1:
    413     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
    414     // T" can be converted to an rvalue of type "pointer to T".
    415     //
    416     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
    417       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
    418                             CK_ArrayToPointerDecay).take();
    419   }
    420   return Owned(E);
    421 }
    422 
    423 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
    424   // Check to see if we are dereferencing a null pointer.  If so,
    425   // and if not volatile-qualified, this is undefined behavior that the
    426   // optimizer will delete, so warn about it.  People sometimes try to use this
    427   // to get a deterministic trap and are surprised by clang's behavior.  This
    428   // only handles the pattern "*null", which is a very syntactic check.
    429   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
    430     if (UO->getOpcode() == UO_Deref &&
    431         UO->getSubExpr()->IgnoreParenCasts()->
    432           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
    433         !UO->getType().isVolatileQualified()) {
    434     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    435                           S.PDiag(diag::warn_indirection_through_null)
    436                             << UO->getSubExpr()->getSourceRange());
    437     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    438                         S.PDiag(diag::note_indirection_through_null));
    439   }
    440 }
    441 
    442 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
    443   // Handle any placeholder expressions which made it here.
    444   if (E->getType()->isPlaceholderType()) {
    445     ExprResult result = CheckPlaceholderExpr(E);
    446     if (result.isInvalid()) return ExprError();
    447     E = result.take();
    448   }
    449 
    450   // C++ [conv.lval]p1:
    451   //   A glvalue of a non-function, non-array type T can be
    452   //   converted to a prvalue.
    453   if (!E->isGLValue()) return Owned(E);
    454 
    455   QualType T = E->getType();
    456   assert(!T.isNull() && "r-value conversion on typeless expression?");
    457 
    458   // We don't want to throw lvalue-to-rvalue casts on top of
    459   // expressions of certain types in C++.
    460   if (getLangOpts().CPlusPlus &&
    461       (E->getType() == Context.OverloadTy ||
    462        T->isDependentType() ||
    463        T->isRecordType()))
    464     return Owned(E);
    465 
    466   // The C standard is actually really unclear on this point, and
    467   // DR106 tells us what the result should be but not why.  It's
    468   // generally best to say that void types just doesn't undergo
    469   // lvalue-to-rvalue at all.  Note that expressions of unqualified
    470   // 'void' type are never l-values, but qualified void can be.
    471   if (T->isVoidType())
    472     return Owned(E);
    473 
    474   CheckForNullPointerDereference(*this, E);
    475 
    476   // C++ [conv.lval]p1:
    477   //   [...] If T is a non-class type, the type of the prvalue is the
    478   //   cv-unqualified version of T. Otherwise, the type of the
    479   //   rvalue is T.
    480   //
    481   // C99 6.3.2.1p2:
    482   //   If the lvalue has qualified type, the value has the unqualified
    483   //   version of the type of the lvalue; otherwise, the value has the
    484   //   type of the lvalue.
    485   if (T.hasQualifiers())
    486     T = T.getUnqualifiedType();
    487 
    488   UpdateMarkingForLValueToRValue(E);
    489 
    490   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
    491                                                   E, 0, VK_RValue));
    492 
    493   // C11 6.3.2.1p2:
    494   //   ... if the lvalue has atomic type, the value has the non-atomic version
    495   //   of the type of the lvalue ...
    496   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
    497     T = Atomic->getValueType().getUnqualifiedType();
    498     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
    499                                          Res.get(), 0, VK_RValue));
    500   }
    501 
    502   return Res;
    503 }
    504 
    505 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
    506   ExprResult Res = DefaultFunctionArrayConversion(E);
    507   if (Res.isInvalid())
    508     return ExprError();
    509   Res = DefaultLvalueConversion(Res.take());
    510   if (Res.isInvalid())
    511     return ExprError();
    512   return Res;
    513 }
    514 
    515 
    516 /// UsualUnaryConversions - Performs various conversions that are common to most
    517 /// operators (C99 6.3). The conversions of array and function types are
    518 /// sometimes suppressed. For example, the array->pointer conversion doesn't
    519 /// apply if the array is an argument to the sizeof or address (&) operators.
    520 /// In these instances, this routine should *not* be called.
    521 ExprResult Sema::UsualUnaryConversions(Expr *E) {
    522   // First, convert to an r-value.
    523   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
    524   if (Res.isInvalid())
    525     return Owned(E);
    526   E = Res.take();
    527 
    528   QualType Ty = E->getType();
    529   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
    530 
    531   // Half FP is a bit different: it's a storage-only type, meaning that any
    532   // "use" of it should be promoted to float.
    533   if (Ty->isHalfType())
    534     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
    535 
    536   // Try to perform integral promotions if the object has a theoretically
    537   // promotable type.
    538   if (Ty->isIntegralOrUnscopedEnumerationType()) {
    539     // C99 6.3.1.1p2:
    540     //
    541     //   The following may be used in an expression wherever an int or
    542     //   unsigned int may be used:
    543     //     - an object or expression with an integer type whose integer
    544     //       conversion rank is less than or equal to the rank of int
    545     //       and unsigned int.
    546     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
    547     //
    548     //   If an int can represent all values of the original type, the
    549     //   value is converted to an int; otherwise, it is converted to an
    550     //   unsigned int. These are called the integer promotions. All
    551     //   other types are unchanged by the integer promotions.
    552 
    553     QualType PTy = Context.isPromotableBitField(E);
    554     if (!PTy.isNull()) {
    555       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
    556       return Owned(E);
    557     }
    558     if (Ty->isPromotableIntegerType()) {
    559       QualType PT = Context.getPromotedIntegerType(Ty);
    560       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
    561       return Owned(E);
    562     }
    563   }
    564   return Owned(E);
    565 }
    566 
    567 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
    568 /// do not have a prototype. Arguments that have type float are promoted to
    569 /// double. All other argument types are converted by UsualUnaryConversions().
    570 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
    571   QualType Ty = E->getType();
    572   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
    573 
    574   ExprResult Res = UsualUnaryConversions(E);
    575   if (Res.isInvalid())
    576     return Owned(E);
    577   E = Res.take();
    578 
    579   // If this is a 'float' (CVR qualified or typedef) promote to double.
    580   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
    581     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
    582 
    583   // C++ performs lvalue-to-rvalue conversion as a default argument
    584   // promotion, even on class types, but note:
    585   //   C++11 [conv.lval]p2:
    586   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
    587   //     operand or a subexpression thereof the value contained in the
    588   //     referenced object is not accessed. Otherwise, if the glvalue
    589   //     has a class type, the conversion copy-initializes a temporary
    590   //     of type T from the glvalue and the result of the conversion
    591   //     is a prvalue for the temporary.
    592   // FIXME: add some way to gate this entire thing for correctness in
    593   // potentially potentially evaluated contexts.
    594   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
    595     ExprResult Temp = PerformCopyInitialization(
    596                        InitializedEntity::InitializeTemporary(E->getType()),
    597                                                 E->getExprLoc(),
    598                                                 Owned(E));
    599     if (Temp.isInvalid())
    600       return ExprError();
    601     E = Temp.get();
    602   }
    603 
    604   return Owned(E);
    605 }
    606 
    607 /// Determine the degree of POD-ness for an expression.
    608 /// Incomplete types are considered POD, since this check can be performed
    609 /// when we're in an unevaluated context.
    610 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
    611   if (Ty->isIncompleteType()) {
    612     if (Ty->isObjCObjectType())
    613       return VAK_Invalid;
    614     return VAK_Valid;
    615   }
    616 
    617   if (Ty.isCXX98PODType(Context))
    618     return VAK_Valid;
    619 
    620   // C++0x [expr.call]p7:
    621   //   Passing a potentially-evaluated argument of class type (Clause 9)
    622   //   having a non-trivial copy constructor, a non-trivial move constructor,
    623   //   or a non-trivial destructor, with no corresponding parameter,
    624   //   is conditionally-supported with implementation-defined semantics.
    625   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
    626     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
    627       if (Record->hasTrivialCopyConstructor() &&
    628           Record->hasTrivialMoveConstructor() &&
    629           Record->hasTrivialDestructor())
    630         return VAK_ValidInCXX11;
    631 
    632   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
    633     return VAK_Valid;
    634   return VAK_Invalid;
    635 }
    636 
    637 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
    638   // Don't allow one to pass an Objective-C interface to a vararg.
    639   const QualType & Ty = E->getType();
    640 
    641   // Complain about passing non-POD types through varargs.
    642   switch (isValidVarArgType(Ty)) {
    643   case VAK_Valid:
    644     break;
    645   case VAK_ValidInCXX11:
    646     DiagRuntimeBehavior(E->getLocStart(), 0,
    647         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
    648         << E->getType() << CT);
    649     break;
    650   case VAK_Invalid: {
    651     if (Ty->isObjCObjectType())
    652       return DiagRuntimeBehavior(E->getLocStart(), 0,
    653                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
    654                             << Ty << CT);
    655 
    656     return DiagRuntimeBehavior(E->getLocStart(), 0,
    657                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
    658                    << getLangOpts().CPlusPlus0x << Ty << CT);
    659   }
    660   }
    661   // c++ rules are enforced elsewhere.
    662   return false;
    663 }
    664 
    665 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
    666 /// will create a trap if the resulting type is not a POD type.
    667 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
    668                                                   FunctionDecl *FDecl) {
    669   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
    670     // Strip the unbridged-cast placeholder expression off, if applicable.
    671     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
    672         (CT == VariadicMethod ||
    673          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
    674       E = stripARCUnbridgedCast(E);
    675 
    676     // Otherwise, do normal placeholder checking.
    677     } else {
    678       ExprResult ExprRes = CheckPlaceholderExpr(E);
    679       if (ExprRes.isInvalid())
    680         return ExprError();
    681       E = ExprRes.take();
    682     }
    683   }
    684 
    685   ExprResult ExprRes = DefaultArgumentPromotion(E);
    686   if (ExprRes.isInvalid())
    687     return ExprError();
    688   E = ExprRes.take();
    689 
    690   // Diagnostics regarding non-POD argument types are
    691   // emitted along with format string checking in Sema::CheckFunctionCall().
    692   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
    693     // Turn this into a trap.
    694     CXXScopeSpec SS;
    695     SourceLocation TemplateKWLoc;
    696     UnqualifiedId Name;
    697     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
    698                        E->getLocStart());
    699     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
    700                                           Name, true, false);
    701     if (TrapFn.isInvalid())
    702       return ExprError();
    703 
    704     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
    705                                     E->getLocStart(), MultiExprArg(),
    706                                     E->getLocEnd());
    707     if (Call.isInvalid())
    708       return ExprError();
    709 
    710     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
    711                                   Call.get(), E);
    712     if (Comma.isInvalid())
    713       return ExprError();
    714     return Comma.get();
    715   }
    716 
    717   if (!getLangOpts().CPlusPlus &&
    718       RequireCompleteType(E->getExprLoc(), E->getType(),
    719                           diag::err_call_incomplete_argument))
    720     return ExprError();
    721 
    722   return Owned(E);
    723 }
    724 
    725 /// \brief Converts an integer to complex float type.  Helper function of
    726 /// UsualArithmeticConversions()
    727 ///
    728 /// \return false if the integer expression is an integer type and is
    729 /// successfully converted to the complex type.
    730 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
    731                                                   ExprResult &ComplexExpr,
    732                                                   QualType IntTy,
    733                                                   QualType ComplexTy,
    734                                                   bool SkipCast) {
    735   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
    736   if (SkipCast) return false;
    737   if (IntTy->isIntegerType()) {
    738     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
    739     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
    740     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
    741                                   CK_FloatingRealToComplex);
    742   } else {
    743     assert(IntTy->isComplexIntegerType());
    744     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
    745                                   CK_IntegralComplexToFloatingComplex);
    746   }
    747   return false;
    748 }
    749 
    750 /// \brief Takes two complex float types and converts them to the same type.
    751 /// Helper function of UsualArithmeticConversions()
    752 static QualType
    753 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
    754                                             ExprResult &RHS, QualType LHSType,
    755                                             QualType RHSType,
    756                                             bool IsCompAssign) {
    757   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
    758 
    759   if (order < 0) {
    760     // _Complex float -> _Complex double
    761     if (!IsCompAssign)
    762       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
    763     return RHSType;
    764   }
    765   if (order > 0)
    766     // _Complex float -> _Complex double
    767     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
    768   return LHSType;
    769 }
    770 
    771 /// \brief Converts otherExpr to complex float and promotes complexExpr if
    772 /// necessary.  Helper function of UsualArithmeticConversions()
    773 static QualType handleOtherComplexFloatConversion(Sema &S,
    774                                                   ExprResult &ComplexExpr,
    775                                                   ExprResult &OtherExpr,
    776                                                   QualType ComplexTy,
    777                                                   QualType OtherTy,
    778                                                   bool ConvertComplexExpr,
    779                                                   bool ConvertOtherExpr) {
    780   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
    781 
    782   // If just the complexExpr is complex, the otherExpr needs to be converted,
    783   // and the complexExpr might need to be promoted.
    784   if (order > 0) { // complexExpr is wider
    785     // float -> _Complex double
    786     if (ConvertOtherExpr) {
    787       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
    788       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
    789       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
    790                                       CK_FloatingRealToComplex);
    791     }
    792     return ComplexTy;
    793   }
    794 
    795   // otherTy is at least as wide.  Find its corresponding complex type.
    796   QualType result = (order == 0 ? ComplexTy :
    797                                   S.Context.getComplexType(OtherTy));
    798 
    799   // double -> _Complex double
    800   if (ConvertOtherExpr)
    801     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
    802                                     CK_FloatingRealToComplex);
    803 
    804   // _Complex float -> _Complex double
    805   if (ConvertComplexExpr && order < 0)
    806     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
    807                                       CK_FloatingComplexCast);
    808 
    809   return result;
    810 }
    811 
    812 /// \brief Handle arithmetic conversion with complex types.  Helper function of
    813 /// UsualArithmeticConversions()
    814 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
    815                                              ExprResult &RHS, QualType LHSType,
    816                                              QualType RHSType,
    817                                              bool IsCompAssign) {
    818   // if we have an integer operand, the result is the complex type.
    819   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
    820                                              /*skipCast*/false))
    821     return LHSType;
    822   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
    823                                              /*skipCast*/IsCompAssign))
    824     return RHSType;
    825 
    826   // This handles complex/complex, complex/float, or float/complex.
    827   // When both operands are complex, the shorter operand is converted to the
    828   // type of the longer, and that is the type of the result. This corresponds
    829   // to what is done when combining two real floating-point operands.
    830   // The fun begins when size promotion occur across type domains.
    831   // From H&S 6.3.4: When one operand is complex and the other is a real
    832   // floating-point type, the less precise type is converted, within it's
    833   // real or complex domain, to the precision of the other type. For example,
    834   // when combining a "long double" with a "double _Complex", the
    835   // "double _Complex" is promoted to "long double _Complex".
    836 
    837   bool LHSComplexFloat = LHSType->isComplexType();
    838   bool RHSComplexFloat = RHSType->isComplexType();
    839 
    840   // If both are complex, just cast to the more precise type.
    841   if (LHSComplexFloat && RHSComplexFloat)
    842     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
    843                                                        LHSType, RHSType,
    844                                                        IsCompAssign);
    845 
    846   // If only one operand is complex, promote it if necessary and convert the
    847   // other operand to complex.
    848   if (LHSComplexFloat)
    849     return handleOtherComplexFloatConversion(
    850         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
    851         /*convertOtherExpr*/ true);
    852 
    853   assert(RHSComplexFloat);
    854   return handleOtherComplexFloatConversion(
    855       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
    856       /*convertOtherExpr*/ !IsCompAssign);
    857 }
    858 
    859 /// \brief Hande arithmetic conversion from integer to float.  Helper function
    860 /// of UsualArithmeticConversions()
    861 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
    862                                            ExprResult &IntExpr,
    863                                            QualType FloatTy, QualType IntTy,
    864                                            bool ConvertFloat, bool ConvertInt) {
    865   if (IntTy->isIntegerType()) {
    866     if (ConvertInt)
    867       // Convert intExpr to the lhs floating point type.
    868       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
    869                                     CK_IntegralToFloating);
    870     return FloatTy;
    871   }
    872 
    873   // Convert both sides to the appropriate complex float.
    874   assert(IntTy->isComplexIntegerType());
    875   QualType result = S.Context.getComplexType(FloatTy);
    876 
    877   // _Complex int -> _Complex float
    878   if (ConvertInt)
    879     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
    880                                   CK_IntegralComplexToFloatingComplex);
    881 
    882   // float -> _Complex float
    883   if (ConvertFloat)
    884     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
    885                                     CK_FloatingRealToComplex);
    886 
    887   return result;
    888 }
    889 
    890 /// \brief Handle arithmethic conversion with floating point types.  Helper
    891 /// function of UsualArithmeticConversions()
    892 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
    893                                       ExprResult &RHS, QualType LHSType,
    894                                       QualType RHSType, bool IsCompAssign) {
    895   bool LHSFloat = LHSType->isRealFloatingType();
    896   bool RHSFloat = RHSType->isRealFloatingType();
    897 
    898   // If we have two real floating types, convert the smaller operand
    899   // to the bigger result.
    900   if (LHSFloat && RHSFloat) {
    901     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
    902     if (order > 0) {
    903       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
    904       return LHSType;
    905     }
    906 
    907     assert(order < 0 && "illegal float comparison");
    908     if (!IsCompAssign)
    909       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
    910     return RHSType;
    911   }
    912 
    913   if (LHSFloat)
    914     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
    915                                       /*convertFloat=*/!IsCompAssign,
    916                                       /*convertInt=*/ true);
    917   assert(RHSFloat);
    918   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
    919                                     /*convertInt=*/ true,
    920                                     /*convertFloat=*/!IsCompAssign);
    921 }
    922 
    923 /// \brief Handle conversions with GCC complex int extension.  Helper function
    924 /// of UsualArithmeticConversions()
    925 // FIXME: if the operands are (int, _Complex long), we currently
    926 // don't promote the complex.  Also, signedness?
    927 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
    928                                            ExprResult &RHS, QualType LHSType,
    929                                            QualType RHSType,
    930                                            bool IsCompAssign) {
    931   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
    932   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
    933 
    934   if (LHSComplexInt && RHSComplexInt) {
    935     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
    936                                               RHSComplexInt->getElementType());
    937     assert(order && "inequal types with equal element ordering");
    938     if (order > 0) {
    939       // _Complex int -> _Complex long
    940       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
    941       return LHSType;
    942     }
    943 
    944     if (!IsCompAssign)
    945       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
    946     return RHSType;
    947   }
    948 
    949   if (LHSComplexInt) {
    950     // int -> _Complex int
    951     // FIXME: This needs to take integer ranks into account
    952     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
    953                               CK_IntegralCast);
    954     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
    955     return LHSType;
    956   }
    957 
    958   assert(RHSComplexInt);
    959   // int -> _Complex int
    960   // FIXME: This needs to take integer ranks into account
    961   if (!IsCompAssign) {
    962     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
    963                               CK_IntegralCast);
    964     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
    965   }
    966   return RHSType;
    967 }
    968 
    969 /// \brief Handle integer arithmetic conversions.  Helper function of
    970 /// UsualArithmeticConversions()
    971 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
    972                                         ExprResult &RHS, QualType LHSType,
    973                                         QualType RHSType, bool IsCompAssign) {
    974   // The rules for this case are in C99 6.3.1.8
    975   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
    976   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
    977   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
    978   if (LHSSigned == RHSSigned) {
    979     // Same signedness; use the higher-ranked type
    980     if (order >= 0) {
    981       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
    982       return LHSType;
    983     } else if (!IsCompAssign)
    984       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
    985     return RHSType;
    986   } else if (order != (LHSSigned ? 1 : -1)) {
    987     // The unsigned type has greater than or equal rank to the
    988     // signed type, so use the unsigned type
    989     if (RHSSigned) {
    990       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
    991       return LHSType;
    992     } else if (!IsCompAssign)
    993       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
    994     return RHSType;
    995   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
    996     // The two types are different widths; if we are here, that
    997     // means the signed type is larger than the unsigned type, so
    998     // use the signed type.
    999     if (LHSSigned) {
   1000       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
   1001       return LHSType;
   1002     } else if (!IsCompAssign)
   1003       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
   1004     return RHSType;
   1005   } else {
   1006     // The signed type is higher-ranked than the unsigned type,
   1007     // but isn't actually any bigger (like unsigned int and long
   1008     // on most 32-bit systems).  Use the unsigned type corresponding
   1009     // to the signed type.
   1010     QualType result =
   1011       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
   1012     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
   1013     if (!IsCompAssign)
   1014       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
   1015     return result;
   1016   }
   1017 }
   1018 
   1019 /// UsualArithmeticConversions - Performs various conversions that are common to
   1020 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
   1021 /// routine returns the first non-arithmetic type found. The client is
   1022 /// responsible for emitting appropriate error diagnostics.
   1023 /// FIXME: verify the conversion rules for "complex int" are consistent with
   1024 /// GCC.
   1025 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
   1026                                           bool IsCompAssign) {
   1027   if (!IsCompAssign) {
   1028     LHS = UsualUnaryConversions(LHS.take());
   1029     if (LHS.isInvalid())
   1030       return QualType();
   1031   }
   1032 
   1033   RHS = UsualUnaryConversions(RHS.take());
   1034   if (RHS.isInvalid())
   1035     return QualType();
   1036 
   1037   // For conversion purposes, we ignore any qualifiers.
   1038   // For example, "const float" and "float" are equivalent.
   1039   QualType LHSType =
   1040     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
   1041   QualType RHSType =
   1042     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
   1043 
   1044   // For conversion purposes, we ignore any atomic qualifier on the LHS.
   1045   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
   1046     LHSType = AtomicLHS->getValueType();
   1047 
   1048   // If both types are identical, no conversion is needed.
   1049   if (LHSType == RHSType)
   1050     return LHSType;
   1051 
   1052   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
   1053   // The caller can deal with this (e.g. pointer + int).
   1054   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
   1055     return QualType();
   1056 
   1057   // Apply unary and bitfield promotions to the LHS's type.
   1058   QualType LHSUnpromotedType = LHSType;
   1059   if (LHSType->isPromotableIntegerType())
   1060     LHSType = Context.getPromotedIntegerType(LHSType);
   1061   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
   1062   if (!LHSBitfieldPromoteTy.isNull())
   1063     LHSType = LHSBitfieldPromoteTy;
   1064   if (LHSType != LHSUnpromotedType && !IsCompAssign)
   1065     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
   1066 
   1067   // If both types are identical, no conversion is needed.
   1068   if (LHSType == RHSType)
   1069     return LHSType;
   1070 
   1071   // At this point, we have two different arithmetic types.
   1072 
   1073   // Handle complex types first (C99 6.3.1.8p1).
   1074   if (LHSType->isComplexType() || RHSType->isComplexType())
   1075     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1076                                         IsCompAssign);
   1077 
   1078   // Now handle "real" floating types (i.e. float, double, long double).
   1079   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
   1080     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1081                                  IsCompAssign);
   1082 
   1083   // Handle GCC complex int extension.
   1084   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
   1085     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
   1086                                       IsCompAssign);
   1087 
   1088   // Finally, we have two differing integer types.
   1089   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
   1090                                  IsCompAssign);
   1091 }
   1092 
   1093 //===----------------------------------------------------------------------===//
   1094 //  Semantic Analysis for various Expression Types
   1095 //===----------------------------------------------------------------------===//
   1096 
   1097 
   1098 ExprResult
   1099 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
   1100                                 SourceLocation DefaultLoc,
   1101                                 SourceLocation RParenLoc,
   1102                                 Expr *ControllingExpr,
   1103                                 MultiTypeArg ArgTypes,
   1104                                 MultiExprArg ArgExprs) {
   1105   unsigned NumAssocs = ArgTypes.size();
   1106   assert(NumAssocs == ArgExprs.size());
   1107 
   1108   ParsedType *ParsedTypes = ArgTypes.data();
   1109   Expr **Exprs = ArgExprs.data();
   1110 
   1111   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
   1112   for (unsigned i = 0; i < NumAssocs; ++i) {
   1113     if (ParsedTypes[i])
   1114       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
   1115     else
   1116       Types[i] = 0;
   1117   }
   1118 
   1119   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1120                                              ControllingExpr, Types, Exprs,
   1121                                              NumAssocs);
   1122   delete [] Types;
   1123   return ER;
   1124 }
   1125 
   1126 ExprResult
   1127 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
   1128                                  SourceLocation DefaultLoc,
   1129                                  SourceLocation RParenLoc,
   1130                                  Expr *ControllingExpr,
   1131                                  TypeSourceInfo **Types,
   1132                                  Expr **Exprs,
   1133                                  unsigned NumAssocs) {
   1134   bool TypeErrorFound = false,
   1135        IsResultDependent = ControllingExpr->isTypeDependent(),
   1136        ContainsUnexpandedParameterPack
   1137          = ControllingExpr->containsUnexpandedParameterPack();
   1138 
   1139   for (unsigned i = 0; i < NumAssocs; ++i) {
   1140     if (Exprs[i]->containsUnexpandedParameterPack())
   1141       ContainsUnexpandedParameterPack = true;
   1142 
   1143     if (Types[i]) {
   1144       if (Types[i]->getType()->containsUnexpandedParameterPack())
   1145         ContainsUnexpandedParameterPack = true;
   1146 
   1147       if (Types[i]->getType()->isDependentType()) {
   1148         IsResultDependent = true;
   1149       } else {
   1150         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
   1151         // complete object type other than a variably modified type."
   1152         unsigned D = 0;
   1153         if (Types[i]->getType()->isIncompleteType())
   1154           D = diag::err_assoc_type_incomplete;
   1155         else if (!Types[i]->getType()->isObjectType())
   1156           D = diag::err_assoc_type_nonobject;
   1157         else if (Types[i]->getType()->isVariablyModifiedType())
   1158           D = diag::err_assoc_type_variably_modified;
   1159 
   1160         if (D != 0) {
   1161           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
   1162             << Types[i]->getTypeLoc().getSourceRange()
   1163             << Types[i]->getType();
   1164           TypeErrorFound = true;
   1165         }
   1166 
   1167         // C11 6.5.1.1p2 "No two generic associations in the same generic
   1168         // selection shall specify compatible types."
   1169         for (unsigned j = i+1; j < NumAssocs; ++j)
   1170           if (Types[j] && !Types[j]->getType()->isDependentType() &&
   1171               Context.typesAreCompatible(Types[i]->getType(),
   1172                                          Types[j]->getType())) {
   1173             Diag(Types[j]->getTypeLoc().getBeginLoc(),
   1174                  diag::err_assoc_compatible_types)
   1175               << Types[j]->getTypeLoc().getSourceRange()
   1176               << Types[j]->getType()
   1177               << Types[i]->getType();
   1178             Diag(Types[i]->getTypeLoc().getBeginLoc(),
   1179                  diag::note_compat_assoc)
   1180               << Types[i]->getTypeLoc().getSourceRange()
   1181               << Types[i]->getType();
   1182             TypeErrorFound = true;
   1183           }
   1184       }
   1185     }
   1186   }
   1187   if (TypeErrorFound)
   1188     return ExprError();
   1189 
   1190   // If we determined that the generic selection is result-dependent, don't
   1191   // try to compute the result expression.
   1192   if (IsResultDependent)
   1193     return Owned(new (Context) GenericSelectionExpr(
   1194                    Context, KeyLoc, ControllingExpr,
   1195                    llvm::makeArrayRef(Types, NumAssocs),
   1196                    llvm::makeArrayRef(Exprs, NumAssocs),
   1197                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
   1198 
   1199   SmallVector<unsigned, 1> CompatIndices;
   1200   unsigned DefaultIndex = -1U;
   1201   for (unsigned i = 0; i < NumAssocs; ++i) {
   1202     if (!Types[i])
   1203       DefaultIndex = i;
   1204     else if (Context.typesAreCompatible(ControllingExpr->getType(),
   1205                                         Types[i]->getType()))
   1206       CompatIndices.push_back(i);
   1207   }
   1208 
   1209   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
   1210   // type compatible with at most one of the types named in its generic
   1211   // association list."
   1212   if (CompatIndices.size() > 1) {
   1213     // We strip parens here because the controlling expression is typically
   1214     // parenthesized in macro definitions.
   1215     ControllingExpr = ControllingExpr->IgnoreParens();
   1216     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
   1217       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
   1218       << (unsigned) CompatIndices.size();
   1219     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
   1220          E = CompatIndices.end(); I != E; ++I) {
   1221       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
   1222            diag::note_compat_assoc)
   1223         << Types[*I]->getTypeLoc().getSourceRange()
   1224         << Types[*I]->getType();
   1225     }
   1226     return ExprError();
   1227   }
   1228 
   1229   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
   1230   // its controlling expression shall have type compatible with exactly one of
   1231   // the types named in its generic association list."
   1232   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
   1233     // We strip parens here because the controlling expression is typically
   1234     // parenthesized in macro definitions.
   1235     ControllingExpr = ControllingExpr->IgnoreParens();
   1236     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
   1237       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
   1238     return ExprError();
   1239   }
   1240 
   1241   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
   1242   // type name that is compatible with the type of the controlling expression,
   1243   // then the result expression of the generic selection is the expression
   1244   // in that generic association. Otherwise, the result expression of the
   1245   // generic selection is the expression in the default generic association."
   1246   unsigned ResultIndex =
   1247     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
   1248 
   1249   return Owned(new (Context) GenericSelectionExpr(
   1250                  Context, KeyLoc, ControllingExpr,
   1251                  llvm::makeArrayRef(Types, NumAssocs),
   1252                  llvm::makeArrayRef(Exprs, NumAssocs),
   1253                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
   1254                  ResultIndex));
   1255 }
   1256 
   1257 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
   1258 /// location of the token and the offset of the ud-suffix within it.
   1259 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
   1260                                      unsigned Offset) {
   1261   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
   1262                                         S.getLangOpts());
   1263 }
   1264 
   1265 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
   1266 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
   1267 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
   1268                                                  IdentifierInfo *UDSuffix,
   1269                                                  SourceLocation UDSuffixLoc,
   1270                                                  ArrayRef<Expr*> Args,
   1271                                                  SourceLocation LitEndLoc) {
   1272   assert(Args.size() <= 2 && "too many arguments for literal operator");
   1273 
   1274   QualType ArgTy[2];
   1275   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
   1276     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
   1277     if (ArgTy[ArgIdx]->isArrayType())
   1278       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
   1279   }
   1280 
   1281   DeclarationName OpName =
   1282     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   1283   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   1284   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   1285 
   1286   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
   1287   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
   1288                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
   1289     return ExprError();
   1290 
   1291   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
   1292 }
   1293 
   1294 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   1295 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
   1296 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
   1297 /// multiple tokens.  However, the common case is that StringToks points to one
   1298 /// string.
   1299 ///
   1300 ExprResult
   1301 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
   1302                          Scope *UDLScope) {
   1303   assert(NumStringToks && "Must have at least one string!");
   1304 
   1305   StringLiteralParser Literal(StringToks, NumStringToks, PP);
   1306   if (Literal.hadError)
   1307     return ExprError();
   1308 
   1309   SmallVector<SourceLocation, 4> StringTokLocs;
   1310   for (unsigned i = 0; i != NumStringToks; ++i)
   1311     StringTokLocs.push_back(StringToks[i].getLocation());
   1312 
   1313   QualType StrTy = Context.CharTy;
   1314   if (Literal.isWide())
   1315     StrTy = Context.getWCharType();
   1316   else if (Literal.isUTF16())
   1317     StrTy = Context.Char16Ty;
   1318   else if (Literal.isUTF32())
   1319     StrTy = Context.Char32Ty;
   1320   else if (Literal.isPascal())
   1321     StrTy = Context.UnsignedCharTy;
   1322 
   1323   StringLiteral::StringKind Kind = StringLiteral::Ascii;
   1324   if (Literal.isWide())
   1325     Kind = StringLiteral::Wide;
   1326   else if (Literal.isUTF8())
   1327     Kind = StringLiteral::UTF8;
   1328   else if (Literal.isUTF16())
   1329     Kind = StringLiteral::UTF16;
   1330   else if (Literal.isUTF32())
   1331     Kind = StringLiteral::UTF32;
   1332 
   1333   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
   1334   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
   1335     StrTy.addConst();
   1336 
   1337   // Get an array type for the string, according to C99 6.4.5.  This includes
   1338   // the nul terminator character as well as the string length for pascal
   1339   // strings.
   1340   StrTy = Context.getConstantArrayType(StrTy,
   1341                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
   1342                                        ArrayType::Normal, 0);
   1343 
   1344   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
   1345   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
   1346                                              Kind, Literal.Pascal, StrTy,
   1347                                              &StringTokLocs[0],
   1348                                              StringTokLocs.size());
   1349   if (Literal.getUDSuffix().empty())
   1350     return Owned(Lit);
   1351 
   1352   // We're building a user-defined literal.
   1353   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   1354   SourceLocation UDSuffixLoc =
   1355     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
   1356                    Literal.getUDSuffixOffset());
   1357 
   1358   // Make sure we're allowed user-defined literals here.
   1359   if (!UDLScope)
   1360     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
   1361 
   1362   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
   1363   //   operator "" X (str, len)
   1364   QualType SizeType = Context.getSizeType();
   1365   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
   1366   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
   1367                                                   StringTokLocs[0]);
   1368   Expr *Args[] = { Lit, LenArg };
   1369   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
   1370                                         Args, StringTokLocs.back());
   1371 }
   1372 
   1373 ExprResult
   1374 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1375                        SourceLocation Loc,
   1376                        const CXXScopeSpec *SS) {
   1377   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
   1378   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
   1379 }
   1380 
   1381 /// BuildDeclRefExpr - Build an expression that references a
   1382 /// declaration that does not require a closure capture.
   1383 ExprResult
   1384 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1385                        const DeclarationNameInfo &NameInfo,
   1386                        const CXXScopeSpec *SS) {
   1387   if (getLangOpts().CUDA)
   1388     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
   1389       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
   1390         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
   1391                            CalleeTarget = IdentifyCUDATarget(Callee);
   1392         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
   1393           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
   1394             << CalleeTarget << D->getIdentifier() << CallerTarget;
   1395           Diag(D->getLocation(), diag::note_previous_decl)
   1396             << D->getIdentifier();
   1397           return ExprError();
   1398         }
   1399       }
   1400 
   1401   bool refersToEnclosingScope =
   1402     (CurContext != D->getDeclContext() &&
   1403      D->getDeclContext()->isFunctionOrMethod());
   1404 
   1405   DeclRefExpr *E = DeclRefExpr::Create(Context,
   1406                                        SS ? SS->getWithLocInContext(Context)
   1407                                               : NestedNameSpecifierLoc(),
   1408                                        SourceLocation(),
   1409                                        D, refersToEnclosingScope,
   1410                                        NameInfo, Ty, VK);
   1411 
   1412   MarkDeclRefReferenced(E);
   1413 
   1414   // Just in case we're building an illegal pointer-to-member.
   1415   FieldDecl *FD = dyn_cast<FieldDecl>(D);
   1416   if (FD && FD->isBitField())
   1417     E->setObjectKind(OK_BitField);
   1418 
   1419   return Owned(E);
   1420 }
   1421 
   1422 /// Decomposes the given name into a DeclarationNameInfo, its location, and
   1423 /// possibly a list of template arguments.
   1424 ///
   1425 /// If this produces template arguments, it is permitted to call
   1426 /// DecomposeTemplateName.
   1427 ///
   1428 /// This actually loses a lot of source location information for
   1429 /// non-standard name kinds; we should consider preserving that in
   1430 /// some way.
   1431 void
   1432 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
   1433                              TemplateArgumentListInfo &Buffer,
   1434                              DeclarationNameInfo &NameInfo,
   1435                              const TemplateArgumentListInfo *&TemplateArgs) {
   1436   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
   1437     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
   1438     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
   1439 
   1440     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
   1441                                        Id.TemplateId->NumArgs);
   1442     translateTemplateArguments(TemplateArgsPtr, Buffer);
   1443 
   1444     TemplateName TName = Id.TemplateId->Template.get();
   1445     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
   1446     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
   1447     TemplateArgs = &Buffer;
   1448   } else {
   1449     NameInfo = GetNameFromUnqualifiedId(Id);
   1450     TemplateArgs = 0;
   1451   }
   1452 }
   1453 
   1454 /// Diagnose an empty lookup.
   1455 ///
   1456 /// \return false if new lookup candidates were found
   1457 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
   1458                                CorrectionCandidateCallback &CCC,
   1459                                TemplateArgumentListInfo *ExplicitTemplateArgs,
   1460                                llvm::ArrayRef<Expr *> Args) {
   1461   DeclarationName Name = R.getLookupName();
   1462 
   1463   unsigned diagnostic = diag::err_undeclared_var_use;
   1464   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
   1465   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
   1466       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
   1467       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
   1468     diagnostic = diag::err_undeclared_use;
   1469     diagnostic_suggest = diag::err_undeclared_use_suggest;
   1470   }
   1471 
   1472   // If the original lookup was an unqualified lookup, fake an
   1473   // unqualified lookup.  This is useful when (for example) the
   1474   // original lookup would not have found something because it was a
   1475   // dependent name.
   1476   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
   1477     ? CurContext : 0;
   1478   while (DC) {
   1479     if (isa<CXXRecordDecl>(DC)) {
   1480       LookupQualifiedName(R, DC);
   1481 
   1482       if (!R.empty()) {
   1483         // Don't give errors about ambiguities in this lookup.
   1484         R.suppressDiagnostics();
   1485 
   1486         // During a default argument instantiation the CurContext points
   1487         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
   1488         // function parameter list, hence add an explicit check.
   1489         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
   1490                               ActiveTemplateInstantiations.back().Kind ==
   1491             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
   1492         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
   1493         bool isInstance = CurMethod &&
   1494                           CurMethod->isInstance() &&
   1495                           DC == CurMethod->getParent() && !isDefaultArgument;
   1496 
   1497 
   1498         // Give a code modification hint to insert 'this->'.
   1499         // TODO: fixit for inserting 'Base<T>::' in the other cases.
   1500         // Actually quite difficult!
   1501         if (getLangOpts().MicrosoftMode)
   1502           diagnostic = diag::warn_found_via_dependent_bases_lookup;
   1503         if (isInstance) {
   1504           Diag(R.getNameLoc(), diagnostic) << Name
   1505             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
   1506           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
   1507               CallsUndergoingInstantiation.back()->getCallee());
   1508 
   1509 
   1510           CXXMethodDecl *DepMethod;
   1511           if (CurMethod->getTemplatedKind() ==
   1512               FunctionDecl::TK_FunctionTemplateSpecialization)
   1513             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
   1514                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
   1515           else
   1516             DepMethod = cast<CXXMethodDecl>(
   1517                 CurMethod->getInstantiatedFromMemberFunction());
   1518           assert(DepMethod && "No template pattern found");
   1519 
   1520           QualType DepThisType = DepMethod->getThisType(Context);
   1521           CheckCXXThisCapture(R.getNameLoc());
   1522           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
   1523                                      R.getNameLoc(), DepThisType, false);
   1524           TemplateArgumentListInfo TList;
   1525           if (ULE->hasExplicitTemplateArgs())
   1526             ULE->copyTemplateArgumentsInto(TList);
   1527 
   1528           CXXScopeSpec SS;
   1529           SS.Adopt(ULE->getQualifierLoc());
   1530           CXXDependentScopeMemberExpr *DepExpr =
   1531               CXXDependentScopeMemberExpr::Create(
   1532                   Context, DepThis, DepThisType, true, SourceLocation(),
   1533                   SS.getWithLocInContext(Context),
   1534                   ULE->getTemplateKeywordLoc(), 0,
   1535                   R.getLookupNameInfo(),
   1536                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
   1537           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
   1538         } else {
   1539           Diag(R.getNameLoc(), diagnostic) << Name;
   1540         }
   1541 
   1542         // Do we really want to note all of these?
   1543         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
   1544           Diag((*I)->getLocation(), diag::note_dependent_var_use);
   1545 
   1546         // Return true if we are inside a default argument instantiation
   1547         // and the found name refers to an instance member function, otherwise
   1548         // the function calling DiagnoseEmptyLookup will try to create an
   1549         // implicit member call and this is wrong for default argument.
   1550         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
   1551           Diag(R.getNameLoc(), diag::err_member_call_without_object);
   1552           return true;
   1553         }
   1554 
   1555         // Tell the callee to try to recover.
   1556         return false;
   1557       }
   1558 
   1559       R.clear();
   1560     }
   1561 
   1562     // In Microsoft mode, if we are performing lookup from within a friend
   1563     // function definition declared at class scope then we must set
   1564     // DC to the lexical parent to be able to search into the parent
   1565     // class.
   1566     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
   1567         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
   1568         DC->getLexicalParent()->isRecord())
   1569       DC = DC->getLexicalParent();
   1570     else
   1571       DC = DC->getParent();
   1572   }
   1573 
   1574   // We didn't find anything, so try to correct for a typo.
   1575   TypoCorrection Corrected;
   1576   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
   1577                                     S, &SS, CCC))) {
   1578     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
   1579     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
   1580     R.setLookupName(Corrected.getCorrection());
   1581 
   1582     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
   1583       if (Corrected.isOverloaded()) {
   1584         OverloadCandidateSet OCS(R.getNameLoc());
   1585         OverloadCandidateSet::iterator Best;
   1586         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
   1587                                         CDEnd = Corrected.end();
   1588              CD != CDEnd; ++CD) {
   1589           if (FunctionTemplateDecl *FTD =
   1590                    dyn_cast<FunctionTemplateDecl>(*CD))
   1591             AddTemplateOverloadCandidate(
   1592                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
   1593                 Args, OCS);
   1594           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
   1595             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
   1596               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
   1597                                    Args, OCS);
   1598         }
   1599         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
   1600           case OR_Success:
   1601             ND = Best->Function;
   1602             break;
   1603           default:
   1604             break;
   1605         }
   1606       }
   1607       R.addDecl(ND);
   1608       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
   1609         if (SS.isEmpty())
   1610           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
   1611             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
   1612         else
   1613           Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1614             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1615             << SS.getRange()
   1616             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
   1617         if (ND)
   1618           Diag(ND->getLocation(), diag::note_previous_decl)
   1619             << CorrectedQuotedStr;
   1620 
   1621         // Tell the callee to try to recover.
   1622         return false;
   1623       }
   1624 
   1625       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
   1626         // FIXME: If we ended up with a typo for a type name or
   1627         // Objective-C class name, we're in trouble because the parser
   1628         // is in the wrong place to recover. Suggest the typo
   1629         // correction, but don't make it a fix-it since we're not going
   1630         // to recover well anyway.
   1631         if (SS.isEmpty())
   1632           Diag(R.getNameLoc(), diagnostic_suggest)
   1633             << Name << CorrectedQuotedStr;
   1634         else
   1635           Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1636             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1637             << SS.getRange();
   1638 
   1639         // Don't try to recover; it won't work.
   1640         return true;
   1641       }
   1642     } else {
   1643       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
   1644       // because we aren't able to recover.
   1645       if (SS.isEmpty())
   1646         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
   1647       else
   1648         Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1649         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1650         << SS.getRange();
   1651       return true;
   1652     }
   1653   }
   1654   R.clear();
   1655 
   1656   // Emit a special diagnostic for failed member lookups.
   1657   // FIXME: computing the declaration context might fail here (?)
   1658   if (!SS.isEmpty()) {
   1659     Diag(R.getNameLoc(), diag::err_no_member)
   1660       << Name << computeDeclContext(SS, false)
   1661       << SS.getRange();
   1662     return true;
   1663   }
   1664 
   1665   // Give up, we can't recover.
   1666   Diag(R.getNameLoc(), diagnostic) << Name;
   1667   return true;
   1668 }
   1669 
   1670 ExprResult Sema::ActOnIdExpression(Scope *S,
   1671                                    CXXScopeSpec &SS,
   1672                                    SourceLocation TemplateKWLoc,
   1673                                    UnqualifiedId &Id,
   1674                                    bool HasTrailingLParen,
   1675                                    bool IsAddressOfOperand,
   1676                                    CorrectionCandidateCallback *CCC) {
   1677   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
   1678          "cannot be direct & operand and have a trailing lparen");
   1679 
   1680   if (SS.isInvalid())
   1681     return ExprError();
   1682 
   1683   TemplateArgumentListInfo TemplateArgsBuffer;
   1684 
   1685   // Decompose the UnqualifiedId into the following data.
   1686   DeclarationNameInfo NameInfo;
   1687   const TemplateArgumentListInfo *TemplateArgs;
   1688   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
   1689 
   1690   DeclarationName Name = NameInfo.getName();
   1691   IdentifierInfo *II = Name.getAsIdentifierInfo();
   1692   SourceLocation NameLoc = NameInfo.getLoc();
   1693 
   1694   // C++ [temp.dep.expr]p3:
   1695   //   An id-expression is type-dependent if it contains:
   1696   //     -- an identifier that was declared with a dependent type,
   1697   //        (note: handled after lookup)
   1698   //     -- a template-id that is dependent,
   1699   //        (note: handled in BuildTemplateIdExpr)
   1700   //     -- a conversion-function-id that specifies a dependent type,
   1701   //     -- a nested-name-specifier that contains a class-name that
   1702   //        names a dependent type.
   1703   // Determine whether this is a member of an unknown specialization;
   1704   // we need to handle these differently.
   1705   bool DependentID = false;
   1706   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
   1707       Name.getCXXNameType()->isDependentType()) {
   1708     DependentID = true;
   1709   } else if (SS.isSet()) {
   1710     if (DeclContext *DC = computeDeclContext(SS, false)) {
   1711       if (RequireCompleteDeclContext(SS, DC))
   1712         return ExprError();
   1713     } else {
   1714       DependentID = true;
   1715     }
   1716   }
   1717 
   1718   if (DependentID)
   1719     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1720                                       IsAddressOfOperand, TemplateArgs);
   1721 
   1722   // Perform the required lookup.
   1723   LookupResult R(*this, NameInfo,
   1724                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
   1725                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
   1726   if (TemplateArgs) {
   1727     // Lookup the template name again to correctly establish the context in
   1728     // which it was found. This is really unfortunate as we already did the
   1729     // lookup to determine that it was a template name in the first place. If
   1730     // this becomes a performance hit, we can work harder to preserve those
   1731     // results until we get here but it's likely not worth it.
   1732     bool MemberOfUnknownSpecialization;
   1733     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
   1734                        MemberOfUnknownSpecialization);
   1735 
   1736     if (MemberOfUnknownSpecialization ||
   1737         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
   1738       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1739                                         IsAddressOfOperand, TemplateArgs);
   1740   } else {
   1741     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
   1742     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
   1743 
   1744     // If the result might be in a dependent base class, this is a dependent
   1745     // id-expression.
   1746     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
   1747       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1748                                         IsAddressOfOperand, TemplateArgs);
   1749 
   1750     // If this reference is in an Objective-C method, then we need to do
   1751     // some special Objective-C lookup, too.
   1752     if (IvarLookupFollowUp) {
   1753       ExprResult E(LookupInObjCMethod(R, S, II, true));
   1754       if (E.isInvalid())
   1755         return ExprError();
   1756 
   1757       if (Expr *Ex = E.takeAs<Expr>())
   1758         return Owned(Ex);
   1759     }
   1760   }
   1761 
   1762   if (R.isAmbiguous())
   1763     return ExprError();
   1764 
   1765   // Determine whether this name might be a candidate for
   1766   // argument-dependent lookup.
   1767   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
   1768 
   1769   if (R.empty() && !ADL) {
   1770     // Otherwise, this could be an implicitly declared function reference (legal
   1771     // in C90, extension in C99, forbidden in C++).
   1772     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
   1773       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
   1774       if (D) R.addDecl(D);
   1775     }
   1776 
   1777     // If this name wasn't predeclared and if this is not a function
   1778     // call, diagnose the problem.
   1779     if (R.empty()) {
   1780 
   1781       // In Microsoft mode, if we are inside a template class member function
   1782       // and we can't resolve an identifier then assume the identifier is type
   1783       // dependent. The goal is to postpone name lookup to instantiation time
   1784       // to be able to search into type dependent base classes.
   1785       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
   1786           isa<CXXMethodDecl>(CurContext))
   1787         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1788                                           IsAddressOfOperand, TemplateArgs);
   1789 
   1790       CorrectionCandidateCallback DefaultValidator;
   1791       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
   1792         return ExprError();
   1793 
   1794       assert(!R.empty() &&
   1795              "DiagnoseEmptyLookup returned false but added no results");
   1796 
   1797       // If we found an Objective-C instance variable, let
   1798       // LookupInObjCMethod build the appropriate expression to
   1799       // reference the ivar.
   1800       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
   1801         R.clear();
   1802         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
   1803         // In a hopelessly buggy code, Objective-C instance variable
   1804         // lookup fails and no expression will be built to reference it.
   1805         if (!E.isInvalid() && !E.get())
   1806           return ExprError();
   1807         return E;
   1808       }
   1809     }
   1810   }
   1811 
   1812   // This is guaranteed from this point on.
   1813   assert(!R.empty() || ADL);
   1814 
   1815   // Check whether this might be a C++ implicit instance member access.
   1816   // C++ [class.mfct.non-static]p3:
   1817   //   When an id-expression that is not part of a class member access
   1818   //   syntax and not used to form a pointer to member is used in the
   1819   //   body of a non-static member function of class X, if name lookup
   1820   //   resolves the name in the id-expression to a non-static non-type
   1821   //   member of some class C, the id-expression is transformed into a
   1822   //   class member access expression using (*this) as the
   1823   //   postfix-expression to the left of the . operator.
   1824   //
   1825   // But we don't actually need to do this for '&' operands if R
   1826   // resolved to a function or overloaded function set, because the
   1827   // expression is ill-formed if it actually works out to be a
   1828   // non-static member function:
   1829   //
   1830   // C++ [expr.ref]p4:
   1831   //   Otherwise, if E1.E2 refers to a non-static member function. . .
   1832   //   [t]he expression can be used only as the left-hand operand of a
   1833   //   member function call.
   1834   //
   1835   // There are other safeguards against such uses, but it's important
   1836   // to get this right here so that we don't end up making a
   1837   // spuriously dependent expression if we're inside a dependent
   1838   // instance method.
   1839   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
   1840     bool MightBeImplicitMember;
   1841     if (!IsAddressOfOperand)
   1842       MightBeImplicitMember = true;
   1843     else if (!SS.isEmpty())
   1844       MightBeImplicitMember = false;
   1845     else if (R.isOverloadedResult())
   1846       MightBeImplicitMember = false;
   1847     else if (R.isUnresolvableResult())
   1848       MightBeImplicitMember = true;
   1849     else
   1850       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
   1851                               isa<IndirectFieldDecl>(R.getFoundDecl());
   1852 
   1853     if (MightBeImplicitMember)
   1854       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
   1855                                              R, TemplateArgs);
   1856   }
   1857 
   1858   if (TemplateArgs || TemplateKWLoc.isValid())
   1859     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
   1860 
   1861   return BuildDeclarationNameExpr(SS, R, ADL);
   1862 }
   1863 
   1864 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
   1865 /// declaration name, generally during template instantiation.
   1866 /// There's a large number of things which don't need to be done along
   1867 /// this path.
   1868 ExprResult
   1869 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
   1870                                         const DeclarationNameInfo &NameInfo) {
   1871   DeclContext *DC;
   1872   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
   1873     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
   1874                                      NameInfo, /*TemplateArgs=*/0);
   1875 
   1876   if (RequireCompleteDeclContext(SS, DC))
   1877     return ExprError();
   1878 
   1879   LookupResult R(*this, NameInfo, LookupOrdinaryName);
   1880   LookupQualifiedName(R, DC);
   1881 
   1882   if (R.isAmbiguous())
   1883     return ExprError();
   1884 
   1885   if (R.empty()) {
   1886     Diag(NameInfo.getLoc(), diag::err_no_member)
   1887       << NameInfo.getName() << DC << SS.getRange();
   1888     return ExprError();
   1889   }
   1890 
   1891   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
   1892 }
   1893 
   1894 /// LookupInObjCMethod - The parser has read a name in, and Sema has
   1895 /// detected that we're currently inside an ObjC method.  Perform some
   1896 /// additional lookup.
   1897 ///
   1898 /// Ideally, most of this would be done by lookup, but there's
   1899 /// actually quite a lot of extra work involved.
   1900 ///
   1901 /// Returns a null sentinel to indicate trivial success.
   1902 ExprResult
   1903 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
   1904                          IdentifierInfo *II, bool AllowBuiltinCreation) {
   1905   SourceLocation Loc = Lookup.getNameLoc();
   1906   ObjCMethodDecl *CurMethod = getCurMethodDecl();
   1907 
   1908   // There are two cases to handle here.  1) scoped lookup could have failed,
   1909   // in which case we should look for an ivar.  2) scoped lookup could have
   1910   // found a decl, but that decl is outside the current instance method (i.e.
   1911   // a global variable).  In these two cases, we do a lookup for an ivar with
   1912   // this name, if the lookup sucedes, we replace it our current decl.
   1913 
   1914   // If we're in a class method, we don't normally want to look for
   1915   // ivars.  But if we don't find anything else, and there's an
   1916   // ivar, that's an error.
   1917   bool IsClassMethod = CurMethod->isClassMethod();
   1918 
   1919   bool LookForIvars;
   1920   if (Lookup.empty())
   1921     LookForIvars = true;
   1922   else if (IsClassMethod)
   1923     LookForIvars = false;
   1924   else
   1925     LookForIvars = (Lookup.isSingleResult() &&
   1926                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
   1927   ObjCInterfaceDecl *IFace = 0;
   1928   if (LookForIvars) {
   1929     IFace = CurMethod->getClassInterface();
   1930     ObjCInterfaceDecl *ClassDeclared;
   1931     ObjCIvarDecl *IV = 0;
   1932     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
   1933       // Diagnose using an ivar in a class method.
   1934       if (IsClassMethod)
   1935         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   1936                          << IV->getDeclName());
   1937 
   1938       // If we're referencing an invalid decl, just return this as a silent
   1939       // error node.  The error diagnostic was already emitted on the decl.
   1940       if (IV->isInvalidDecl())
   1941         return ExprError();
   1942 
   1943       // Check if referencing a field with __attribute__((deprecated)).
   1944       if (DiagnoseUseOfDecl(IV, Loc))
   1945         return ExprError();
   1946 
   1947       // Diagnose the use of an ivar outside of the declaring class.
   1948       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
   1949           !declaresSameEntity(ClassDeclared, IFace) &&
   1950           !getLangOpts().DebuggerSupport)
   1951         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
   1952 
   1953       // FIXME: This should use a new expr for a direct reference, don't
   1954       // turn this into Self->ivar, just return a BareIVarExpr or something.
   1955       IdentifierInfo &II = Context.Idents.get("self");
   1956       UnqualifiedId SelfName;
   1957       SelfName.setIdentifier(&II, SourceLocation());
   1958       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
   1959       CXXScopeSpec SelfScopeSpec;
   1960       SourceLocation TemplateKWLoc;
   1961       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
   1962                                               SelfName, false, false);
   1963       if (SelfExpr.isInvalid())
   1964         return ExprError();
   1965 
   1966       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
   1967       if (SelfExpr.isInvalid())
   1968         return ExprError();
   1969 
   1970       MarkAnyDeclReferenced(Loc, IV);
   1971 
   1972       ObjCMethodFamily MF = CurMethod->getMethodFamily();
   1973       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
   1974         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
   1975       return Owned(new (Context)
   1976                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
   1977                                    SelfExpr.take(), true, true));
   1978     }
   1979   } else if (CurMethod->isInstanceMethod()) {
   1980     // We should warn if a local variable hides an ivar.
   1981     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
   1982       ObjCInterfaceDecl *ClassDeclared;
   1983       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
   1984         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
   1985             declaresSameEntity(IFace, ClassDeclared))
   1986           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
   1987       }
   1988     }
   1989   } else if (Lookup.isSingleResult() &&
   1990              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
   1991     // If accessing a stand-alone ivar in a class method, this is an error.
   1992     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
   1993       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   1994                        << IV->getDeclName());
   1995   }
   1996 
   1997   if (Lookup.empty() && II && AllowBuiltinCreation) {
   1998     // FIXME. Consolidate this with similar code in LookupName.
   1999     if (unsigned BuiltinID = II->getBuiltinID()) {
   2000       if (!(getLangOpts().CPlusPlus &&
   2001             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
   2002         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
   2003                                            S, Lookup.isForRedeclaration(),
   2004                                            Lookup.getNameLoc());
   2005         if (D) Lookup.addDecl(D);
   2006       }
   2007     }
   2008   }
   2009   // Sentinel value saying that we didn't do anything special.
   2010   return Owned((Expr*) 0);
   2011 }
   2012 
   2013 /// \brief Cast a base object to a member's actual type.
   2014 ///
   2015 /// Logically this happens in three phases:
   2016 ///
   2017 /// * First we cast from the base type to the naming class.
   2018 ///   The naming class is the class into which we were looking
   2019 ///   when we found the member;  it's the qualifier type if a
   2020 ///   qualifier was provided, and otherwise it's the base type.
   2021 ///
   2022 /// * Next we cast from the naming class to the declaring class.
   2023 ///   If the member we found was brought into a class's scope by
   2024 ///   a using declaration, this is that class;  otherwise it's
   2025 ///   the class declaring the member.
   2026 ///
   2027 /// * Finally we cast from the declaring class to the "true"
   2028 ///   declaring class of the member.  This conversion does not
   2029 ///   obey access control.
   2030 ExprResult
   2031 Sema::PerformObjectMemberConversion(Expr *From,
   2032                                     NestedNameSpecifier *Qualifier,
   2033                                     NamedDecl *FoundDecl,
   2034                                     NamedDecl *Member) {
   2035   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
   2036   if (!RD)
   2037     return Owned(From);
   2038 
   2039   QualType DestRecordType;
   2040   QualType DestType;
   2041   QualType FromRecordType;
   2042   QualType FromType = From->getType();
   2043   bool PointerConversions = false;
   2044   if (isa<FieldDecl>(Member)) {
   2045     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
   2046 
   2047     if (FromType->getAs<PointerType>()) {
   2048       DestType = Context.getPointerType(DestRecordType);
   2049       FromRecordType = FromType->getPointeeType();
   2050       PointerConversions = true;
   2051     } else {
   2052       DestType = DestRecordType;
   2053       FromRecordType = FromType;
   2054     }
   2055   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
   2056     if (Method->isStatic())
   2057       return Owned(From);
   2058 
   2059     DestType = Method->getThisType(Context);
   2060     DestRecordType = DestType->getPointeeType();
   2061 
   2062     if (FromType->getAs<PointerType>()) {
   2063       FromRecordType = FromType->getPointeeType();
   2064       PointerConversions = true;
   2065     } else {
   2066       FromRecordType = FromType;
   2067       DestType = DestRecordType;
   2068     }
   2069   } else {
   2070     // No conversion necessary.
   2071     return Owned(From);
   2072   }
   2073 
   2074   if (DestType->isDependentType() || FromType->isDependentType())
   2075     return Owned(From);
   2076 
   2077   // If the unqualified types are the same, no conversion is necessary.
   2078   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2079     return Owned(From);
   2080 
   2081   SourceRange FromRange = From->getSourceRange();
   2082   SourceLocation FromLoc = FromRange.getBegin();
   2083 
   2084   ExprValueKind VK = From->getValueKind();
   2085 
   2086   // C++ [class.member.lookup]p8:
   2087   //   [...] Ambiguities can often be resolved by qualifying a name with its
   2088   //   class name.
   2089   //
   2090   // If the member was a qualified name and the qualified referred to a
   2091   // specific base subobject type, we'll cast to that intermediate type
   2092   // first and then to the object in which the member is declared. That allows
   2093   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
   2094   //
   2095   //   class Base { public: int x; };
   2096   //   class Derived1 : public Base { };
   2097   //   class Derived2 : public Base { };
   2098   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
   2099   //
   2100   //   void VeryDerived::f() {
   2101   //     x = 17; // error: ambiguous base subobjects
   2102   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
   2103   //   }
   2104   if (Qualifier) {
   2105     QualType QType = QualType(Qualifier->getAsType(), 0);
   2106     assert(!QType.isNull() && "lookup done with dependent qualifier?");
   2107     assert(QType->isRecordType() && "lookup done with non-record type");
   2108 
   2109     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
   2110 
   2111     // In C++98, the qualifier type doesn't actually have to be a base
   2112     // type of the object type, in which case we just ignore it.
   2113     // Otherwise build the appropriate casts.
   2114     if (IsDerivedFrom(FromRecordType, QRecordType)) {
   2115       CXXCastPath BasePath;
   2116       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
   2117                                        FromLoc, FromRange, &BasePath))
   2118         return ExprError();
   2119 
   2120       if (PointerConversions)
   2121         QType = Context.getPointerType(QType);
   2122       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
   2123                                VK, &BasePath).take();
   2124 
   2125       FromType = QType;
   2126       FromRecordType = QRecordType;
   2127 
   2128       // If the qualifier type was the same as the destination type,
   2129       // we're done.
   2130       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2131         return Owned(From);
   2132     }
   2133   }
   2134 
   2135   bool IgnoreAccess = false;
   2136 
   2137   // If we actually found the member through a using declaration, cast
   2138   // down to the using declaration's type.
   2139   //
   2140   // Pointer equality is fine here because only one declaration of a
   2141   // class ever has member declarations.
   2142   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
   2143     assert(isa<UsingShadowDecl>(FoundDecl));
   2144     QualType URecordType = Context.getTypeDeclType(
   2145                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
   2146 
   2147     // We only need to do this if the naming-class to declaring-class
   2148     // conversion is non-trivial.
   2149     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
   2150       assert(IsDerivedFrom(FromRecordType, URecordType));
   2151       CXXCastPath BasePath;
   2152       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
   2153                                        FromLoc, FromRange, &BasePath))
   2154         return ExprError();
   2155 
   2156       QualType UType = URecordType;
   2157       if (PointerConversions)
   2158         UType = Context.getPointerType(UType);
   2159       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
   2160                                VK, &BasePath).take();
   2161       FromType = UType;
   2162       FromRecordType = URecordType;
   2163     }
   2164 
   2165     // We don't do access control for the conversion from the
   2166     // declaring class to the true declaring class.
   2167     IgnoreAccess = true;
   2168   }
   2169 
   2170   CXXCastPath BasePath;
   2171   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
   2172                                    FromLoc, FromRange, &BasePath,
   2173                                    IgnoreAccess))
   2174     return ExprError();
   2175 
   2176   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
   2177                            VK, &BasePath);
   2178 }
   2179 
   2180 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
   2181                                       const LookupResult &R,
   2182                                       bool HasTrailingLParen) {
   2183   // Only when used directly as the postfix-expression of a call.
   2184   if (!HasTrailingLParen)
   2185     return false;
   2186 
   2187   // Never if a scope specifier was provided.
   2188   if (SS.isSet())
   2189     return false;
   2190 
   2191   // Only in C++ or ObjC++.
   2192   if (!getLangOpts().CPlusPlus)
   2193     return false;
   2194 
   2195   // Turn off ADL when we find certain kinds of declarations during
   2196   // normal lookup:
   2197   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   2198     NamedDecl *D = *I;
   2199 
   2200     // C++0x [basic.lookup.argdep]p3:
   2201     //     -- a declaration of a class member
   2202     // Since using decls preserve this property, we check this on the
   2203     // original decl.
   2204     if (D->isCXXClassMember())
   2205       return false;
   2206 
   2207     // C++0x [basic.lookup.argdep]p3:
   2208     //     -- a block-scope function declaration that is not a
   2209     //        using-declaration
   2210     // NOTE: we also trigger this for function templates (in fact, we
   2211     // don't check the decl type at all, since all other decl types
   2212     // turn off ADL anyway).
   2213     if (isa<UsingShadowDecl>(D))
   2214       D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2215     else if (D->getDeclContext()->isFunctionOrMethod())
   2216       return false;
   2217 
   2218     // C++0x [basic.lookup.argdep]p3:
   2219     //     -- a declaration that is neither a function or a function
   2220     //        template
   2221     // And also for builtin functions.
   2222     if (isa<FunctionDecl>(D)) {
   2223       FunctionDecl *FDecl = cast<FunctionDecl>(D);
   2224 
   2225       // But also builtin functions.
   2226       if (FDecl->getBuiltinID() && FDecl->isImplicit())
   2227         return false;
   2228     } else if (!isa<FunctionTemplateDecl>(D))
   2229       return false;
   2230   }
   2231 
   2232   return true;
   2233 }
   2234 
   2235 
   2236 /// Diagnoses obvious problems with the use of the given declaration
   2237 /// as an expression.  This is only actually called for lookups that
   2238 /// were not overloaded, and it doesn't promise that the declaration
   2239 /// will in fact be used.
   2240 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
   2241   if (isa<TypedefNameDecl>(D)) {
   2242     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
   2243     return true;
   2244   }
   2245 
   2246   if (isa<ObjCInterfaceDecl>(D)) {
   2247     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
   2248     return true;
   2249   }
   2250 
   2251   if (isa<NamespaceDecl>(D)) {
   2252     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
   2253     return true;
   2254   }
   2255 
   2256   return false;
   2257 }
   2258 
   2259 ExprResult
   2260 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2261                                LookupResult &R,
   2262                                bool NeedsADL) {
   2263   // If this is a single, fully-resolved result and we don't need ADL,
   2264   // just build an ordinary singleton decl ref.
   2265   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
   2266     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
   2267                                     R.getFoundDecl());
   2268 
   2269   // We only need to check the declaration if there's exactly one
   2270   // result, because in the overloaded case the results can only be
   2271   // functions and function templates.
   2272   if (R.isSingleResult() &&
   2273       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
   2274     return ExprError();
   2275 
   2276   // Otherwise, just build an unresolved lookup expression.  Suppress
   2277   // any lookup-related diagnostics; we'll hash these out later, when
   2278   // we've picked a target.
   2279   R.suppressDiagnostics();
   2280 
   2281   UnresolvedLookupExpr *ULE
   2282     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
   2283                                    SS.getWithLocInContext(Context),
   2284                                    R.getLookupNameInfo(),
   2285                                    NeedsADL, R.isOverloadedResult(),
   2286                                    R.begin(), R.end());
   2287 
   2288   return Owned(ULE);
   2289 }
   2290 
   2291 /// \brief Complete semantic analysis for a reference to the given declaration.
   2292 ExprResult
   2293 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2294                                const DeclarationNameInfo &NameInfo,
   2295                                NamedDecl *D) {
   2296   assert(D && "Cannot refer to a NULL declaration");
   2297   assert(!isa<FunctionTemplateDecl>(D) &&
   2298          "Cannot refer unambiguously to a function template");
   2299 
   2300   SourceLocation Loc = NameInfo.getLoc();
   2301   if (CheckDeclInExpr(*this, Loc, D))
   2302     return ExprError();
   2303 
   2304   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
   2305     // Specifically diagnose references to class templates that are missing
   2306     // a template argument list.
   2307     Diag(Loc, diag::err_template_decl_ref)
   2308       << Template << SS.getRange();
   2309     Diag(Template->getLocation(), diag::note_template_decl_here);
   2310     return ExprError();
   2311   }
   2312 
   2313   // Make sure that we're referring to a value.
   2314   ValueDecl *VD = dyn_cast<ValueDecl>(D);
   2315   if (!VD) {
   2316     Diag(Loc, diag::err_ref_non_value)
   2317       << D << SS.getRange();
   2318     Diag(D->getLocation(), diag::note_declared_at);
   2319     return ExprError();
   2320   }
   2321 
   2322   // Check whether this declaration can be used. Note that we suppress
   2323   // this check when we're going to perform argument-dependent lookup
   2324   // on this function name, because this might not be the function
   2325   // that overload resolution actually selects.
   2326   if (DiagnoseUseOfDecl(VD, Loc))
   2327     return ExprError();
   2328 
   2329   // Only create DeclRefExpr's for valid Decl's.
   2330   if (VD->isInvalidDecl())
   2331     return ExprError();
   2332 
   2333   // Handle members of anonymous structs and unions.  If we got here,
   2334   // and the reference is to a class member indirect field, then this
   2335   // must be the subject of a pointer-to-member expression.
   2336   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
   2337     if (!indirectField->isCXXClassMember())
   2338       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
   2339                                                       indirectField);
   2340 
   2341   {
   2342     QualType type = VD->getType();
   2343     ExprValueKind valueKind = VK_RValue;
   2344 
   2345     switch (D->getKind()) {
   2346     // Ignore all the non-ValueDecl kinds.
   2347 #define ABSTRACT_DECL(kind)
   2348 #define VALUE(type, base)
   2349 #define DECL(type, base) \
   2350     case Decl::type:
   2351 #include "clang/AST/DeclNodes.inc"
   2352       llvm_unreachable("invalid value decl kind");
   2353 
   2354     // These shouldn't make it here.
   2355     case Decl::ObjCAtDefsField:
   2356     case Decl::ObjCIvar:
   2357       llvm_unreachable("forming non-member reference to ivar?");
   2358 
   2359     // Enum constants are always r-values and never references.
   2360     // Unresolved using declarations are dependent.
   2361     case Decl::EnumConstant:
   2362     case Decl::UnresolvedUsingValue:
   2363       valueKind = VK_RValue;
   2364       break;
   2365 
   2366     // Fields and indirect fields that got here must be for
   2367     // pointer-to-member expressions; we just call them l-values for
   2368     // internal consistency, because this subexpression doesn't really
   2369     // exist in the high-level semantics.
   2370     case Decl::Field:
   2371     case Decl::IndirectField:
   2372       assert(getLangOpts().CPlusPlus &&
   2373              "building reference to field in C?");
   2374 
   2375       // These can't have reference type in well-formed programs, but
   2376       // for internal consistency we do this anyway.
   2377       type = type.getNonReferenceType();
   2378       valueKind = VK_LValue;
   2379       break;
   2380 
   2381     // Non-type template parameters are either l-values or r-values
   2382     // depending on the type.
   2383     case Decl::NonTypeTemplateParm: {
   2384       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
   2385         type = reftype->getPointeeType();
   2386         valueKind = VK_LValue; // even if the parameter is an r-value reference
   2387         break;
   2388       }
   2389 
   2390       // For non-references, we need to strip qualifiers just in case
   2391       // the template parameter was declared as 'const int' or whatever.
   2392       valueKind = VK_RValue;
   2393       type = type.getUnqualifiedType();
   2394       break;
   2395     }
   2396 
   2397     case Decl::Var:
   2398       // In C, "extern void blah;" is valid and is an r-value.
   2399       if (!getLangOpts().CPlusPlus &&
   2400           !type.hasQualifiers() &&
   2401           type->isVoidType()) {
   2402         valueKind = VK_RValue;
   2403         break;
   2404       }
   2405       // fallthrough
   2406 
   2407     case Decl::ImplicitParam:
   2408     case Decl::ParmVar: {
   2409       // These are always l-values.
   2410       valueKind = VK_LValue;
   2411       type = type.getNonReferenceType();
   2412 
   2413       // FIXME: Does the addition of const really only apply in
   2414       // potentially-evaluated contexts? Since the variable isn't actually
   2415       // captured in an unevaluated context, it seems that the answer is no.
   2416       if (!isUnevaluatedContext()) {
   2417         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
   2418         if (!CapturedType.isNull())
   2419           type = CapturedType;
   2420       }
   2421 
   2422       break;
   2423     }
   2424 
   2425     case Decl::Function: {
   2426       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
   2427         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
   2428           type = Context.BuiltinFnTy;
   2429           valueKind = VK_RValue;
   2430           break;
   2431         }
   2432       }
   2433 
   2434       const FunctionType *fty = type->castAs<FunctionType>();
   2435 
   2436       // If we're referring to a function with an __unknown_anytype
   2437       // result type, make the entire expression __unknown_anytype.
   2438       if (fty->getResultType() == Context.UnknownAnyTy) {
   2439         type = Context.UnknownAnyTy;
   2440         valueKind = VK_RValue;
   2441         break;
   2442       }
   2443 
   2444       // Functions are l-values in C++.
   2445       if (getLangOpts().CPlusPlus) {
   2446         valueKind = VK_LValue;
   2447         break;
   2448       }
   2449 
   2450       // C99 DR 316 says that, if a function type comes from a
   2451       // function definition (without a prototype), that type is only
   2452       // used for checking compatibility. Therefore, when referencing
   2453       // the function, we pretend that we don't have the full function
   2454       // type.
   2455       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
   2456           isa<FunctionProtoType>(fty))
   2457         type = Context.getFunctionNoProtoType(fty->getResultType(),
   2458                                               fty->getExtInfo());
   2459 
   2460       // Functions are r-values in C.
   2461       valueKind = VK_RValue;
   2462       break;
   2463     }
   2464 
   2465     case Decl::CXXMethod:
   2466       // If we're referring to a method with an __unknown_anytype
   2467       // result type, make the entire expression __unknown_anytype.
   2468       // This should only be possible with a type written directly.
   2469       if (const FunctionProtoType *proto
   2470             = dyn_cast<FunctionProtoType>(VD->getType()))
   2471         if (proto->getResultType() == Context.UnknownAnyTy) {
   2472           type = Context.UnknownAnyTy;
   2473           valueKind = VK_RValue;
   2474           break;
   2475         }
   2476 
   2477       // C++ methods are l-values if static, r-values if non-static.
   2478       if (cast<CXXMethodDecl>(VD)->isStatic()) {
   2479         valueKind = VK_LValue;
   2480         break;
   2481       }
   2482       // fallthrough
   2483 
   2484     case Decl::CXXConversion:
   2485     case Decl::CXXDestructor:
   2486     case Decl::CXXConstructor:
   2487       valueKind = VK_RValue;
   2488       break;
   2489     }
   2490 
   2491     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
   2492   }
   2493 }
   2494 
   2495 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
   2496   PredefinedExpr::IdentType IT;
   2497 
   2498   switch (Kind) {
   2499   default: llvm_unreachable("Unknown simple primary expr!");
   2500   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
   2501   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
   2502   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
   2503   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
   2504   }
   2505 
   2506   // Pre-defined identifiers are of type char[x], where x is the length of the
   2507   // string.
   2508 
   2509   Decl *currentDecl = getCurFunctionOrMethodDecl();
   2510   if (!currentDecl && getCurBlock())
   2511     currentDecl = getCurBlock()->TheDecl;
   2512   if (!currentDecl) {
   2513     Diag(Loc, diag::ext_predef_outside_function);
   2514     currentDecl = Context.getTranslationUnitDecl();
   2515   }
   2516 
   2517   QualType ResTy;
   2518   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
   2519     ResTy = Context.DependentTy;
   2520   } else {
   2521     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
   2522 
   2523     llvm::APInt LengthI(32, Length + 1);
   2524     if (IT == PredefinedExpr::LFunction)
   2525       ResTy = Context.WCharTy.withConst();
   2526     else
   2527       ResTy = Context.CharTy.withConst();
   2528     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
   2529   }
   2530   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
   2531 }
   2532 
   2533 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
   2534   SmallString<16> CharBuffer;
   2535   bool Invalid = false;
   2536   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
   2537   if (Invalid)
   2538     return ExprError();
   2539 
   2540   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
   2541                             PP, Tok.getKind());
   2542   if (Literal.hadError())
   2543     return ExprError();
   2544 
   2545   QualType Ty;
   2546   if (Literal.isWide())
   2547     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
   2548   else if (Literal.isUTF16())
   2549     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
   2550   else if (Literal.isUTF32())
   2551     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
   2552   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
   2553     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
   2554   else
   2555     Ty = Context.CharTy;  // 'x' -> char in C++
   2556 
   2557   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
   2558   if (Literal.isWide())
   2559     Kind = CharacterLiteral::Wide;
   2560   else if (Literal.isUTF16())
   2561     Kind = CharacterLiteral::UTF16;
   2562   else if (Literal.isUTF32())
   2563     Kind = CharacterLiteral::UTF32;
   2564 
   2565   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
   2566                                              Tok.getLocation());
   2567 
   2568   if (Literal.getUDSuffix().empty())
   2569     return Owned(Lit);
   2570 
   2571   // We're building a user-defined literal.
   2572   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   2573   SourceLocation UDSuffixLoc =
   2574     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   2575 
   2576   // Make sure we're allowed user-defined literals here.
   2577   if (!UDLScope)
   2578     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
   2579 
   2580   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
   2581   //   operator "" X (ch)
   2582   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
   2583                                         llvm::makeArrayRef(&Lit, 1),
   2584                                         Tok.getLocation());
   2585 }
   2586 
   2587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
   2588   unsigned IntSize = Context.getTargetInfo().getIntWidth();
   2589   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
   2590                                       Context.IntTy, Loc));
   2591 }
   2592 
   2593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
   2594                                   QualType Ty, SourceLocation Loc) {
   2595   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
   2596 
   2597   using llvm::APFloat;
   2598   APFloat Val(Format);
   2599 
   2600   APFloat::opStatus result = Literal.GetFloatValue(Val);
   2601 
   2602   // Overflow is always an error, but underflow is only an error if
   2603   // we underflowed to zero (APFloat reports denormals as underflow).
   2604   if ((result & APFloat::opOverflow) ||
   2605       ((result & APFloat::opUnderflow) && Val.isZero())) {
   2606     unsigned diagnostic;
   2607     SmallString<20> buffer;
   2608     if (result & APFloat::opOverflow) {
   2609       diagnostic = diag::warn_float_overflow;
   2610       APFloat::getLargest(Format).toString(buffer);
   2611     } else {
   2612       diagnostic = diag::warn_float_underflow;
   2613       APFloat::getSmallest(Format).toString(buffer);
   2614     }
   2615 
   2616     S.Diag(Loc, diagnostic)
   2617       << Ty
   2618       << StringRef(buffer.data(), buffer.size());
   2619   }
   2620 
   2621   bool isExact = (result == APFloat::opOK);
   2622   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
   2623 }
   2624 
   2625 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
   2626   // Fast path for a single digit (which is quite common).  A single digit
   2627   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
   2628   if (Tok.getLength() == 1) {
   2629     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
   2630     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
   2631   }
   2632 
   2633   SmallString<512> IntegerBuffer;
   2634   // Add padding so that NumericLiteralParser can overread by one character.
   2635   IntegerBuffer.resize(Tok.getLength()+1);
   2636   const char *ThisTokBegin = &IntegerBuffer[0];
   2637 
   2638   // Get the spelling of the token, which eliminates trigraphs, etc.
   2639   bool Invalid = false;
   2640   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
   2641   if (Invalid)
   2642     return ExprError();
   2643 
   2644   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
   2645                                Tok.getLocation(), PP);
   2646   if (Literal.hadError)
   2647     return ExprError();
   2648 
   2649   if (Literal.hasUDSuffix()) {
   2650     // We're building a user-defined literal.
   2651     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   2652     SourceLocation UDSuffixLoc =
   2653       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   2654 
   2655     // Make sure we're allowed user-defined literals here.
   2656     if (!UDLScope)
   2657       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
   2658 
   2659     QualType CookedTy;
   2660     if (Literal.isFloatingLiteral()) {
   2661       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
   2662       // long double, the literal is treated as a call of the form
   2663       //   operator "" X (f L)
   2664       CookedTy = Context.LongDoubleTy;
   2665     } else {
   2666       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
   2667       // unsigned long long, the literal is treated as a call of the form
   2668       //   operator "" X (n ULL)
   2669       CookedTy = Context.UnsignedLongLongTy;
   2670     }
   2671 
   2672     DeclarationName OpName =
   2673       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   2674     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   2675     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   2676 
   2677     // Perform literal operator lookup to determine if we're building a raw
   2678     // literal or a cooked one.
   2679     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
   2680     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
   2681                                   /*AllowRawAndTemplate*/true)) {
   2682     case LOLR_Error:
   2683       return ExprError();
   2684 
   2685     case LOLR_Cooked: {
   2686       Expr *Lit;
   2687       if (Literal.isFloatingLiteral()) {
   2688         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
   2689       } else {
   2690         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
   2691         if (Literal.GetIntegerValue(ResultVal))
   2692           Diag(Tok.getLocation(), diag::warn_integer_too_large);
   2693         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
   2694                                      Tok.getLocation());
   2695       }
   2696       return BuildLiteralOperatorCall(R, OpNameInfo,
   2697                                       llvm::makeArrayRef(&Lit, 1),
   2698                                       Tok.getLocation());
   2699     }
   2700 
   2701     case LOLR_Raw: {
   2702       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
   2703       // literal is treated as a call of the form
   2704       //   operator "" X ("n")
   2705       SourceLocation TokLoc = Tok.getLocation();
   2706       unsigned Length = Literal.getUDSuffixOffset();
   2707       QualType StrTy = Context.getConstantArrayType(
   2708           Context.CharTy, llvm::APInt(32, Length + 1),
   2709           ArrayType::Normal, 0);
   2710       Expr *Lit = StringLiteral::Create(
   2711           Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
   2712           /*Pascal*/false, StrTy, &TokLoc, 1);
   2713       return BuildLiteralOperatorCall(R, OpNameInfo,
   2714                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
   2715     }
   2716 
   2717     case LOLR_Template:
   2718       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
   2719       // template), L is treated as a call fo the form
   2720       //   operator "" X <'c1', 'c2', ... 'ck'>()
   2721       // where n is the source character sequence c1 c2 ... ck.
   2722       TemplateArgumentListInfo ExplicitArgs;
   2723       unsigned CharBits = Context.getIntWidth(Context.CharTy);
   2724       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
   2725       llvm::APSInt Value(CharBits, CharIsUnsigned);
   2726       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
   2727         Value = ThisTokBegin[I];
   2728         TemplateArgument Arg(Context, Value, Context.CharTy);
   2729         TemplateArgumentLocInfo ArgInfo;
   2730         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
   2731       }
   2732       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
   2733                                       Tok.getLocation(), &ExplicitArgs);
   2734     }
   2735 
   2736     llvm_unreachable("unexpected literal operator lookup result");
   2737   }
   2738 
   2739   Expr *Res;
   2740 
   2741   if (Literal.isFloatingLiteral()) {
   2742     QualType Ty;
   2743     if (Literal.isFloat)
   2744       Ty = Context.FloatTy;
   2745     else if (!Literal.isLong)
   2746       Ty = Context.DoubleTy;
   2747     else
   2748       Ty = Context.LongDoubleTy;
   2749 
   2750     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
   2751 
   2752     if (Ty == Context.DoubleTy) {
   2753       if (getLangOpts().SinglePrecisionConstants) {
   2754         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
   2755       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
   2756         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
   2757         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
   2758       }
   2759     }
   2760   } else if (!Literal.isIntegerLiteral()) {
   2761     return ExprError();
   2762   } else {
   2763     QualType Ty;
   2764 
   2765     // long long is a C99 feature.
   2766     if (!getLangOpts().C99 && Literal.isLongLong)
   2767       Diag(Tok.getLocation(),
   2768            getLangOpts().CPlusPlus0x ?
   2769              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
   2770 
   2771     // Get the value in the widest-possible width.
   2772     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
   2773     // The microsoft literal suffix extensions support 128-bit literals, which
   2774     // may be wider than [u]intmax_t.
   2775     if (Literal.isMicrosoftInteger && MaxWidth < 128)
   2776       MaxWidth = 128;
   2777     llvm::APInt ResultVal(MaxWidth, 0);
   2778 
   2779     if (Literal.GetIntegerValue(ResultVal)) {
   2780       // If this value didn't fit into uintmax_t, warn and force to ull.
   2781       Diag(Tok.getLocation(), diag::warn_integer_too_large);
   2782       Ty = Context.UnsignedLongLongTy;
   2783       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
   2784              "long long is not intmax_t?");
   2785     } else {
   2786       // If this value fits into a ULL, try to figure out what else it fits into
   2787       // according to the rules of C99 6.4.4.1p5.
   2788 
   2789       // Octal, Hexadecimal, and integers with a U suffix are allowed to
   2790       // be an unsigned int.
   2791       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
   2792 
   2793       // Check from smallest to largest, picking the smallest type we can.
   2794       unsigned Width = 0;
   2795       if (!Literal.isLong && !Literal.isLongLong) {
   2796         // Are int/unsigned possibilities?
   2797         unsigned IntSize = Context.getTargetInfo().getIntWidth();
   2798 
   2799         // Does it fit in a unsigned int?
   2800         if (ResultVal.isIntN(IntSize)) {
   2801           // Does it fit in a signed int?
   2802           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
   2803             Ty = Context.IntTy;
   2804           else if (AllowUnsigned)
   2805             Ty = Context.UnsignedIntTy;
   2806           Width = IntSize;
   2807         }
   2808       }
   2809 
   2810       // Are long/unsigned long possibilities?
   2811       if (Ty.isNull() && !Literal.isLongLong) {
   2812         unsigned LongSize = Context.getTargetInfo().getLongWidth();
   2813 
   2814         // Does it fit in a unsigned long?
   2815         if (ResultVal.isIntN(LongSize)) {
   2816           // Does it fit in a signed long?
   2817           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
   2818             Ty = Context.LongTy;
   2819           else if (AllowUnsigned)
   2820             Ty = Context.UnsignedLongTy;
   2821           Width = LongSize;
   2822         }
   2823       }
   2824 
   2825       // Check long long if needed.
   2826       if (Ty.isNull()) {
   2827         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
   2828 
   2829         // Does it fit in a unsigned long long?
   2830         if (ResultVal.isIntN(LongLongSize)) {
   2831           // Does it fit in a signed long long?
   2832           // To be compatible with MSVC, hex integer literals ending with the
   2833           // LL or i64 suffix are always signed in Microsoft mode.
   2834           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
   2835               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
   2836             Ty = Context.LongLongTy;
   2837           else if (AllowUnsigned)
   2838             Ty = Context.UnsignedLongLongTy;
   2839           Width = LongLongSize;
   2840         }
   2841       }
   2842 
   2843       // If it doesn't fit in unsigned long long, and we're using Microsoft
   2844       // extensions, then its a 128-bit integer literal.
   2845       if (Ty.isNull() && Literal.isMicrosoftInteger) {
   2846         if (Literal.isUnsigned)
   2847           Ty = Context.UnsignedInt128Ty;
   2848         else
   2849           Ty = Context.Int128Ty;
   2850         Width = 128;
   2851       }
   2852 
   2853       // If we still couldn't decide a type, we probably have something that
   2854       // does not fit in a signed long long, but has no U suffix.
   2855       if (Ty.isNull()) {
   2856         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
   2857         Ty = Context.UnsignedLongLongTy;
   2858         Width = Context.getTargetInfo().getLongLongWidth();
   2859       }
   2860 
   2861       if (ResultVal.getBitWidth() != Width)
   2862         ResultVal = ResultVal.trunc(Width);
   2863     }
   2864     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
   2865   }
   2866 
   2867   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
   2868   if (Literal.isImaginary)
   2869     Res = new (Context) ImaginaryLiteral(Res,
   2870                                         Context.getComplexType(Res->getType()));
   2871 
   2872   return Owned(Res);
   2873 }
   2874 
   2875 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
   2876   assert((E != 0) && "ActOnParenExpr() missing expr");
   2877   return Owned(new (Context) ParenExpr(L, R, E));
   2878 }
   2879 
   2880 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
   2881                                          SourceLocation Loc,
   2882                                          SourceRange ArgRange) {
   2883   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
   2884   // scalar or vector data type argument..."
   2885   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
   2886   // type (C99 6.2.5p18) or void.
   2887   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
   2888     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
   2889       << T << ArgRange;
   2890     return true;
   2891   }
   2892 
   2893   assert((T->isVoidType() || !T->isIncompleteType()) &&
   2894          "Scalar types should always be complete");
   2895   return false;
   2896 }
   2897 
   2898 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
   2899                                            SourceLocation Loc,
   2900                                            SourceRange ArgRange,
   2901                                            UnaryExprOrTypeTrait TraitKind) {
   2902   // C99 6.5.3.4p1:
   2903   if (T->isFunctionType()) {
   2904     // alignof(function) is allowed as an extension.
   2905     if (TraitKind == UETT_SizeOf)
   2906       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
   2907     return false;
   2908   }
   2909 
   2910   // Allow sizeof(void)/alignof(void) as an extension.
   2911   if (T->isVoidType()) {
   2912     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
   2913     return false;
   2914   }
   2915 
   2916   return true;
   2917 }
   2918 
   2919 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
   2920                                              SourceLocation Loc,
   2921                                              SourceRange ArgRange,
   2922                                              UnaryExprOrTypeTrait TraitKind) {
   2923   // Reject sizeof(interface) and sizeof(interface<proto>) if the
   2924   // runtime doesn't allow it.
   2925   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
   2926     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
   2927       << T << (TraitKind == UETT_SizeOf)
   2928       << ArgRange;
   2929     return true;
   2930   }
   2931 
   2932   return false;
   2933 }
   2934 
   2935 /// \brief Check the constrains on expression operands to unary type expression
   2936 /// and type traits.
   2937 ///
   2938 /// Completes any types necessary and validates the constraints on the operand
   2939 /// expression. The logic mostly mirrors the type-based overload, but may modify
   2940 /// the expression as it completes the type for that expression through template
   2941 /// instantiation, etc.
   2942 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
   2943                                             UnaryExprOrTypeTrait ExprKind) {
   2944   QualType ExprTy = E->getType();
   2945 
   2946   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   2947   //   the result is the size of the referenced type."
   2948   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   2949   //   result shall be the alignment of the referenced type."
   2950   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
   2951     ExprTy = Ref->getPointeeType();
   2952 
   2953   if (ExprKind == UETT_VecStep)
   2954     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
   2955                                         E->getSourceRange());
   2956 
   2957   // Whitelist some types as extensions
   2958   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
   2959                                       E->getSourceRange(), ExprKind))
   2960     return false;
   2961 
   2962   if (RequireCompleteExprType(E,
   2963                               diag::err_sizeof_alignof_incomplete_type,
   2964                               ExprKind, E->getSourceRange()))
   2965     return true;
   2966 
   2967   // Completeing the expression's type may have changed it.
   2968   ExprTy = E->getType();
   2969   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
   2970     ExprTy = Ref->getPointeeType();
   2971 
   2972   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
   2973                                        E->getSourceRange(), ExprKind))
   2974     return true;
   2975 
   2976   if (ExprKind == UETT_SizeOf) {
   2977     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
   2978       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
   2979         QualType OType = PVD->getOriginalType();
   2980         QualType Type = PVD->getType();
   2981         if (Type->isPointerType() && OType->isArrayType()) {
   2982           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
   2983             << Type << OType;
   2984           Diag(PVD->getLocation(), diag::note_declared_at);
   2985         }
   2986       }
   2987     }
   2988   }
   2989 
   2990   return false;
   2991 }
   2992 
   2993 /// \brief Check the constraints on operands to unary expression and type
   2994 /// traits.
   2995 ///
   2996 /// This will complete any types necessary, and validate the various constraints
   2997 /// on those operands.
   2998 ///
   2999 /// The UsualUnaryConversions() function is *not* called by this routine.
   3000 /// C99 6.3.2.1p[2-4] all state:
   3001 ///   Except when it is the operand of the sizeof operator ...
   3002 ///
   3003 /// C++ [expr.sizeof]p4
   3004 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
   3005 ///   standard conversions are not applied to the operand of sizeof.
   3006 ///
   3007 /// This policy is followed for all of the unary trait expressions.
   3008 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
   3009                                             SourceLocation OpLoc,
   3010                                             SourceRange ExprRange,
   3011                                             UnaryExprOrTypeTrait ExprKind) {
   3012   if (ExprType->isDependentType())
   3013     return false;
   3014 
   3015   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   3016   //   the result is the size of the referenced type."
   3017   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   3018   //   result shall be the alignment of the referenced type."
   3019   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
   3020     ExprType = Ref->getPointeeType();
   3021 
   3022   if (ExprKind == UETT_VecStep)
   3023     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
   3024 
   3025   // Whitelist some types as extensions
   3026   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
   3027                                       ExprKind))
   3028     return false;
   3029 
   3030   if (RequireCompleteType(OpLoc, ExprType,
   3031                           diag::err_sizeof_alignof_incomplete_type,
   3032                           ExprKind, ExprRange))
   3033     return true;
   3034 
   3035   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
   3036                                        ExprKind))
   3037     return true;
   3038 
   3039   return false;
   3040 }
   3041 
   3042 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
   3043   E = E->IgnoreParens();
   3044 
   3045   // alignof decl is always ok.
   3046   if (isa<DeclRefExpr>(E))
   3047     return false;
   3048 
   3049   // Cannot know anything else if the expression is dependent.
   3050   if (E->isTypeDependent())
   3051     return false;
   3052 
   3053   if (E->getBitField()) {
   3054     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
   3055        << 1 << E->getSourceRange();
   3056     return true;
   3057   }
   3058 
   3059   // Alignment of a field access is always okay, so long as it isn't a
   3060   // bit-field.
   3061   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
   3062     if (isa<FieldDecl>(ME->getMemberDecl()))
   3063       return false;
   3064 
   3065   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
   3066 }
   3067 
   3068 bool Sema::CheckVecStepExpr(Expr *E) {
   3069   E = E->IgnoreParens();
   3070 
   3071   // Cannot know anything else if the expression is dependent.
   3072   if (E->isTypeDependent())
   3073     return false;
   3074 
   3075   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
   3076 }
   3077 
   3078 /// \brief Build a sizeof or alignof expression given a type operand.
   3079 ExprResult
   3080 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
   3081                                      SourceLocation OpLoc,
   3082                                      UnaryExprOrTypeTrait ExprKind,
   3083                                      SourceRange R) {
   3084   if (!TInfo)
   3085     return ExprError();
   3086 
   3087   QualType T = TInfo->getType();
   3088 
   3089   if (!T->isDependentType() &&
   3090       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
   3091     return ExprError();
   3092 
   3093   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3094   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
   3095                                                       Context.getSizeType(),
   3096                                                       OpLoc, R.getEnd()));
   3097 }
   3098 
   3099 /// \brief Build a sizeof or alignof expression given an expression
   3100 /// operand.
   3101 ExprResult
   3102 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
   3103                                      UnaryExprOrTypeTrait ExprKind) {
   3104   ExprResult PE = CheckPlaceholderExpr(E);
   3105   if (PE.isInvalid())
   3106     return ExprError();
   3107 
   3108   E = PE.get();
   3109 
   3110   // Verify that the operand is valid.
   3111   bool isInvalid = false;
   3112   if (E->isTypeDependent()) {
   3113     // Delay type-checking for type-dependent expressions.
   3114   } else if (ExprKind == UETT_AlignOf) {
   3115     isInvalid = CheckAlignOfExpr(*this, E);
   3116   } else if (ExprKind == UETT_VecStep) {
   3117     isInvalid = CheckVecStepExpr(E);
   3118   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
   3119     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
   3120     isInvalid = true;
   3121   } else {
   3122     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
   3123   }
   3124 
   3125   if (isInvalid)
   3126     return ExprError();
   3127 
   3128   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
   3129     PE = TranformToPotentiallyEvaluated(E);
   3130     if (PE.isInvalid()) return ExprError();
   3131     E = PE.take();
   3132   }
   3133 
   3134   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3135   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
   3136       ExprKind, E, Context.getSizeType(), OpLoc,
   3137       E->getSourceRange().getEnd()));
   3138 }
   3139 
   3140 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
   3141 /// expr and the same for @c alignof and @c __alignof
   3142 /// Note that the ArgRange is invalid if isType is false.
   3143 ExprResult
   3144 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
   3145                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
   3146                                     void *TyOrEx, const SourceRange &ArgRange) {
   3147   // If error parsing type, ignore.
   3148   if (TyOrEx == 0) return ExprError();
   3149 
   3150   if (IsType) {
   3151     TypeSourceInfo *TInfo;
   3152     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
   3153     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
   3154   }
   3155 
   3156   Expr *ArgEx = (Expr *)TyOrEx;
   3157   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
   3158   return Result;
   3159 }
   3160 
   3161 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
   3162                                      bool IsReal) {
   3163   if (V.get()->isTypeDependent())
   3164     return S.Context.DependentTy;
   3165 
   3166   // _Real and _Imag are only l-values for normal l-values.
   3167   if (V.get()->getObjectKind() != OK_Ordinary) {
   3168     V = S.DefaultLvalueConversion(V.take());
   3169     if (V.isInvalid())
   3170       return QualType();
   3171   }
   3172 
   3173   // These operators return the element type of a complex type.
   3174   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
   3175     return CT->getElementType();
   3176 
   3177   // Otherwise they pass through real integer and floating point types here.
   3178   if (V.get()->getType()->isArithmeticType())
   3179     return V.get()->getType();
   3180 
   3181   // Test for placeholders.
   3182   ExprResult PR = S.CheckPlaceholderExpr(V.get());
   3183   if (PR.isInvalid()) return QualType();
   3184   if (PR.get() != V.get()) {
   3185     V = PR;
   3186     return CheckRealImagOperand(S, V, Loc, IsReal);
   3187   }
   3188 
   3189   // Reject anything else.
   3190   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
   3191     << (IsReal ? "__real" : "__imag");
   3192   return QualType();
   3193 }
   3194 
   3195 
   3196 
   3197 ExprResult
   3198 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
   3199                           tok::TokenKind Kind, Expr *Input) {
   3200   UnaryOperatorKind Opc;
   3201   switch (Kind) {
   3202   default: llvm_unreachable("Unknown unary op!");
   3203   case tok::plusplus:   Opc = UO_PostInc; break;
   3204   case tok::minusminus: Opc = UO_PostDec; break;
   3205   }
   3206 
   3207   // Since this might is a postfix expression, get rid of ParenListExprs.
   3208   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
   3209   if (Result.isInvalid()) return ExprError();
   3210   Input = Result.take();
   3211 
   3212   return BuildUnaryOp(S, OpLoc, Opc, Input);
   3213 }
   3214 
   3215 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
   3216 ///
   3217 /// \return true on error
   3218 static bool checkArithmeticOnObjCPointer(Sema &S,
   3219                                          SourceLocation opLoc,
   3220                                          Expr *op) {
   3221   assert(op->getType()->isObjCObjectPointerType());
   3222   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
   3223     return false;
   3224 
   3225   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
   3226     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
   3227     << op->getSourceRange();
   3228   return true;
   3229 }
   3230 
   3231 ExprResult
   3232 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
   3233                               Expr *Idx, SourceLocation RLoc) {
   3234   // Since this might be a postfix expression, get rid of ParenListExprs.
   3235   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
   3236   if (Result.isInvalid()) return ExprError();
   3237   Base = Result.take();
   3238 
   3239   Expr *LHSExp = Base, *RHSExp = Idx;
   3240 
   3241   if (getLangOpts().CPlusPlus &&
   3242       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
   3243     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
   3244                                                   Context.DependentTy,
   3245                                                   VK_LValue, OK_Ordinary,
   3246                                                   RLoc));
   3247   }
   3248 
   3249   if (getLangOpts().CPlusPlus &&
   3250       (LHSExp->getType()->isRecordType() ||
   3251        LHSExp->getType()->isEnumeralType() ||
   3252        RHSExp->getType()->isRecordType() ||
   3253        RHSExp->getType()->isEnumeralType()) &&
   3254       !LHSExp->getType()->isObjCObjectPointerType()) {
   3255     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
   3256   }
   3257 
   3258   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
   3259 }
   3260 
   3261 ExprResult
   3262 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   3263                                       Expr *Idx, SourceLocation RLoc) {
   3264   Expr *LHSExp = Base;
   3265   Expr *RHSExp = Idx;
   3266 
   3267   // Perform default conversions.
   3268   if (!LHSExp->getType()->getAs<VectorType>()) {
   3269     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
   3270     if (Result.isInvalid())
   3271       return ExprError();
   3272     LHSExp = Result.take();
   3273   }
   3274   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
   3275   if (Result.isInvalid())
   3276     return ExprError();
   3277   RHSExp = Result.take();
   3278 
   3279   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
   3280   ExprValueKind VK = VK_LValue;
   3281   ExprObjectKind OK = OK_Ordinary;
   3282 
   3283   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
   3284   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
   3285   // in the subscript position. As a result, we need to derive the array base
   3286   // and index from the expression types.
   3287   Expr *BaseExpr, *IndexExpr;
   3288   QualType ResultType;
   3289   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
   3290     BaseExpr = LHSExp;
   3291     IndexExpr = RHSExp;
   3292     ResultType = Context.DependentTy;
   3293   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
   3294     BaseExpr = LHSExp;
   3295     IndexExpr = RHSExp;
   3296     ResultType = PTy->getPointeeType();
   3297   } else if (const ObjCObjectPointerType *PTy =
   3298                LHSTy->getAs<ObjCObjectPointerType>()) {
   3299     BaseExpr = LHSExp;
   3300     IndexExpr = RHSExp;
   3301 
   3302     // Use custom logic if this should be the pseudo-object subscript
   3303     // expression.
   3304     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
   3305       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
   3306 
   3307     ResultType = PTy->getPointeeType();
   3308     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
   3309       Diag(LLoc, diag::err_subscript_nonfragile_interface)
   3310         << ResultType << BaseExpr->getSourceRange();
   3311       return ExprError();
   3312     }
   3313   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
   3314      // Handle the uncommon case of "123[Ptr]".
   3315     BaseExpr = RHSExp;
   3316     IndexExpr = LHSExp;
   3317     ResultType = PTy->getPointeeType();
   3318   } else if (const ObjCObjectPointerType *PTy =
   3319                RHSTy->getAs<ObjCObjectPointerType>()) {
   3320      // Handle the uncommon case of "123[Ptr]".
   3321     BaseExpr = RHSExp;
   3322     IndexExpr = LHSExp;
   3323     ResultType = PTy->getPointeeType();
   3324     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
   3325       Diag(LLoc, diag::err_subscript_nonfragile_interface)
   3326         << ResultType << BaseExpr->getSourceRange();
   3327       return ExprError();
   3328     }
   3329   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
   3330     BaseExpr = LHSExp;    // vectors: V[123]
   3331     IndexExpr = RHSExp;
   3332     VK = LHSExp->getValueKind();
   3333     if (VK != VK_RValue)
   3334       OK = OK_VectorComponent;
   3335 
   3336     // FIXME: need to deal with const...
   3337     ResultType = VTy->getElementType();
   3338   } else if (LHSTy->isArrayType()) {
   3339     // If we see an array that wasn't promoted by
   3340     // DefaultFunctionArrayLvalueConversion, it must be an array that
   3341     // wasn't promoted because of the C90 rule that doesn't
   3342     // allow promoting non-lvalue arrays.  Warn, then
   3343     // force the promotion here.
   3344     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   3345         LHSExp->getSourceRange();
   3346     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
   3347                                CK_ArrayToPointerDecay).take();
   3348     LHSTy = LHSExp->getType();
   3349 
   3350     BaseExpr = LHSExp;
   3351     IndexExpr = RHSExp;
   3352     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
   3353   } else if (RHSTy->isArrayType()) {
   3354     // Same as previous, except for 123[f().a] case
   3355     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   3356         RHSExp->getSourceRange();
   3357     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
   3358                                CK_ArrayToPointerDecay).take();
   3359     RHSTy = RHSExp->getType();
   3360 
   3361     BaseExpr = RHSExp;
   3362     IndexExpr = LHSExp;
   3363     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
   3364   } else {
   3365     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
   3366        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
   3367   }
   3368   // C99 6.5.2.1p1
   3369   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
   3370     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
   3371                      << IndexExpr->getSourceRange());
   3372 
   3373   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
   3374        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
   3375          && !IndexExpr->isTypeDependent())
   3376     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
   3377 
   3378   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   3379   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
   3380   // type. Note that Functions are not objects, and that (in C99 parlance)
   3381   // incomplete types are not object types.
   3382   if (ResultType->isFunctionType()) {
   3383     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
   3384       << ResultType << BaseExpr->getSourceRange();
   3385     return ExprError();
   3386   }
   3387 
   3388   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
   3389     // GNU extension: subscripting on pointer to void
   3390     Diag(LLoc, diag::ext_gnu_subscript_void_type)
   3391       << BaseExpr->getSourceRange();
   3392 
   3393     // C forbids expressions of unqualified void type from being l-values.
   3394     // See IsCForbiddenLValueType.
   3395     if (!ResultType.hasQualifiers()) VK = VK_RValue;
   3396   } else if (!ResultType->isDependentType() &&
   3397       RequireCompleteType(LLoc, ResultType,
   3398                           diag::err_subscript_incomplete_type, BaseExpr))
   3399     return ExprError();
   3400 
   3401   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
   3402          !ResultType.isCForbiddenLValueType());
   3403 
   3404   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
   3405                                                 ResultType, VK, OK, RLoc));
   3406 }
   3407 
   3408 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
   3409                                         FunctionDecl *FD,
   3410                                         ParmVarDecl *Param) {
   3411   if (Param->hasUnparsedDefaultArg()) {
   3412     Diag(CallLoc,
   3413          diag::err_use_of_default_argument_to_function_declared_later) <<
   3414       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
   3415     Diag(UnparsedDefaultArgLocs[Param],
   3416          diag::note_default_argument_declared_here);
   3417     return ExprError();
   3418   }
   3419 
   3420   if (Param->hasUninstantiatedDefaultArg()) {
   3421     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
   3422 
   3423     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
   3424                                                  Param);
   3425 
   3426     // Instantiate the expression.
   3427     MultiLevelTemplateArgumentList ArgList
   3428       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
   3429 
   3430     std::pair<const TemplateArgument *, unsigned> Innermost
   3431       = ArgList.getInnermost();
   3432     InstantiatingTemplate Inst(*this, CallLoc, Param,
   3433                                ArrayRef<TemplateArgument>(Innermost.first,
   3434                                                           Innermost.second));
   3435     if (Inst)
   3436       return ExprError();
   3437 
   3438     ExprResult Result;
   3439     {
   3440       // C++ [dcl.fct.default]p5:
   3441       //   The names in the [default argument] expression are bound, and
   3442       //   the semantic constraints are checked, at the point where the
   3443       //   default argument expression appears.
   3444       ContextRAII SavedContext(*this, FD);
   3445       LocalInstantiationScope Local(*this);
   3446       Result = SubstExpr(UninstExpr, ArgList);
   3447     }
   3448     if (Result.isInvalid())
   3449       return ExprError();
   3450 
   3451     // Check the expression as an initializer for the parameter.
   3452     InitializedEntity Entity
   3453       = InitializedEntity::InitializeParameter(Context, Param);
   3454     InitializationKind Kind
   3455       = InitializationKind::CreateCopy(Param->getLocation(),
   3456              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
   3457     Expr *ResultE = Result.takeAs<Expr>();
   3458 
   3459     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
   3460     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
   3461     if (Result.isInvalid())
   3462       return ExprError();
   3463 
   3464     Expr *Arg = Result.takeAs<Expr>();
   3465     CheckImplicitConversions(Arg, Param->getOuterLocStart());
   3466     // Build the default argument expression.
   3467     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
   3468   }
   3469 
   3470   // If the default expression creates temporaries, we need to
   3471   // push them to the current stack of expression temporaries so they'll
   3472   // be properly destroyed.
   3473   // FIXME: We should really be rebuilding the default argument with new
   3474   // bound temporaries; see the comment in PR5810.
   3475   // We don't need to do that with block decls, though, because
   3476   // blocks in default argument expression can never capture anything.
   3477   if (isa<ExprWithCleanups>(Param->getInit())) {
   3478     // Set the "needs cleanups" bit regardless of whether there are
   3479     // any explicit objects.
   3480     ExprNeedsCleanups = true;
   3481 
   3482     // Append all the objects to the cleanup list.  Right now, this
   3483     // should always be a no-op, because blocks in default argument
   3484     // expressions should never be able to capture anything.
   3485     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
   3486            "default argument expression has capturing blocks?");
   3487   }
   3488 
   3489   // We already type-checked the argument, so we know it works.
   3490   // Just mark all of the declarations in this potentially-evaluated expression
   3491   // as being "referenced".
   3492   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
   3493                                    /*SkipLocalVariables=*/true);
   3494   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
   3495 }
   3496 
   3497 
   3498 Sema::VariadicCallType
   3499 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
   3500                           Expr *Fn) {
   3501   if (Proto && Proto->isVariadic()) {
   3502     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
   3503       return VariadicConstructor;
   3504     else if (Fn && Fn->getType()->isBlockPointerType())
   3505       return VariadicBlock;
   3506     else if (FDecl) {
   3507       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
   3508         if (Method->isInstance())
   3509           return VariadicMethod;
   3510     }
   3511     return VariadicFunction;
   3512   }
   3513   return VariadicDoesNotApply;
   3514 }
   3515 
   3516 /// ConvertArgumentsForCall - Converts the arguments specified in
   3517 /// Args/NumArgs to the parameter types of the function FDecl with
   3518 /// function prototype Proto. Call is the call expression itself, and
   3519 /// Fn is the function expression. For a C++ member function, this
   3520 /// routine does not attempt to convert the object argument. Returns
   3521 /// true if the call is ill-formed.
   3522 bool
   3523 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
   3524                               FunctionDecl *FDecl,
   3525                               const FunctionProtoType *Proto,
   3526                               Expr **Args, unsigned NumArgs,
   3527                               SourceLocation RParenLoc,
   3528                               bool IsExecConfig) {
   3529   // Bail out early if calling a builtin with custom typechecking.
   3530   // We don't need to do this in the
   3531   if (FDecl)
   3532     if (unsigned ID = FDecl->getBuiltinID())
   3533       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
   3534         return false;
   3535 
   3536   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
   3537   // assignment, to the types of the corresponding parameter, ...
   3538   unsigned NumArgsInProto = Proto->getNumArgs();
   3539   bool Invalid = false;
   3540   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
   3541   unsigned FnKind = Fn->getType()->isBlockPointerType()
   3542                        ? 1 /* block */
   3543                        : (IsExecConfig ? 3 /* kernel function (exec config) */
   3544                                        : 0 /* function */);
   3545 
   3546   // If too few arguments are available (and we don't have default
   3547   // arguments for the remaining parameters), don't make the call.
   3548   if (NumArgs < NumArgsInProto) {
   3549     if (NumArgs < MinArgs) {
   3550       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
   3551         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
   3552                           ? diag::err_typecheck_call_too_few_args_one
   3553                           : diag::err_typecheck_call_too_few_args_at_least_one)
   3554           << FnKind
   3555           << FDecl->getParamDecl(0) << Fn->getSourceRange();
   3556       else
   3557         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
   3558                           ? diag::err_typecheck_call_too_few_args
   3559                           : diag::err_typecheck_call_too_few_args_at_least)
   3560           << FnKind
   3561           << MinArgs << NumArgs << Fn->getSourceRange();
   3562 
   3563       // Emit the location of the prototype.
   3564       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   3565         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   3566           << FDecl;
   3567 
   3568       return true;
   3569     }
   3570     Call->setNumArgs(Context, NumArgsInProto);
   3571   }
   3572 
   3573   // If too many are passed and not variadic, error on the extras and drop
   3574   // them.
   3575   if (NumArgs > NumArgsInProto) {
   3576     if (!Proto->isVariadic()) {
   3577       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
   3578         Diag(Args[NumArgsInProto]->getLocStart(),
   3579              MinArgs == NumArgsInProto
   3580                ? diag::err_typecheck_call_too_many_args_one
   3581                : diag::err_typecheck_call_too_many_args_at_most_one)
   3582           << FnKind
   3583           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
   3584           << SourceRange(Args[NumArgsInProto]->getLocStart(),
   3585                          Args[NumArgs-1]->getLocEnd());
   3586       else
   3587         Diag(Args[NumArgsInProto]->getLocStart(),
   3588              MinArgs == NumArgsInProto
   3589                ? diag::err_typecheck_call_too_many_args
   3590                : diag::err_typecheck_call_too_many_args_at_most)
   3591           << FnKind
   3592           << NumArgsInProto << NumArgs << Fn->getSourceRange()
   3593           << SourceRange(Args[NumArgsInProto]->getLocStart(),
   3594                          Args[NumArgs-1]->getLocEnd());
   3595 
   3596       // Emit the location of the prototype.
   3597       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   3598         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   3599           << FDecl;
   3600 
   3601       // This deletes the extra arguments.
   3602       Call->setNumArgs(Context, NumArgsInProto);
   3603       return true;
   3604     }
   3605   }
   3606   SmallVector<Expr *, 8> AllArgs;
   3607   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
   3608 
   3609   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
   3610                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
   3611   if (Invalid)
   3612     return true;
   3613   unsigned TotalNumArgs = AllArgs.size();
   3614   for (unsigned i = 0; i < TotalNumArgs; ++i)
   3615     Call->setArg(i, AllArgs[i]);
   3616 
   3617   return false;
   3618 }
   3619 
   3620 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
   3621                                   FunctionDecl *FDecl,
   3622                                   const FunctionProtoType *Proto,
   3623                                   unsigned FirstProtoArg,
   3624                                   Expr **Args, unsigned NumArgs,
   3625                                   SmallVector<Expr *, 8> &AllArgs,
   3626                                   VariadicCallType CallType,
   3627                                   bool AllowExplicit) {
   3628   unsigned NumArgsInProto = Proto->getNumArgs();
   3629   unsigned NumArgsToCheck = NumArgs;
   3630   bool Invalid = false;
   3631   if (NumArgs != NumArgsInProto)
   3632     // Use default arguments for missing arguments
   3633     NumArgsToCheck = NumArgsInProto;
   3634   unsigned ArgIx = 0;
   3635   // Continue to check argument types (even if we have too few/many args).
   3636   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
   3637     QualType ProtoArgType = Proto->getArgType(i);
   3638 
   3639     Expr *Arg;
   3640     ParmVarDecl *Param;
   3641     if (ArgIx < NumArgs) {
   3642       Arg = Args[ArgIx++];
   3643 
   3644       if (RequireCompleteType(Arg->getLocStart(),
   3645                               ProtoArgType,
   3646                               diag::err_call_incomplete_argument, Arg))
   3647         return true;
   3648 
   3649       // Pass the argument
   3650       Param = 0;
   3651       if (FDecl && i < FDecl->getNumParams())
   3652         Param = FDecl->getParamDecl(i);
   3653 
   3654       // Strip the unbridged-cast placeholder expression off, if applicable.
   3655       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
   3656           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
   3657           (!Param || !Param->hasAttr<CFConsumedAttr>()))
   3658         Arg = stripARCUnbridgedCast(Arg);
   3659 
   3660       InitializedEntity Entity =
   3661         Param? InitializedEntity::InitializeParameter(Context, Param)
   3662              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
   3663                                                       Proto->isArgConsumed(i));
   3664       ExprResult ArgE = PerformCopyInitialization(Entity,
   3665                                                   SourceLocation(),
   3666                                                   Owned(Arg),
   3667                                                   /*TopLevelOfInitList=*/false,
   3668                                                   AllowExplicit);
   3669       if (ArgE.isInvalid())
   3670         return true;
   3671 
   3672       Arg = ArgE.takeAs<Expr>();
   3673     } else {
   3674       Param = FDecl->getParamDecl(i);
   3675 
   3676       ExprResult ArgExpr =
   3677         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
   3678       if (ArgExpr.isInvalid())
   3679         return true;
   3680 
   3681       Arg = ArgExpr.takeAs<Expr>();
   3682     }
   3683 
   3684     // Check for array bounds violations for each argument to the call. This
   3685     // check only triggers warnings when the argument isn't a more complex Expr
   3686     // with its own checking, such as a BinaryOperator.
   3687     CheckArrayAccess(Arg);
   3688 
   3689     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
   3690     CheckStaticArrayArgument(CallLoc, Param, Arg);
   3691 
   3692     AllArgs.push_back(Arg);
   3693   }
   3694 
   3695   // If this is a variadic call, handle args passed through "...".
   3696   if (CallType != VariadicDoesNotApply) {
   3697     // Assume that extern "C" functions with variadic arguments that
   3698     // return __unknown_anytype aren't *really* variadic.
   3699     if (Proto->getResultType() == Context.UnknownAnyTy &&
   3700         FDecl && FDecl->isExternC()) {
   3701       for (unsigned i = ArgIx; i != NumArgs; ++i) {
   3702         ExprResult arg;
   3703         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
   3704           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
   3705         else
   3706           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
   3707         Invalid |= arg.isInvalid();
   3708         AllArgs.push_back(arg.take());
   3709       }
   3710 
   3711     // Otherwise do argument promotion, (C99 6.5.2.2p7).
   3712     } else {
   3713       for (unsigned i = ArgIx; i != NumArgs; ++i) {
   3714         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
   3715                                                           FDecl);
   3716         Invalid |= Arg.isInvalid();
   3717         AllArgs.push_back(Arg.take());
   3718       }
   3719     }
   3720 
   3721     // Check for array bounds violations.
   3722     for (unsigned i = ArgIx; i != NumArgs; ++i)
   3723       CheckArrayAccess(Args[i]);
   3724   }
   3725   return Invalid;
   3726 }
   3727 
   3728 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
   3729   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
   3730   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
   3731     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
   3732       << ATL->getLocalSourceRange();
   3733 }
   3734 
   3735 /// CheckStaticArrayArgument - If the given argument corresponds to a static
   3736 /// array parameter, check that it is non-null, and that if it is formed by
   3737 /// array-to-pointer decay, the underlying array is sufficiently large.
   3738 ///
   3739 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
   3740 /// array type derivation, then for each call to the function, the value of the
   3741 /// corresponding actual argument shall provide access to the first element of
   3742 /// an array with at least as many elements as specified by the size expression.
   3743 void
   3744 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
   3745                                ParmVarDecl *Param,
   3746                                const Expr *ArgExpr) {
   3747   // Static array parameters are not supported in C++.
   3748   if (!Param || getLangOpts().CPlusPlus)
   3749     return;
   3750 
   3751   QualType OrigTy = Param->getOriginalType();
   3752 
   3753   const ArrayType *AT = Context.getAsArrayType(OrigTy);
   3754   if (!AT || AT->getSizeModifier() != ArrayType::Static)
   3755     return;
   3756 
   3757   if (ArgExpr->isNullPointerConstant(Context,
   3758                                      Expr::NPC_NeverValueDependent)) {
   3759     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
   3760     DiagnoseCalleeStaticArrayParam(*this, Param);
   3761     return;
   3762   }
   3763 
   3764   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
   3765   if (!CAT)
   3766     return;
   3767 
   3768   const ConstantArrayType *ArgCAT =
   3769     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
   3770   if (!ArgCAT)
   3771     return;
   3772 
   3773   if (ArgCAT->getSize().ult(CAT->getSize())) {
   3774     Diag(CallLoc, diag::warn_static_array_too_small)
   3775       << ArgExpr->getSourceRange()
   3776       << (unsigned) ArgCAT->getSize().getZExtValue()
   3777       << (unsigned) CAT->getSize().getZExtValue();
   3778     DiagnoseCalleeStaticArrayParam(*this, Param);
   3779   }
   3780 }
   3781 
   3782 /// Given a function expression of unknown-any type, try to rebuild it
   3783 /// to have a function type.
   3784 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
   3785 
   3786 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
   3787 /// This provides the location of the left/right parens and a list of comma
   3788 /// locations.
   3789 ExprResult
   3790 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
   3791                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
   3792                     Expr *ExecConfig, bool IsExecConfig) {
   3793   // Since this might be a postfix expression, get rid of ParenListExprs.
   3794   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
   3795   if (Result.isInvalid()) return ExprError();
   3796   Fn = Result.take();
   3797 
   3798   if (getLangOpts().CPlusPlus) {
   3799     // If this is a pseudo-destructor expression, build the call immediately.
   3800     if (isa<CXXPseudoDestructorExpr>(Fn)) {
   3801       if (!ArgExprs.empty()) {
   3802         // Pseudo-destructor calls should not have any arguments.
   3803         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
   3804           << FixItHint::CreateRemoval(
   3805                                     SourceRange(ArgExprs[0]->getLocStart(),
   3806                                                 ArgExprs.back()->getLocEnd()));
   3807       }
   3808 
   3809       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
   3810                                           Context.VoidTy, VK_RValue,
   3811                                           RParenLoc));
   3812     }
   3813 
   3814     // Determine whether this is a dependent call inside a C++ template,
   3815     // in which case we won't do any semantic analysis now.
   3816     // FIXME: Will need to cache the results of name lookup (including ADL) in
   3817     // Fn.
   3818     bool Dependent = false;
   3819     if (Fn->isTypeDependent())
   3820       Dependent = true;
   3821     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
   3822       Dependent = true;
   3823 
   3824     if (Dependent) {
   3825       if (ExecConfig) {
   3826         return Owned(new (Context) CUDAKernelCallExpr(
   3827             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
   3828             Context.DependentTy, VK_RValue, RParenLoc));
   3829       } else {
   3830         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
   3831                                             Context.DependentTy, VK_RValue,
   3832                                             RParenLoc));
   3833       }
   3834     }
   3835 
   3836     // Determine whether this is a call to an object (C++ [over.call.object]).
   3837     if (Fn->getType()->isRecordType())
   3838       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
   3839                                                 ArgExprs.data(),
   3840                                                 ArgExprs.size(), RParenLoc));
   3841 
   3842     if (Fn->getType() == Context.UnknownAnyTy) {
   3843       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
   3844       if (result.isInvalid()) return ExprError();
   3845       Fn = result.take();
   3846     }
   3847 
   3848     if (Fn->getType() == Context.BoundMemberTy) {
   3849       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
   3850                                        ArgExprs.size(), RParenLoc);
   3851     }
   3852   }
   3853 
   3854   // Check for overloaded calls.  This can happen even in C due to extensions.
   3855   if (Fn->getType() == Context.OverloadTy) {
   3856     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
   3857 
   3858     // We aren't supposed to apply this logic for if there's an '&' involved.
   3859     if (!find.HasFormOfMemberPointer) {
   3860       OverloadExpr *ovl = find.Expression;
   3861       if (isa<UnresolvedLookupExpr>(ovl)) {
   3862         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
   3863         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
   3864                                        ArgExprs.size(), RParenLoc, ExecConfig);
   3865       } else {
   3866         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
   3867                                          ArgExprs.size(), RParenLoc);
   3868       }
   3869     }
   3870   }
   3871 
   3872   // If we're directly calling a function, get the appropriate declaration.
   3873   if (Fn->getType() == Context.UnknownAnyTy) {
   3874     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
   3875     if (result.isInvalid()) return ExprError();
   3876     Fn = result.take();
   3877   }
   3878 
   3879   Expr *NakedFn = Fn->IgnoreParens();
   3880 
   3881   NamedDecl *NDecl = 0;
   3882   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
   3883     if (UnOp->getOpcode() == UO_AddrOf)
   3884       NakedFn = UnOp->getSubExpr()->IgnoreParens();
   3885 
   3886   if (isa<DeclRefExpr>(NakedFn))
   3887     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
   3888   else if (isa<MemberExpr>(NakedFn))
   3889     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
   3890 
   3891   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
   3892                                ArgExprs.size(), RParenLoc, ExecConfig,
   3893                                IsExecConfig);
   3894 }
   3895 
   3896 ExprResult
   3897 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
   3898                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
   3899   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
   3900   if (!ConfigDecl)
   3901     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
   3902                           << "cudaConfigureCall");
   3903   QualType ConfigQTy = ConfigDecl->getType();
   3904 
   3905   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
   3906       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
   3907   MarkFunctionReferenced(LLLLoc, ConfigDecl);
   3908 
   3909   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
   3910                        /*IsExecConfig=*/true);
   3911 }
   3912 
   3913 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
   3914 ///
   3915 /// __builtin_astype( value, dst type )
   3916 ///
   3917 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
   3918                                  SourceLocation BuiltinLoc,
   3919                                  SourceLocation RParenLoc) {
   3920   ExprValueKind VK = VK_RValue;
   3921   ExprObjectKind OK = OK_Ordinary;
   3922   QualType DstTy = GetTypeFromParser(ParsedDestTy);
   3923   QualType SrcTy = E->getType();
   3924   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
   3925     return ExprError(Diag(BuiltinLoc,
   3926                           diag::err_invalid_astype_of_different_size)
   3927                      << DstTy
   3928                      << SrcTy
   3929                      << E->getSourceRange());
   3930   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
   3931                RParenLoc));
   3932 }
   3933 
   3934 /// BuildResolvedCallExpr - Build a call to a resolved expression,
   3935 /// i.e. an expression not of \p OverloadTy.  The expression should
   3936 /// unary-convert to an expression of function-pointer or
   3937 /// block-pointer type.
   3938 ///
   3939 /// \param NDecl the declaration being called, if available
   3940 ExprResult
   3941 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   3942                             SourceLocation LParenLoc,
   3943                             Expr **Args, unsigned NumArgs,
   3944                             SourceLocation RParenLoc,
   3945                             Expr *Config, bool IsExecConfig) {
   3946   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
   3947   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
   3948 
   3949   // Promote the function operand.
   3950   // We special-case function promotion here because we only allow promoting
   3951   // builtin functions to function pointers in the callee of a call.
   3952   ExprResult Result;
   3953   if (BuiltinID &&
   3954       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
   3955     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
   3956                                CK_BuiltinFnToFnPtr).take();
   3957   } else {
   3958     Result = UsualUnaryConversions(Fn);
   3959   }
   3960   if (Result.isInvalid())
   3961     return ExprError();
   3962   Fn = Result.take();
   3963 
   3964   // Make the call expr early, before semantic checks.  This guarantees cleanup
   3965   // of arguments and function on error.
   3966   CallExpr *TheCall;
   3967   if (Config)
   3968     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
   3969                                                cast<CallExpr>(Config),
   3970                                                llvm::makeArrayRef(Args,NumArgs),
   3971                                                Context.BoolTy,
   3972                                                VK_RValue,
   3973                                                RParenLoc);
   3974   else
   3975     TheCall = new (Context) CallExpr(Context, Fn,
   3976                                      llvm::makeArrayRef(Args, NumArgs),
   3977                                      Context.BoolTy,
   3978                                      VK_RValue,
   3979                                      RParenLoc);
   3980 
   3981   // Bail out early if calling a builtin with custom typechecking.
   3982   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
   3983     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
   3984 
   3985  retry:
   3986   const FunctionType *FuncT;
   3987   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
   3988     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
   3989     // have type pointer to function".
   3990     FuncT = PT->getPointeeType()->getAs<FunctionType>();
   3991     if (FuncT == 0)
   3992       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
   3993                          << Fn->getType() << Fn->getSourceRange());
   3994   } else if (const BlockPointerType *BPT =
   3995                Fn->getType()->getAs<BlockPointerType>()) {
   3996     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
   3997   } else {
   3998     // Handle calls to expressions of unknown-any type.
   3999     if (Fn->getType() == Context.UnknownAnyTy) {
   4000       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
   4001       if (rewrite.isInvalid()) return ExprError();
   4002       Fn = rewrite.take();
   4003       TheCall->setCallee(Fn);
   4004       goto retry;
   4005     }
   4006 
   4007     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
   4008       << Fn->getType() << Fn->getSourceRange());
   4009   }
   4010 
   4011   if (getLangOpts().CUDA) {
   4012     if (Config) {
   4013       // CUDA: Kernel calls must be to global functions
   4014       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
   4015         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
   4016             << FDecl->getName() << Fn->getSourceRange());
   4017 
   4018       // CUDA: Kernel function must have 'void' return type
   4019       if (!FuncT->getResultType()->isVoidType())
   4020         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
   4021             << Fn->getType() << Fn->getSourceRange());
   4022     } else {
   4023       // CUDA: Calls to global functions must be configured
   4024       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
   4025         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
   4026             << FDecl->getName() << Fn->getSourceRange());
   4027     }
   4028   }
   4029 
   4030   // Check for a valid return type
   4031   if (CheckCallReturnType(FuncT->getResultType(),
   4032                           Fn->getLocStart(), TheCall,
   4033                           FDecl))
   4034     return ExprError();
   4035 
   4036   // We know the result type of the call, set it.
   4037   TheCall->setType(FuncT->getCallResultType(Context));
   4038   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
   4039 
   4040   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
   4041   if (Proto) {
   4042     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
   4043                                 RParenLoc, IsExecConfig))
   4044       return ExprError();
   4045   } else {
   4046     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
   4047 
   4048     if (FDecl) {
   4049       // Check if we have too few/too many template arguments, based
   4050       // on our knowledge of the function definition.
   4051       const FunctionDecl *Def = 0;
   4052       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
   4053         Proto = Def->getType()->getAs<FunctionProtoType>();
   4054         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
   4055           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
   4056             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
   4057       }
   4058 
   4059       // If the function we're calling isn't a function prototype, but we have
   4060       // a function prototype from a prior declaratiom, use that prototype.
   4061       if (!FDecl->hasPrototype())
   4062         Proto = FDecl->getType()->getAs<FunctionProtoType>();
   4063     }
   4064 
   4065     // Promote the arguments (C99 6.5.2.2p6).
   4066     for (unsigned i = 0; i != NumArgs; i++) {
   4067       Expr *Arg = Args[i];
   4068 
   4069       if (Proto && i < Proto->getNumArgs()) {
   4070         InitializedEntity Entity
   4071           = InitializedEntity::InitializeParameter(Context,
   4072                                                    Proto->getArgType(i),
   4073                                                    Proto->isArgConsumed(i));
   4074         ExprResult ArgE = PerformCopyInitialization(Entity,
   4075                                                     SourceLocation(),
   4076                                                     Owned(Arg));
   4077         if (ArgE.isInvalid())
   4078           return true;
   4079 
   4080         Arg = ArgE.takeAs<Expr>();
   4081 
   4082       } else {
   4083         ExprResult ArgE = DefaultArgumentPromotion(Arg);
   4084 
   4085         if (ArgE.isInvalid())
   4086           return true;
   4087 
   4088         Arg = ArgE.takeAs<Expr>();
   4089       }
   4090 
   4091       if (RequireCompleteType(Arg->getLocStart(),
   4092                               Arg->getType(),
   4093                               diag::err_call_incomplete_argument, Arg))
   4094         return ExprError();
   4095 
   4096       TheCall->setArg(i, Arg);
   4097     }
   4098   }
   4099 
   4100   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
   4101     if (!Method->isStatic())
   4102       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
   4103         << Fn->getSourceRange());
   4104 
   4105   // Check for sentinels
   4106   if (NDecl)
   4107     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
   4108 
   4109   // Do special checking on direct calls to functions.
   4110   if (FDecl) {
   4111     if (CheckFunctionCall(FDecl, TheCall, Proto))
   4112       return ExprError();
   4113 
   4114     if (BuiltinID)
   4115       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
   4116   } else if (NDecl) {
   4117     if (CheckBlockCall(NDecl, TheCall, Proto))
   4118       return ExprError();
   4119   }
   4120 
   4121   return MaybeBindToTemporary(TheCall);
   4122 }
   4123 
   4124 ExprResult
   4125 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
   4126                            SourceLocation RParenLoc, Expr *InitExpr) {
   4127   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
   4128   // FIXME: put back this assert when initializers are worked out.
   4129   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
   4130 
   4131   TypeSourceInfo *TInfo;
   4132   QualType literalType = GetTypeFromParser(Ty, &TInfo);
   4133   if (!TInfo)
   4134     TInfo = Context.getTrivialTypeSourceInfo(literalType);
   4135 
   4136   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
   4137 }
   4138 
   4139 ExprResult
   4140 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
   4141                                SourceLocation RParenLoc, Expr *LiteralExpr) {
   4142   QualType literalType = TInfo->getType();
   4143 
   4144   if (literalType->isArrayType()) {
   4145     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
   4146           diag::err_illegal_decl_array_incomplete_type,
   4147           SourceRange(LParenLoc,
   4148                       LiteralExpr->getSourceRange().getEnd())))
   4149       return ExprError();
   4150     if (literalType->isVariableArrayType())
   4151       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
   4152         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
   4153   } else if (!literalType->isDependentType() &&
   4154              RequireCompleteType(LParenLoc, literalType,
   4155                diag::err_typecheck_decl_incomplete_type,
   4156                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
   4157     return ExprError();
   4158 
   4159   InitializedEntity Entity
   4160     = InitializedEntity::InitializeTemporary(literalType);
   4161   InitializationKind Kind
   4162     = InitializationKind::CreateCStyleCast(LParenLoc,
   4163                                            SourceRange(LParenLoc, RParenLoc),
   4164                                            /*InitList=*/true);
   4165   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
   4166   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
   4167                                       &literalType);
   4168   if (Result.isInvalid())
   4169     return ExprError();
   4170   LiteralExpr = Result.get();
   4171 
   4172   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
   4173   if (isFileScope) { // 6.5.2.5p3
   4174     if (CheckForConstantInitializer(LiteralExpr, literalType))
   4175       return ExprError();
   4176   }
   4177 
   4178   // In C, compound literals are l-values for some reason.
   4179   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
   4180 
   4181   return MaybeBindToTemporary(
   4182            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
   4183                                              VK, LiteralExpr, isFileScope));
   4184 }
   4185 
   4186 ExprResult
   4187 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
   4188                     SourceLocation RBraceLoc) {
   4189   // Immediately handle non-overload placeholders.  Overloads can be
   4190   // resolved contextually, but everything else here can't.
   4191   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
   4192     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
   4193       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
   4194 
   4195       // Ignore failures; dropping the entire initializer list because
   4196       // of one failure would be terrible for indexing/etc.
   4197       if (result.isInvalid()) continue;
   4198 
   4199       InitArgList[I] = result.take();
   4200     }
   4201   }
   4202 
   4203   // Semantic analysis for initializers is done by ActOnDeclarator() and
   4204   // CheckInitializer() - it requires knowledge of the object being intialized.
   4205 
   4206   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
   4207                                                RBraceLoc);
   4208   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
   4209   return Owned(E);
   4210 }
   4211 
   4212 /// Do an explicit extend of the given block pointer if we're in ARC.
   4213 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
   4214   assert(E.get()->getType()->isBlockPointerType());
   4215   assert(E.get()->isRValue());
   4216 
   4217   // Only do this in an r-value context.
   4218   if (!S.getLangOpts().ObjCAutoRefCount) return;
   4219 
   4220   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
   4221                                CK_ARCExtendBlockObject, E.get(),
   4222                                /*base path*/ 0, VK_RValue);
   4223   S.ExprNeedsCleanups = true;
   4224 }
   4225 
   4226 /// Prepare a conversion of the given expression to an ObjC object
   4227 /// pointer type.
   4228 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
   4229   QualType type = E.get()->getType();
   4230   if (type->isObjCObjectPointerType()) {
   4231     return CK_BitCast;
   4232   } else if (type->isBlockPointerType()) {
   4233     maybeExtendBlockObject(*this, E);
   4234     return CK_BlockPointerToObjCPointerCast;
   4235   } else {
   4236     assert(type->isPointerType());
   4237     return CK_CPointerToObjCPointerCast;
   4238   }
   4239 }
   4240 
   4241 /// Prepares for a scalar cast, performing all the necessary stages
   4242 /// except the final cast and returning the kind required.
   4243 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
   4244   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
   4245   // Also, callers should have filtered out the invalid cases with
   4246   // pointers.  Everything else should be possible.
   4247 
   4248   QualType SrcTy = Src.get()->getType();
   4249   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
   4250     return CK_NoOp;
   4251 
   4252   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
   4253   case Type::STK_MemberPointer:
   4254     llvm_unreachable("member pointer type in C");
   4255 
   4256   case Type::STK_CPointer:
   4257   case Type::STK_BlockPointer:
   4258   case Type::STK_ObjCObjectPointer:
   4259     switch (DestTy->getScalarTypeKind()) {
   4260     case Type::STK_CPointer:
   4261       return CK_BitCast;
   4262     case Type::STK_BlockPointer:
   4263       return (SrcKind == Type::STK_BlockPointer
   4264                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
   4265     case Type::STK_ObjCObjectPointer:
   4266       if (SrcKind == Type::STK_ObjCObjectPointer)
   4267         return CK_BitCast;
   4268       if (SrcKind == Type::STK_CPointer)
   4269         return CK_CPointerToObjCPointerCast;
   4270       maybeExtendBlockObject(*this, Src);
   4271       return CK_BlockPointerToObjCPointerCast;
   4272     case Type::STK_Bool:
   4273       return CK_PointerToBoolean;
   4274     case Type::STK_Integral:
   4275       return CK_PointerToIntegral;
   4276     case Type::STK_Floating:
   4277     case Type::STK_FloatingComplex:
   4278     case Type::STK_IntegralComplex:
   4279     case Type::STK_MemberPointer:
   4280       llvm_unreachable("illegal cast from pointer");
   4281     }
   4282     llvm_unreachable("Should have returned before this");
   4283 
   4284   case Type::STK_Bool: // casting from bool is like casting from an integer
   4285   case Type::STK_Integral:
   4286     switch (DestTy->getScalarTypeKind()) {
   4287     case Type::STK_CPointer:
   4288     case Type::STK_ObjCObjectPointer:
   4289     case Type::STK_BlockPointer:
   4290       if (Src.get()->isNullPointerConstant(Context,
   4291                                            Expr::NPC_ValueDependentIsNull))
   4292         return CK_NullToPointer;
   4293       return CK_IntegralToPointer;
   4294     case Type::STK_Bool:
   4295       return CK_IntegralToBoolean;
   4296     case Type::STK_Integral:
   4297       return CK_IntegralCast;
   4298     case Type::STK_Floating:
   4299       return CK_IntegralToFloating;
   4300     case Type::STK_IntegralComplex:
   4301       Src = ImpCastExprToType(Src.take(),
   4302                               DestTy->castAs<ComplexType>()->getElementType(),
   4303                               CK_IntegralCast);
   4304       return CK_IntegralRealToComplex;
   4305     case Type::STK_FloatingComplex:
   4306       Src = ImpCastExprToType(Src.take(),
   4307                               DestTy->castAs<ComplexType>()->getElementType(),
   4308                               CK_IntegralToFloating);
   4309       return CK_FloatingRealToComplex;
   4310     case Type::STK_MemberPointer:
   4311       llvm_unreachable("member pointer type in C");
   4312     }
   4313     llvm_unreachable("Should have returned before this");
   4314 
   4315   case Type::STK_Floating:
   4316     switch (DestTy->getScalarTypeKind()) {
   4317     case Type::STK_Floating:
   4318       return CK_FloatingCast;
   4319     case Type::STK_Bool:
   4320       return CK_FloatingToBoolean;
   4321     case Type::STK_Integral:
   4322       return CK_FloatingToIntegral;
   4323     case Type::STK_FloatingComplex:
   4324       Src = ImpCastExprToType(Src.take(),
   4325                               DestTy->castAs<ComplexType>()->getElementType(),
   4326                               CK_FloatingCast);
   4327       return CK_FloatingRealToComplex;
   4328     case Type::STK_IntegralComplex:
   4329       Src = ImpCastExprToType(Src.take(),
   4330                               DestTy->castAs<ComplexType>()->getElementType(),
   4331                               CK_FloatingToIntegral);
   4332       return CK_IntegralRealToComplex;
   4333     case Type::STK_CPointer:
   4334     case Type::STK_ObjCObjectPointer:
   4335     case Type::STK_BlockPointer:
   4336       llvm_unreachable("valid float->pointer cast?");
   4337     case Type::STK_MemberPointer:
   4338       llvm_unreachable("member pointer type in C");
   4339     }
   4340     llvm_unreachable("Should have returned before this");
   4341 
   4342   case Type::STK_FloatingComplex:
   4343     switch (DestTy->getScalarTypeKind()) {
   4344     case Type::STK_FloatingComplex:
   4345       return CK_FloatingComplexCast;
   4346     case Type::STK_IntegralComplex:
   4347       return CK_FloatingComplexToIntegralComplex;
   4348     case Type::STK_Floating: {
   4349       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
   4350       if (Context.hasSameType(ET, DestTy))
   4351         return CK_FloatingComplexToReal;
   4352       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
   4353       return CK_FloatingCast;
   4354     }
   4355     case Type::STK_Bool:
   4356       return CK_FloatingComplexToBoolean;
   4357     case Type::STK_Integral:
   4358       Src = ImpCastExprToType(Src.take(),
   4359                               SrcTy->castAs<ComplexType>()->getElementType(),
   4360                               CK_FloatingComplexToReal);
   4361       return CK_FloatingToIntegral;
   4362     case Type::STK_CPointer:
   4363     case Type::STK_ObjCObjectPointer:
   4364     case Type::STK_BlockPointer:
   4365       llvm_unreachable("valid complex float->pointer cast?");
   4366     case Type::STK_MemberPointer:
   4367       llvm_unreachable("member pointer type in C");
   4368     }
   4369     llvm_unreachable("Should have returned before this");
   4370 
   4371   case Type::STK_IntegralComplex:
   4372     switch (DestTy->getScalarTypeKind()) {
   4373     case Type::STK_FloatingComplex:
   4374       return CK_IntegralComplexToFloatingComplex;
   4375     case Type::STK_IntegralComplex:
   4376       return CK_IntegralComplexCast;
   4377     case Type::STK_Integral: {
   4378       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
   4379       if (Context.hasSameType(ET, DestTy))
   4380         return CK_IntegralComplexToReal;
   4381       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
   4382       return CK_IntegralCast;
   4383     }
   4384     case Type::STK_Bool:
   4385       return CK_IntegralComplexToBoolean;
   4386     case Type::STK_Floating:
   4387       Src = ImpCastExprToType(Src.take(),
   4388                               SrcTy->castAs<ComplexType>()->getElementType(),
   4389                               CK_IntegralComplexToReal);
   4390       return CK_IntegralToFloating;
   4391     case Type::STK_CPointer:
   4392     case Type::STK_ObjCObjectPointer:
   4393     case Type::STK_BlockPointer:
   4394       llvm_unreachable("valid complex int->pointer cast?");
   4395     case Type::STK_MemberPointer:
   4396       llvm_unreachable("member pointer type in C");
   4397     }
   4398     llvm_unreachable("Should have returned before this");
   4399   }
   4400 
   4401   llvm_unreachable("Unhandled scalar cast");
   4402 }
   4403 
   4404 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
   4405                            CastKind &Kind) {
   4406   assert(VectorTy->isVectorType() && "Not a vector type!");
   4407 
   4408   if (Ty->isVectorType() || Ty->isIntegerType()) {
   4409     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
   4410       return Diag(R.getBegin(),
   4411                   Ty->isVectorType() ?
   4412                   diag::err_invalid_conversion_between_vectors :
   4413                   diag::err_invalid_conversion_between_vector_and_integer)
   4414         << VectorTy << Ty << R;
   4415   } else
   4416     return Diag(R.getBegin(),
   4417                 diag::err_invalid_conversion_between_vector_and_scalar)
   4418       << VectorTy << Ty << R;
   4419 
   4420   Kind = CK_BitCast;
   4421   return false;
   4422 }
   4423 
   4424 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
   4425                                     Expr *CastExpr, CastKind &Kind) {
   4426   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
   4427 
   4428   QualType SrcTy = CastExpr->getType();
   4429 
   4430   // If SrcTy is a VectorType, the total size must match to explicitly cast to
   4431   // an ExtVectorType.
   4432   // In OpenCL, casts between vectors of different types are not allowed.
   4433   // (See OpenCL 6.2).
   4434   if (SrcTy->isVectorType()) {
   4435     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
   4436         || (getLangOpts().OpenCL &&
   4437             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
   4438       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
   4439         << DestTy << SrcTy << R;
   4440       return ExprError();
   4441     }
   4442     Kind = CK_BitCast;
   4443     return Owned(CastExpr);
   4444   }
   4445 
   4446   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
   4447   // conversion will take place first from scalar to elt type, and then
   4448   // splat from elt type to vector.
   4449   if (SrcTy->isPointerType())
   4450     return Diag(R.getBegin(),
   4451                 diag::err_invalid_conversion_between_vector_and_scalar)
   4452       << DestTy << SrcTy << R;
   4453 
   4454   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
   4455   ExprResult CastExprRes = Owned(CastExpr);
   4456   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
   4457   if (CastExprRes.isInvalid())
   4458     return ExprError();
   4459   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
   4460 
   4461   Kind = CK_VectorSplat;
   4462   return Owned(CastExpr);
   4463 }
   4464 
   4465 ExprResult
   4466 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
   4467                     Declarator &D, ParsedType &Ty,
   4468                     SourceLocation RParenLoc, Expr *CastExpr) {
   4469   assert(!D.isInvalidType() && (CastExpr != 0) &&
   4470          "ActOnCastExpr(): missing type or expr");
   4471 
   4472   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
   4473   if (D.isInvalidType())
   4474     return ExprError();
   4475 
   4476   if (getLangOpts().CPlusPlus) {
   4477     // Check that there are no default arguments (C++ only).
   4478     CheckExtraCXXDefaultArguments(D);
   4479   }
   4480 
   4481   checkUnusedDeclAttributes(D);
   4482 
   4483   QualType castType = castTInfo->getType();
   4484   Ty = CreateParsedType(castType, castTInfo);
   4485 
   4486   bool isVectorLiteral = false;
   4487 
   4488   // Check for an altivec or OpenCL literal,
   4489   // i.e. all the elements are integer constants.
   4490   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
   4491   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
   4492   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
   4493        && castType->isVectorType() && (PE || PLE)) {
   4494     if (PLE && PLE->getNumExprs() == 0) {
   4495       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
   4496       return ExprError();
   4497     }
   4498     if (PE || PLE->getNumExprs() == 1) {
   4499       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
   4500       if (!E->getType()->isVectorType())
   4501         isVectorLiteral = true;
   4502     }
   4503     else
   4504       isVectorLiteral = true;
   4505   }
   4506 
   4507   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
   4508   // then handle it as such.
   4509   if (isVectorLiteral)
   4510     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
   4511 
   4512   // If the Expr being casted is a ParenListExpr, handle it specially.
   4513   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
   4514   // sequence of BinOp comma operators.
   4515   if (isa<ParenListExpr>(CastExpr)) {
   4516     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
   4517     if (Result.isInvalid()) return ExprError();
   4518     CastExpr = Result.take();
   4519   }
   4520 
   4521   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
   4522 }
   4523 
   4524 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
   4525                                     SourceLocation RParenLoc, Expr *E,
   4526                                     TypeSourceInfo *TInfo) {
   4527   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
   4528          "Expected paren or paren list expression");
   4529 
   4530   Expr **exprs;
   4531   unsigned numExprs;
   4532   Expr *subExpr;
   4533   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
   4534     exprs = PE->getExprs();
   4535     numExprs = PE->getNumExprs();
   4536   } else {
   4537     subExpr = cast<ParenExpr>(E)->getSubExpr();
   4538     exprs = &subExpr;
   4539     numExprs = 1;
   4540   }
   4541 
   4542   QualType Ty = TInfo->getType();
   4543   assert(Ty->isVectorType() && "Expected vector type");
   4544 
   4545   SmallVector<Expr *, 8> initExprs;
   4546   const VectorType *VTy = Ty->getAs<VectorType>();
   4547   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
   4548 
   4549   // '(...)' form of vector initialization in AltiVec: the number of
   4550   // initializers must be one or must match the size of the vector.
   4551   // If a single value is specified in the initializer then it will be
   4552   // replicated to all the components of the vector
   4553   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
   4554     // The number of initializers must be one or must match the size of the
   4555     // vector. If a single value is specified in the initializer then it will
   4556     // be replicated to all the components of the vector
   4557     if (numExprs == 1) {
   4558       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
   4559       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
   4560       if (Literal.isInvalid())
   4561         return ExprError();
   4562       Literal = ImpCastExprToType(Literal.take(), ElemTy,
   4563                                   PrepareScalarCast(Literal, ElemTy));
   4564       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
   4565     }
   4566     else if (numExprs < numElems) {
   4567       Diag(E->getExprLoc(),
   4568            diag::err_incorrect_number_of_vector_initializers);
   4569       return ExprError();
   4570     }
   4571     else
   4572       initExprs.append(exprs, exprs + numExprs);
   4573   }
   4574   else {
   4575     // For OpenCL, when the number of initializers is a single value,
   4576     // it will be replicated to all components of the vector.
   4577     if (getLangOpts().OpenCL &&
   4578         VTy->getVectorKind() == VectorType::GenericVector &&
   4579         numExprs == 1) {
   4580         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
   4581         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
   4582         if (Literal.isInvalid())
   4583           return ExprError();
   4584         Literal = ImpCastExprToType(Literal.take(), ElemTy,
   4585                                     PrepareScalarCast(Literal, ElemTy));
   4586         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
   4587     }
   4588 
   4589     initExprs.append(exprs, exprs + numExprs);
   4590   }
   4591   // FIXME: This means that pretty-printing the final AST will produce curly
   4592   // braces instead of the original commas.
   4593   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
   4594                                                    initExprs, RParenLoc);
   4595   initE->setType(Ty);
   4596   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
   4597 }
   4598 
   4599 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
   4600 /// the ParenListExpr into a sequence of comma binary operators.
   4601 ExprResult
   4602 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
   4603   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
   4604   if (!E)
   4605     return Owned(OrigExpr);
   4606 
   4607   ExprResult Result(E->getExpr(0));
   4608 
   4609   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
   4610     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
   4611                         E->getExpr(i));
   4612 
   4613   if (Result.isInvalid()) return ExprError();
   4614 
   4615   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
   4616 }
   4617 
   4618 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
   4619                                     SourceLocation R,
   4620                                     MultiExprArg Val) {
   4621   assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
   4622   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
   4623   return Owned(expr);
   4624 }
   4625 
   4626 /// \brief Emit a specialized diagnostic when one expression is a null pointer
   4627 /// constant and the other is not a pointer.  Returns true if a diagnostic is
   4628 /// emitted.
   4629 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
   4630                                       SourceLocation QuestionLoc) {
   4631   Expr *NullExpr = LHSExpr;
   4632   Expr *NonPointerExpr = RHSExpr;
   4633   Expr::NullPointerConstantKind NullKind =
   4634       NullExpr->isNullPointerConstant(Context,
   4635                                       Expr::NPC_ValueDependentIsNotNull);
   4636 
   4637   if (NullKind == Expr::NPCK_NotNull) {
   4638     NullExpr = RHSExpr;
   4639     NonPointerExpr = LHSExpr;
   4640     NullKind =
   4641         NullExpr->isNullPointerConstant(Context,
   4642                                         Expr::NPC_ValueDependentIsNotNull);
   4643   }
   4644 
   4645   if (NullKind == Expr::NPCK_NotNull)
   4646     return false;
   4647 
   4648   if (NullKind == Expr::NPCK_ZeroExpression)
   4649     return false;
   4650 
   4651   if (NullKind == Expr::NPCK_ZeroLiteral) {
   4652     // In this case, check to make sure that we got here from a "NULL"
   4653     // string in the source code.
   4654     NullExpr = NullExpr->IgnoreParenImpCasts();
   4655     SourceLocation loc = NullExpr->getExprLoc();
   4656     if (!findMacroSpelling(loc, "NULL"))
   4657       return false;
   4658   }
   4659 
   4660   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
   4661   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
   4662       << NonPointerExpr->getType() << DiagType
   4663       << NonPointerExpr->getSourceRange();
   4664   return true;
   4665 }
   4666 
   4667 /// \brief Return false if the condition expression is valid, true otherwise.
   4668 static bool checkCondition(Sema &S, Expr *Cond) {
   4669   QualType CondTy = Cond->getType();
   4670 
   4671   // C99 6.5.15p2
   4672   if (CondTy->isScalarType()) return false;
   4673 
   4674   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
   4675   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
   4676     return false;
   4677 
   4678   // Emit the proper error message.
   4679   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
   4680                               diag::err_typecheck_cond_expect_scalar :
   4681                               diag::err_typecheck_cond_expect_scalar_or_vector)
   4682     << CondTy;
   4683   return true;
   4684 }
   4685 
   4686 /// \brief Return false if the two expressions can be converted to a vector,
   4687 /// true otherwise
   4688 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
   4689                                                     ExprResult &RHS,
   4690                                                     QualType CondTy) {
   4691   // Both operands should be of scalar type.
   4692   if (!LHS.get()->getType()->isScalarType()) {
   4693     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
   4694       << CondTy;
   4695     return true;
   4696   }
   4697   if (!RHS.get()->getType()->isScalarType()) {
   4698     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
   4699       << CondTy;
   4700     return true;
   4701   }
   4702 
   4703   // Implicity convert these scalars to the type of the condition.
   4704   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
   4705   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
   4706   return false;
   4707 }
   4708 
   4709 /// \brief Handle when one or both operands are void type.
   4710 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
   4711                                          ExprResult &RHS) {
   4712     Expr *LHSExpr = LHS.get();
   4713     Expr *RHSExpr = RHS.get();
   4714 
   4715     if (!LHSExpr->getType()->isVoidType())
   4716       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
   4717         << RHSExpr->getSourceRange();
   4718     if (!RHSExpr->getType()->isVoidType())
   4719       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
   4720         << LHSExpr->getSourceRange();
   4721     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
   4722     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
   4723     return S.Context.VoidTy;
   4724 }
   4725 
   4726 /// \brief Return false if the NullExpr can be promoted to PointerTy,
   4727 /// true otherwise.
   4728 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
   4729                                         QualType PointerTy) {
   4730   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
   4731       !NullExpr.get()->isNullPointerConstant(S.Context,
   4732                                             Expr::NPC_ValueDependentIsNull))
   4733     return true;
   4734 
   4735   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
   4736   return false;
   4737 }
   4738 
   4739 /// \brief Checks compatibility between two pointers and return the resulting
   4740 /// type.
   4741 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
   4742                                                      ExprResult &RHS,
   4743                                                      SourceLocation Loc) {
   4744   QualType LHSTy = LHS.get()->getType();
   4745   QualType RHSTy = RHS.get()->getType();
   4746 
   4747   if (S.Context.hasSameType(LHSTy, RHSTy)) {
   4748     // Two identical pointers types are always compatible.
   4749     return LHSTy;
   4750   }
   4751 
   4752   QualType lhptee, rhptee;
   4753 
   4754   // Get the pointee types.
   4755   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
   4756     lhptee = LHSBTy->getPointeeType();
   4757     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
   4758   } else {
   4759     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
   4760     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
   4761   }
   4762 
   4763   // C99 6.5.15p6: If both operands are pointers to compatible types or to
   4764   // differently qualified versions of compatible types, the result type is
   4765   // a pointer to an appropriately qualified version of the composite
   4766   // type.
   4767 
   4768   // Only CVR-qualifiers exist in the standard, and the differently-qualified
   4769   // clause doesn't make sense for our extensions. E.g. address space 2 should
   4770   // be incompatible with address space 3: they may live on different devices or
   4771   // anything.
   4772   Qualifiers lhQual = lhptee.getQualifiers();
   4773   Qualifiers rhQual = rhptee.getQualifiers();
   4774 
   4775   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
   4776   lhQual.removeCVRQualifiers();
   4777   rhQual.removeCVRQualifiers();
   4778 
   4779   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
   4780   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
   4781 
   4782   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
   4783 
   4784   if (CompositeTy.isNull()) {
   4785     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
   4786       << LHSTy << RHSTy << LHS.get()->getSourceRange()
   4787       << RHS.get()->getSourceRange();
   4788     // In this situation, we assume void* type. No especially good
   4789     // reason, but this is what gcc does, and we do have to pick
   4790     // to get a consistent AST.
   4791     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
   4792     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
   4793     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
   4794     return incompatTy;
   4795   }
   4796 
   4797   // The pointer types are compatible.
   4798   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
   4799   ResultTy = S.Context.getPointerType(ResultTy);
   4800 
   4801   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
   4802   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
   4803   return ResultTy;
   4804 }
   4805 
   4806 /// \brief Return the resulting type when the operands are both block pointers.
   4807 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
   4808                                                           ExprResult &LHS,
   4809                                                           ExprResult &RHS,
   4810                                                           SourceLocation Loc) {
   4811   QualType LHSTy = LHS.get()->getType();
   4812   QualType RHSTy = RHS.get()->getType();
   4813 
   4814   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
   4815     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
   4816       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
   4817       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
   4818       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
   4819       return destType;
   4820     }
   4821     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
   4822       << LHSTy << RHSTy << LHS.get()->getSourceRange()
   4823       << RHS.get()->getSourceRange();
   4824     return QualType();
   4825   }
   4826 
   4827   // We have 2 block pointer types.
   4828   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
   4829 }
   4830 
   4831 /// \brief Return the resulting type when the operands are both pointers.
   4832 static QualType
   4833 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
   4834                                             ExprResult &RHS,
   4835                                             SourceLocation Loc) {
   4836   // get the pointer types
   4837   QualType LHSTy = LHS.get()->getType();
   4838   QualType RHSTy = RHS.get()->getType();
   4839 
   4840   // get the "pointed to" types
   4841   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
   4842   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
   4843 
   4844   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
   4845   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
   4846     // Figure out necessary qualifiers (C99 6.5.15p6)
   4847     QualType destPointee
   4848       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
   4849     QualType destType = S.Context.getPointerType(destPointee);
   4850     // Add qualifiers if necessary.
   4851     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
   4852     // Promote to void*.
   4853     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
   4854     return destType;
   4855   }
   4856   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
   4857     QualType destPointee
   4858       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
   4859     QualType destType = S.Context.getPointerType(destPointee);
   4860     // Add qualifiers if necessary.
   4861     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
   4862     // Promote to void*.
   4863     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
   4864     return destType;
   4865   }
   4866 
   4867   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
   4868 }
   4869 
   4870 /// \brief Return false if the first expression is not an integer and the second
   4871 /// expression is not a pointer, true otherwise.
   4872 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
   4873                                         Expr* PointerExpr, SourceLocation Loc,
   4874                                         bool IsIntFirstExpr) {
   4875   if (!PointerExpr->getType()->isPointerType() ||
   4876       !Int.get()->getType()->isIntegerType())
   4877     return false;
   4878 
   4879   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
   4880   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
   4881 
   4882   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
   4883     << Expr1->getType() << Expr2->getType()
   4884     << Expr1->getSourceRange() << Expr2->getSourceRange();
   4885   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
   4886                             CK_IntegralToPointer);
   4887   return true;
   4888 }
   4889 
   4890 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
   4891 /// In that case, LHS = cond.
   4892 /// C99 6.5.15
   4893 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
   4894                                         ExprResult &RHS, ExprValueKind &VK,
   4895                                         ExprObjectKind &OK,
   4896                                         SourceLocation QuestionLoc) {
   4897 
   4898   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
   4899   if (!LHSResult.isUsable()) return QualType();
   4900   LHS = LHSResult;
   4901 
   4902   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
   4903   if (!RHSResult.isUsable()) return QualType();
   4904   RHS = RHSResult;
   4905 
   4906   // C++ is sufficiently different to merit its own checker.
   4907   if (getLangOpts().CPlusPlus)
   4908     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
   4909 
   4910   VK = VK_RValue;
   4911   OK = OK_Ordinary;
   4912 
   4913   Cond = UsualUnaryConversions(Cond.take());
   4914   if (Cond.isInvalid())
   4915     return QualType();
   4916   LHS = UsualUnaryConversions(LHS.take());
   4917   if (LHS.isInvalid())
   4918     return QualType();
   4919   RHS = UsualUnaryConversions(RHS.take());
   4920   if (RHS.isInvalid())
   4921     return QualType();
   4922 
   4923   QualType CondTy = Cond.get()->getType();
   4924   QualType LHSTy = LHS.get()->getType();
   4925   QualType RHSTy = RHS.get()->getType();
   4926 
   4927   // first, check the condition.
   4928   if (checkCondition(*this, Cond.get()))
   4929     return QualType();
   4930 
   4931   // Now check the two expressions.
   4932   if (LHSTy->isVectorType() || RHSTy->isVectorType())
   4933     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
   4934 
   4935   // OpenCL: If the condition is a vector, and both operands are scalar,
   4936   // attempt to implicity convert them to the vector type to act like the
   4937   // built in select.
   4938   if (getLangOpts().OpenCL && CondTy->isVectorType())
   4939     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
   4940       return QualType();
   4941 
   4942   // If both operands have arithmetic type, do the usual arithmetic conversions
   4943   // to find a common type: C99 6.5.15p3,5.
   4944   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
   4945     UsualArithmeticConversions(LHS, RHS);
   4946     if (LHS.isInvalid() || RHS.isInvalid())
   4947       return QualType();
   4948     return LHS.get()->getType();
   4949   }
   4950 
   4951   // If both operands are the same structure or union type, the result is that
   4952   // type.
   4953   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
   4954     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
   4955       if (LHSRT->getDecl() == RHSRT->getDecl())
   4956         // "If both the operands have structure or union type, the result has
   4957         // that type."  This implies that CV qualifiers are dropped.
   4958         return LHSTy.getUnqualifiedType();
   4959     // FIXME: Type of conditional expression must be complete in C mode.
   4960   }
   4961 
   4962   // C99 6.5.15p5: "If both operands have void type, the result has void type."
   4963   // The following || allows only one side to be void (a GCC-ism).
   4964   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
   4965     return checkConditionalVoidType(*this, LHS, RHS);
   4966   }
   4967 
   4968   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
   4969   // the type of the other operand."
   4970   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
   4971   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
   4972 
   4973   // All objective-c pointer type analysis is done here.
   4974   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
   4975                                                         QuestionLoc);
   4976   if (LHS.isInvalid() || RHS.isInvalid())
   4977     return QualType();
   4978   if (!compositeType.isNull())
   4979     return compositeType;
   4980 
   4981 
   4982   // Handle block pointer types.
   4983   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
   4984     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
   4985                                                      QuestionLoc);
   4986 
   4987   // Check constraints for C object pointers types (C99 6.5.15p3,6).
   4988   if (LHSTy->isPointerType() && RHSTy->isPointerType())
   4989     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
   4990                                                        QuestionLoc);
   4991 
   4992   // GCC compatibility: soften pointer/integer mismatch.  Note that
   4993   // null pointers have been filtered out by this point.
   4994   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
   4995       /*isIntFirstExpr=*/true))
   4996     return RHSTy;
   4997   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
   4998       /*isIntFirstExpr=*/false))
   4999     return LHSTy;
   5000 
   5001   // Emit a better diagnostic if one of the expressions is a null pointer
   5002   // constant and the other is not a pointer type. In this case, the user most
   5003   // likely forgot to take the address of the other expression.
   5004   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
   5005     return QualType();
   5006 
   5007   // Otherwise, the operands are not compatible.
   5008   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
   5009     << LHSTy << RHSTy << LHS.get()->getSourceRange()
   5010     << RHS.get()->getSourceRange();
   5011   return QualType();
   5012 }
   5013 
   5014 /// FindCompositeObjCPointerType - Helper method to find composite type of
   5015 /// two objective-c pointer types of the two input expressions.
   5016 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
   5017                                             SourceLocation QuestionLoc) {
   5018   QualType LHSTy = LHS.get()->getType();
   5019   QualType RHSTy = RHS.get()->getType();
   5020 
   5021   // Handle things like Class and struct objc_class*.  Here we case the result
   5022   // to the pseudo-builtin, because that will be implicitly cast back to the
   5023   // redefinition type if an attempt is made to access its fields.
   5024   if (LHSTy->isObjCClassType() &&
   5025       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
   5026     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
   5027     return LHSTy;
   5028   }
   5029   if (RHSTy->isObjCClassType() &&
   5030       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
   5031     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
   5032     return RHSTy;
   5033   }
   5034   // And the same for struct objc_object* / id
   5035   if (LHSTy->isObjCIdType() &&
   5036       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
   5037     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
   5038     return LHSTy;
   5039   }
   5040   if (RHSTy->isObjCIdType() &&
   5041       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
   5042     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
   5043     return RHSTy;
   5044   }
   5045   // And the same for struct objc_selector* / SEL
   5046   if (Context.isObjCSelType(LHSTy) &&
   5047       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
   5048     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
   5049     return LHSTy;
   5050   }
   5051   if (Context.isObjCSelType(RHSTy) &&
   5052       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
   5053     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
   5054     return RHSTy;
   5055   }
   5056   // Check constraints for Objective-C object pointers types.
   5057   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
   5058 
   5059     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
   5060       // Two identical object pointer types are always compatible.
   5061       return LHSTy;
   5062     }
   5063     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
   5064     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
   5065     QualType compositeType = LHSTy;
   5066 
   5067     // If both operands are interfaces and either operand can be
   5068     // assigned to the other, use that type as the composite
   5069     // type. This allows
   5070     //   xxx ? (A*) a : (B*) b
   5071     // where B is a subclass of A.
   5072     //
   5073     // Additionally, as for assignment, if either type is 'id'
   5074     // allow silent coercion. Finally, if the types are
   5075     // incompatible then make sure to use 'id' as the composite
   5076     // type so the result is acceptable for sending messages to.
   5077 
   5078     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
   5079     // It could return the composite type.
   5080     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
   5081       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
   5082     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
   5083       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
   5084     } else if ((LHSTy->isObjCQualifiedIdType() ||
   5085                 RHSTy->isObjCQualifiedIdType()) &&
   5086                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
   5087       // Need to handle "id<xx>" explicitly.
   5088       // GCC allows qualified id and any Objective-C type to devolve to
   5089       // id. Currently localizing to here until clear this should be
   5090       // part of ObjCQualifiedIdTypesAreCompatible.
   5091       compositeType = Context.getObjCIdType();
   5092     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
   5093       compositeType = Context.getObjCIdType();
   5094     } else if (!(compositeType =
   5095                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
   5096       ;
   5097     else {
   5098       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
   5099       << LHSTy << RHSTy
   5100       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   5101       QualType incompatTy = Context.getObjCIdType();
   5102       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
   5103       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
   5104       return incompatTy;
   5105     }
   5106     // The object pointer types are compatible.
   5107     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
   5108     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
   5109     return compositeType;
   5110   }
   5111   // Check Objective-C object pointer types and 'void *'
   5112   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
   5113     if (getLangOpts().ObjCAutoRefCount) {
   5114       // ARC forbids the implicit conversion of object pointers to 'void *',
   5115       // so these types are not compatible.
   5116       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
   5117           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   5118       LHS = RHS = true;
   5119       return QualType();
   5120     }
   5121     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
   5122     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
   5123     QualType destPointee
   5124     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
   5125     QualType destType = Context.getPointerType(destPointee);
   5126     // Add qualifiers if necessary.
   5127     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
   5128     // Promote to void*.
   5129     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
   5130     return destType;
   5131   }
   5132   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
   5133     if (getLangOpts().ObjCAutoRefCount) {
   5134       // ARC forbids the implicit conversion of object pointers to 'void *',
   5135       // so these types are not compatible.
   5136       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
   5137           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   5138       LHS = RHS = true;
   5139       return QualType();
   5140     }
   5141     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
   5142     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
   5143     QualType destPointee
   5144     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
   5145     QualType destType = Context.getPointerType(destPointee);
   5146     // Add qualifiers if necessary.
   5147     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
   5148     // Promote to void*.
   5149     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
   5150     return destType;
   5151   }
   5152   return QualType();
   5153 }
   5154 
   5155 /// SuggestParentheses - Emit a note with a fixit hint that wraps
   5156 /// ParenRange in parentheses.
   5157 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
   5158                                const PartialDiagnostic &Note,
   5159                                SourceRange ParenRange) {
   5160   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
   5161   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
   5162       EndLoc.isValid()) {
   5163     Self.Diag(Loc, Note)
   5164       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
   5165       << FixItHint::CreateInsertion(EndLoc, ")");
   5166   } else {
   5167     // We can't display the parentheses, so just show the bare note.
   5168     Self.Diag(Loc, Note) << ParenRange;
   5169   }
   5170 }
   5171 
   5172 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
   5173   return Opc >= BO_Mul && Opc <= BO_Shr;
   5174 }
   5175 
   5176 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
   5177 /// expression, either using a built-in or overloaded operator,
   5178 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
   5179 /// expression.
   5180 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
   5181                                    Expr **RHSExprs) {
   5182   // Don't strip parenthesis: we should not warn if E is in parenthesis.
   5183   E = E->IgnoreImpCasts();
   5184   E = E->IgnoreConversionOperator();
   5185   E = E->IgnoreImpCasts();
   5186 
   5187   // Built-in binary operator.
   5188   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
   5189     if (IsArithmeticOp(OP->getOpcode())) {
   5190       *Opcode = OP->getOpcode();
   5191       *RHSExprs = OP->getRHS();
   5192       return true;
   5193     }
   5194   }
   5195 
   5196   // Overloaded operator.
   5197   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
   5198     if (Call->getNumArgs() != 2)
   5199       return false;
   5200 
   5201     // Make sure this is really a binary operator that is safe to pass into
   5202     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
   5203     OverloadedOperatorKind OO = Call->getOperator();
   5204     if (OO < OO_Plus || OO > OO_Arrow)
   5205       return false;
   5206 
   5207     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
   5208     if (IsArithmeticOp(OpKind)) {
   5209       *Opcode = OpKind;
   5210       *RHSExprs = Call->getArg(1);
   5211       return true;
   5212     }
   5213   }
   5214 
   5215   return false;
   5216 }
   5217 
   5218 static bool IsLogicOp(BinaryOperatorKind Opc) {
   5219   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
   5220 }
   5221 
   5222 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
   5223 /// or is a logical expression such as (x==y) which has int type, but is
   5224 /// commonly interpreted as boolean.
   5225 static bool ExprLooksBoolean(Expr *E) {
   5226   E = E->IgnoreParenImpCasts();
   5227 
   5228   if (E->getType()->isBooleanType())
   5229     return true;
   5230   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
   5231     return IsLogicOp(OP->getOpcode());
   5232   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
   5233     return OP->getOpcode() == UO_LNot;
   5234 
   5235   return false;
   5236 }
   5237 
   5238 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
   5239 /// and binary operator are mixed in a way that suggests the programmer assumed
   5240 /// the conditional operator has higher precedence, for example:
   5241 /// "int x = a + someBinaryCondition ? 1 : 2".
   5242 static void DiagnoseConditionalPrecedence(Sema &Self,
   5243                                           SourceLocation OpLoc,
   5244                                           Expr *Condition,
   5245                                           Expr *LHSExpr,
   5246                                           Expr *RHSExpr) {
   5247   BinaryOperatorKind CondOpcode;
   5248   Expr *CondRHS;
   5249 
   5250   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
   5251     return;
   5252   if (!ExprLooksBoolean(CondRHS))
   5253     return;
   5254 
   5255   // The condition is an arithmetic binary expression, with a right-
   5256   // hand side that looks boolean, so warn.
   5257 
   5258   Self.Diag(OpLoc, diag::warn_precedence_conditional)
   5259       << Condition->getSourceRange()
   5260       << BinaryOperator::getOpcodeStr(CondOpcode);
   5261 
   5262   SuggestParentheses(Self, OpLoc,
   5263     Self.PDiag(diag::note_precedence_conditional_silence)
   5264       << BinaryOperator::getOpcodeStr(CondOpcode),
   5265     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
   5266 
   5267   SuggestParentheses(Self, OpLoc,
   5268     Self.PDiag(diag::note_precedence_conditional_first),
   5269     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
   5270 }
   5271 
   5272 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
   5273 /// in the case of a the GNU conditional expr extension.
   5274 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
   5275                                     SourceLocation ColonLoc,
   5276                                     Expr *CondExpr, Expr *LHSExpr,
   5277                                     Expr *RHSExpr) {
   5278   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
   5279   // was the condition.
   5280   OpaqueValueExpr *opaqueValue = 0;
   5281   Expr *commonExpr = 0;
   5282   if (LHSExpr == 0) {
   5283     commonExpr = CondExpr;
   5284 
   5285     // We usually want to apply unary conversions *before* saving, except
   5286     // in the special case of a C++ l-value conditional.
   5287     if (!(getLangOpts().CPlusPlus
   5288           && !commonExpr->isTypeDependent()
   5289           && commonExpr->getValueKind() == RHSExpr->getValueKind()
   5290           && commonExpr->isGLValue()
   5291           && commonExpr->isOrdinaryOrBitFieldObject()
   5292           && RHSExpr->isOrdinaryOrBitFieldObject()
   5293           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
   5294       ExprResult commonRes = UsualUnaryConversions(commonExpr);
   5295       if (commonRes.isInvalid())
   5296         return ExprError();
   5297       commonExpr = commonRes.take();
   5298     }
   5299 
   5300     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
   5301                                                 commonExpr->getType(),
   5302                                                 commonExpr->getValueKind(),
   5303                                                 commonExpr->getObjectKind(),
   5304                                                 commonExpr);
   5305     LHSExpr = CondExpr = opaqueValue;
   5306   }
   5307 
   5308   ExprValueKind VK = VK_RValue;
   5309   ExprObjectKind OK = OK_Ordinary;
   5310   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
   5311   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
   5312                                              VK, OK, QuestionLoc);
   5313   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
   5314       RHS.isInvalid())
   5315     return ExprError();
   5316 
   5317   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
   5318                                 RHS.get());
   5319 
   5320   if (!commonExpr)
   5321     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
   5322                                                    LHS.take(), ColonLoc,
   5323                                                    RHS.take(), result, VK, OK));
   5324 
   5325   return Owned(new (Context)
   5326     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
   5327                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
   5328                               OK));
   5329 }
   5330 
   5331 // checkPointerTypesForAssignment - This is a very tricky routine (despite
   5332 // being closely modeled after the C99 spec:-). The odd characteristic of this
   5333 // routine is it effectively iqnores the qualifiers on the top level pointee.
   5334 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
   5335 // FIXME: add a couple examples in this comment.
   5336 static Sema::AssignConvertType
   5337 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
   5338   assert(LHSType.isCanonical() && "LHS not canonicalized!");
   5339   assert(RHSType.isCanonical() && "RHS not canonicalized!");
   5340 
   5341   // get the "pointed to" type (ignoring qualifiers at the top level)
   5342   const Type *lhptee, *rhptee;
   5343   Qualifiers lhq, rhq;
   5344   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
   5345   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
   5346 
   5347   Sema::AssignConvertType ConvTy = Sema::Compatible;
   5348 
   5349   // C99 6.5.16.1p1: This following citation is common to constraints
   5350   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
   5351   // qualifiers of the type *pointed to* by the right;
   5352   Qualifiers lq;
   5353 
   5354   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
   5355   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
   5356       lhq.compatiblyIncludesObjCLifetime(rhq)) {
   5357     // Ignore lifetime for further calculation.
   5358     lhq.removeObjCLifetime();
   5359     rhq.removeObjCLifetime();
   5360   }
   5361 
   5362   if (!lhq.compatiblyIncludes(rhq)) {
   5363     // Treat address-space mismatches as fatal.  TODO: address subspaces
   5364     if (lhq.getAddressSpace() != rhq.getAddressSpace())
   5365       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
   5366 
   5367     // It's okay to add or remove GC or lifetime qualifiers when converting to
   5368     // and from void*.
   5369     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
   5370                         .compatiblyIncludes(
   5371                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
   5372              && (lhptee->isVoidType() || rhptee->isVoidType()))
   5373       ; // keep old
   5374 
   5375     // Treat lifetime mismatches as fatal.
   5376     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
   5377       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
   5378 
   5379     // For GCC compatibility, other qualifier mismatches are treated
   5380     // as still compatible in C.
   5381     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
   5382   }
   5383 
   5384   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
   5385   // incomplete type and the other is a pointer to a qualified or unqualified
   5386   // version of void...
   5387   if (lhptee->isVoidType()) {
   5388     if (rhptee->isIncompleteOrObjectType())
   5389       return ConvTy;
   5390 
   5391     // As an extension, we allow cast to/from void* to function pointer.
   5392     assert(rhptee->isFunctionType());
   5393     return Sema::FunctionVoidPointer;
   5394   }
   5395 
   5396   if (rhptee->isVoidType()) {
   5397     if (lhptee->isIncompleteOrObjectType())
   5398       return ConvTy;
   5399 
   5400     // As an extension, we allow cast to/from void* to function pointer.
   5401     assert(lhptee->isFunctionType());
   5402     return Sema::FunctionVoidPointer;
   5403   }
   5404 
   5405   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
   5406   // unqualified versions of compatible types, ...
   5407   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
   5408   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
   5409     // Check if the pointee types are compatible ignoring the sign.
   5410     // We explicitly check for char so that we catch "char" vs
   5411     // "unsigned char" on systems where "char" is unsigned.
   5412     if (lhptee->isCharType())
   5413       ltrans = S.Context.UnsignedCharTy;
   5414     else if (lhptee->hasSignedIntegerRepresentation())
   5415       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
   5416 
   5417     if (rhptee->isCharType())
   5418       rtrans = S.Context.UnsignedCharTy;
   5419     else if (rhptee->hasSignedIntegerRepresentation())
   5420       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
   5421 
   5422     if (ltrans == rtrans) {
   5423       // Types are compatible ignoring the sign. Qualifier incompatibility
   5424       // takes priority over sign incompatibility because the sign
   5425       // warning can be disabled.
   5426       if (ConvTy != Sema::Compatible)
   5427         return ConvTy;
   5428 
   5429       return Sema::IncompatiblePointerSign;
   5430     }
   5431 
   5432     // If we are a multi-level pointer, it's possible that our issue is simply
   5433     // one of qualification - e.g. char ** -> const char ** is not allowed. If
   5434     // the eventual target type is the same and the pointers have the same
   5435     // level of indirection, this must be the issue.
   5436     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
   5437       do {
   5438         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
   5439         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
   5440       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
   5441 
   5442       if (lhptee == rhptee)
   5443         return Sema::IncompatibleNestedPointerQualifiers;
   5444     }
   5445 
   5446     // General pointer incompatibility takes priority over qualifiers.
   5447     return Sema::IncompatiblePointer;
   5448   }
   5449   if (!S.getLangOpts().CPlusPlus &&
   5450       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
   5451     return Sema::IncompatiblePointer;
   5452   return ConvTy;
   5453 }
   5454 
   5455 /// checkBlockPointerTypesForAssignment - This routine determines whether two
   5456 /// block pointer types are compatible or whether a block and normal pointer
   5457 /// are compatible. It is more restrict than comparing two function pointer
   5458 // types.
   5459 static Sema::AssignConvertType
   5460 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
   5461                                     QualType RHSType) {
   5462   assert(LHSType.isCanonical() && "LHS not canonicalized!");
   5463   assert(RHSType.isCanonical() && "RHS not canonicalized!");
   5464 
   5465   QualType lhptee, rhptee;
   5466 
   5467   // get the "pointed to" type (ignoring qualifiers at the top level)
   5468   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
   5469   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
   5470 
   5471   // In C++, the types have to match exactly.
   5472   if (S.getLangOpts().CPlusPlus)
   5473     return Sema::IncompatibleBlockPointer;
   5474 
   5475   Sema::AssignConvertType ConvTy = Sema::Compatible;
   5476 
   5477   // For blocks we enforce that qualifiers are identical.
   5478   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
   5479     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
   5480 
   5481   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
   5482     return Sema::IncompatibleBlockPointer;
   5483 
   5484   return ConvTy;
   5485 }
   5486 
   5487 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
   5488 /// for assignment compatibility.
   5489 static Sema::AssignConvertType
   5490 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
   5491                                    QualType RHSType) {
   5492   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
   5493   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
   5494 
   5495   if (LHSType->isObjCBuiltinType()) {
   5496     // Class is not compatible with ObjC object pointers.
   5497     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
   5498         !RHSType->isObjCQualifiedClassType())
   5499       return Sema::IncompatiblePointer;
   5500     return Sema::Compatible;
   5501   }
   5502   if (RHSType->isObjCBuiltinType()) {
   5503     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
   5504         !LHSType->isObjCQualifiedClassType())
   5505       return Sema::IncompatiblePointer;
   5506     return Sema::Compatible;
   5507   }
   5508   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
   5509   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
   5510 
   5511   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
   5512       // make an exception for id<P>
   5513       !LHSType->isObjCQualifiedIdType())
   5514     return Sema::CompatiblePointerDiscardsQualifiers;
   5515 
   5516   if (S.Context.typesAreCompatible(LHSType, RHSType))
   5517     return Sema::Compatible;
   5518   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
   5519     return Sema::IncompatibleObjCQualifiedId;
   5520   return Sema::IncompatiblePointer;
   5521 }
   5522 
   5523 Sema::AssignConvertType
   5524 Sema::CheckAssignmentConstraints(SourceLocation Loc,
   5525                                  QualType LHSType, QualType RHSType) {
   5526   // Fake up an opaque expression.  We don't actually care about what
   5527   // cast operations are required, so if CheckAssignmentConstraints
   5528   // adds casts to this they'll be wasted, but fortunately that doesn't
   5529   // usually happen on valid code.
   5530   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
   5531   ExprResult RHSPtr = &RHSExpr;
   5532   CastKind K = CK_Invalid;
   5533 
   5534   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
   5535 }
   5536 
   5537 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
   5538 /// has code to accommodate several GCC extensions when type checking
   5539 /// pointers. Here are some objectionable examples that GCC considers warnings:
   5540 ///
   5541 ///  int a, *pint;
   5542 ///  short *pshort;
   5543 ///  struct foo *pfoo;
   5544 ///
   5545 ///  pint = pshort; // warning: assignment from incompatible pointer type
   5546 ///  a = pint; // warning: assignment makes integer from pointer without a cast
   5547 ///  pint = a; // warning: assignment makes pointer from integer without a cast
   5548 ///  pint = pfoo; // warning: assignment from incompatible pointer type
   5549 ///
   5550 /// As a result, the code for dealing with pointers is more complex than the
   5551 /// C99 spec dictates.
   5552 ///
   5553 /// Sets 'Kind' for any result kind except Incompatible.
   5554 Sema::AssignConvertType
   5555 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
   5556                                  CastKind &Kind) {
   5557   QualType RHSType = RHS.get()->getType();
   5558   QualType OrigLHSType = LHSType;
   5559 
   5560   // Get canonical types.  We're not formatting these types, just comparing
   5561   // them.
   5562   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
   5563   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
   5564 
   5565 
   5566   // Common case: no conversion required.
   5567   if (LHSType == RHSType) {
   5568     Kind = CK_NoOp;
   5569     return Compatible;
   5570   }
   5571 
   5572   // If we have an atomic type, try a non-atomic assignment, then just add an
   5573   // atomic qualification step.
   5574   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
   5575     Sema::AssignConvertType result =
   5576       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
   5577     if (result != Compatible)
   5578       return result;
   5579     if (Kind != CK_NoOp)
   5580       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
   5581     Kind = CK_NonAtomicToAtomic;
   5582     return Compatible;
   5583   }
   5584 
   5585   // If the left-hand side is a reference type, then we are in a
   5586   // (rare!) case where we've allowed the use of references in C,
   5587   // e.g., as a parameter type in a built-in function. In this case,
   5588   // just make sure that the type referenced is compatible with the
   5589   // right-hand side type. The caller is responsible for adjusting
   5590   // LHSType so that the resulting expression does not have reference
   5591   // type.
   5592   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
   5593     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
   5594       Kind = CK_LValueBitCast;
   5595       return Compatible;
   5596     }
   5597     return Incompatible;
   5598   }
   5599 
   5600   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
   5601   // to the same ExtVector type.
   5602   if (LHSType->isExtVectorType()) {
   5603     if (RHSType->isExtVectorType())
   5604       return Incompatible;
   5605     if (RHSType->isArithmeticType()) {
   5606       // CK_VectorSplat does T -> vector T, so first cast to the
   5607       // element type.
   5608       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
   5609       if (elType != RHSType) {
   5610         Kind = PrepareScalarCast(RHS, elType);
   5611         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
   5612       }
   5613       Kind = CK_VectorSplat;
   5614       return Compatible;
   5615     }
   5616   }
   5617 
   5618   // Conversions to or from vector type.
   5619   if (LHSType->isVectorType() || RHSType->isVectorType()) {
   5620     if (LHSType->isVectorType() && RHSType->isVectorType()) {
   5621       // Allow assignments of an AltiVec vector type to an equivalent GCC
   5622       // vector type and vice versa
   5623       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
   5624         Kind = CK_BitCast;
   5625         return Compatible;
   5626       }
   5627 
   5628       // If we are allowing lax vector conversions, and LHS and RHS are both
   5629       // vectors, the total size only needs to be the same. This is a bitcast;
   5630       // no bits are changed but the result type is different.
   5631       if (getLangOpts().LaxVectorConversions &&
   5632           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
   5633         Kind = CK_BitCast;
   5634         return IncompatibleVectors;
   5635       }
   5636     }
   5637     return Incompatible;
   5638   }
   5639 
   5640   // Arithmetic conversions.
   5641   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
   5642       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
   5643     Kind = PrepareScalarCast(RHS, LHSType);
   5644     return Compatible;
   5645   }
   5646 
   5647   // Conversions to normal pointers.
   5648   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
   5649     // U* -> T*
   5650     if (isa<PointerType>(RHSType)) {
   5651       Kind = CK_BitCast;
   5652       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
   5653     }
   5654 
   5655     // int -> T*
   5656     if (RHSType->isIntegerType()) {
   5657       Kind = CK_IntegralToPointer; // FIXME: null?
   5658       return IntToPointer;
   5659     }
   5660 
   5661     // C pointers are not compatible with ObjC object pointers,
   5662     // with two exceptions:
   5663     if (isa<ObjCObjectPointerType>(RHSType)) {
   5664       //  - conversions to void*
   5665       if (LHSPointer->getPointeeType()->isVoidType()) {
   5666         Kind = CK_BitCast;
   5667         return Compatible;
   5668       }
   5669 
   5670       //  - conversions from 'Class' to the redefinition type
   5671       if (RHSType->isObjCClassType() &&
   5672           Context.hasSameType(LHSType,
   5673                               Context.getObjCClassRedefinitionType())) {
   5674         Kind = CK_BitCast;
   5675         return Compatible;
   5676       }
   5677 
   5678       Kind = CK_BitCast;
   5679       return IncompatiblePointer;
   5680     }
   5681 
   5682     // U^ -> void*
   5683     if (RHSType->getAs<BlockPointerType>()) {
   5684       if (LHSPointer->getPointeeType()->isVoidType()) {
   5685         Kind = CK_BitCast;
   5686         return Compatible;
   5687       }
   5688     }
   5689 
   5690     return Incompatible;
   5691   }
   5692 
   5693   // Conversions to block pointers.
   5694   if (isa<BlockPointerType>(LHSType)) {
   5695     // U^ -> T^
   5696     if (RHSType->isBlockPointerType()) {
   5697       Kind = CK_BitCast;
   5698       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
   5699     }
   5700 
   5701     // int or null -> T^
   5702     if (RHSType->isIntegerType()) {
   5703       Kind = CK_IntegralToPointer; // FIXME: null
   5704       return IntToBlockPointer;
   5705     }
   5706 
   5707     // id -> T^
   5708     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
   5709       Kind = CK_AnyPointerToBlockPointerCast;
   5710       return Compatible;
   5711     }
   5712 
   5713     // void* -> T^
   5714     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
   5715       if (RHSPT->getPointeeType()->isVoidType()) {
   5716         Kind = CK_AnyPointerToBlockPointerCast;
   5717         return Compatible;
   5718       }
   5719 
   5720     return Incompatible;
   5721   }
   5722 
   5723   // Conversions to Objective-C pointers.
   5724   if (isa<ObjCObjectPointerType>(LHSType)) {
   5725     // A* -> B*
   5726     if (RHSType->isObjCObjectPointerType()) {
   5727       Kind = CK_BitCast;
   5728       Sema::AssignConvertType result =
   5729         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
   5730       if (getLangOpts().ObjCAutoRefCount &&
   5731           result == Compatible &&
   5732           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
   5733         result = IncompatibleObjCWeakRef;
   5734       return result;
   5735     }
   5736 
   5737     // int or null -> A*
   5738     if (RHSType->isIntegerType()) {
   5739       Kind = CK_IntegralToPointer; // FIXME: null
   5740       return IntToPointer;
   5741     }
   5742 
   5743     // In general, C pointers are not compatible with ObjC object pointers,
   5744     // with two exceptions:
   5745     if (isa<PointerType>(RHSType)) {
   5746       Kind = CK_CPointerToObjCPointerCast;
   5747 
   5748       //  - conversions from 'void*'
   5749       if (RHSType->isVoidPointerType()) {
   5750         return Compatible;
   5751       }
   5752 
   5753       //  - conversions to 'Class' from its redefinition type
   5754       if (LHSType->isObjCClassType() &&
   5755           Context.hasSameType(RHSType,
   5756                               Context.getObjCClassRedefinitionType())) {
   5757         return Compatible;
   5758       }
   5759 
   5760       return IncompatiblePointer;
   5761     }
   5762 
   5763     // T^ -> A*
   5764     if (RHSType->isBlockPointerType()) {
   5765       maybeExtendBlockObject(*this, RHS);
   5766       Kind = CK_BlockPointerToObjCPointerCast;
   5767       return Compatible;
   5768     }
   5769 
   5770     return Incompatible;
   5771   }
   5772 
   5773   // Conversions from pointers that are not covered by the above.
   5774   if (isa<PointerType>(RHSType)) {
   5775     // T* -> _Bool
   5776     if (LHSType == Context.BoolTy) {
   5777       Kind = CK_PointerToBoolean;
   5778       return Compatible;
   5779     }
   5780 
   5781     // T* -> int
   5782     if (LHSType->isIntegerType()) {
   5783       Kind = CK_PointerToIntegral;
   5784       return PointerToInt;
   5785     }
   5786 
   5787     return Incompatible;
   5788   }
   5789 
   5790   // Conversions from Objective-C pointers that are not covered by the above.
   5791   if (isa<ObjCObjectPointerType>(RHSType)) {
   5792     // T* -> _Bool
   5793     if (LHSType == Context.BoolTy) {
   5794       Kind = CK_PointerToBoolean;
   5795       return Compatible;
   5796     }
   5797 
   5798     // T* -> int
   5799     if (LHSType->isIntegerType()) {
   5800       Kind = CK_PointerToIntegral;
   5801       return PointerToInt;
   5802     }
   5803 
   5804     return Incompatible;
   5805   }
   5806 
   5807   // struct A -> struct B
   5808   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
   5809     if (Context.typesAreCompatible(LHSType, RHSType)) {
   5810       Kind = CK_NoOp;
   5811       return Compatible;
   5812     }
   5813   }
   5814 
   5815   return Incompatible;
   5816 }
   5817 
   5818 /// \brief Constructs a transparent union from an expression that is
   5819 /// used to initialize the transparent union.
   5820 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
   5821                                       ExprResult &EResult, QualType UnionType,
   5822                                       FieldDecl *Field) {
   5823   // Build an initializer list that designates the appropriate member
   5824   // of the transparent union.
   5825   Expr *E = EResult.take();
   5826   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
   5827                                                    E, SourceLocation());
   5828   Initializer->setType(UnionType);
   5829   Initializer->setInitializedFieldInUnion(Field);
   5830 
   5831   // Build a compound literal constructing a value of the transparent
   5832   // union type from this initializer list.
   5833   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
   5834   EResult = S.Owned(
   5835     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
   5836                                 VK_RValue, Initializer, false));
   5837 }
   5838 
   5839 Sema::AssignConvertType
   5840 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
   5841                                                ExprResult &RHS) {
   5842   QualType RHSType = RHS.get()->getType();
   5843 
   5844   // If the ArgType is a Union type, we want to handle a potential
   5845   // transparent_union GCC extension.
   5846   const RecordType *UT = ArgType->getAsUnionType();
   5847   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
   5848     return Incompatible;
   5849 
   5850   // The field to initialize within the transparent union.
   5851   RecordDecl *UD = UT->getDecl();
   5852   FieldDecl *InitField = 0;
   5853   // It's compatible if the expression matches any of the fields.
   5854   for (RecordDecl::field_iterator it = UD->field_begin(),
   5855          itend = UD->field_end();
   5856        it != itend; ++it) {
   5857     if (it->getType()->isPointerType()) {
   5858       // If the transparent union contains a pointer type, we allow:
   5859       // 1) void pointer
   5860       // 2) null pointer constant
   5861       if (RHSType->isPointerType())
   5862         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
   5863           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
   5864           InitField = *it;
   5865           break;
   5866         }
   5867 
   5868       if (RHS.get()->isNullPointerConstant(Context,
   5869                                            Expr::NPC_ValueDependentIsNull)) {
   5870         RHS = ImpCastExprToType(RHS.take(), it->getType(),
   5871                                 CK_NullToPointer);
   5872         InitField = *it;
   5873         break;
   5874       }
   5875     }
   5876 
   5877     CastKind Kind = CK_Invalid;
   5878     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
   5879           == Compatible) {
   5880       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
   5881       InitField = *it;
   5882       break;
   5883     }
   5884   }
   5885 
   5886   if (!InitField)
   5887     return Incompatible;
   5888 
   5889   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
   5890   return Compatible;
   5891 }
   5892 
   5893 Sema::AssignConvertType
   5894 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
   5895                                        bool Diagnose) {
   5896   if (getLangOpts().CPlusPlus) {
   5897     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
   5898       // C++ 5.17p3: If the left operand is not of class type, the
   5899       // expression is implicitly converted (C++ 4) to the
   5900       // cv-unqualified type of the left operand.
   5901       ExprResult Res;
   5902       if (Diagnose) {
   5903         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   5904                                         AA_Assigning);
   5905       } else {
   5906         ImplicitConversionSequence ICS =
   5907             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   5908                                   /*SuppressUserConversions=*/false,
   5909                                   /*AllowExplicit=*/false,
   5910                                   /*InOverloadResolution=*/false,
   5911                                   /*CStyle=*/false,
   5912                                   /*AllowObjCWritebackConversion=*/false);
   5913         if (ICS.isFailure())
   5914           return Incompatible;
   5915         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   5916                                         ICS, AA_Assigning);
   5917       }
   5918       if (Res.isInvalid())
   5919         return Incompatible;
   5920       Sema::AssignConvertType result = Compatible;
   5921       if (getLangOpts().ObjCAutoRefCount &&
   5922           !CheckObjCARCUnavailableWeakConversion(LHSType,
   5923                                                  RHS.get()->getType()))
   5924         result = IncompatibleObjCWeakRef;
   5925       RHS = Res;
   5926       return result;
   5927     }
   5928 
   5929     // FIXME: Currently, we fall through and treat C++ classes like C
   5930     // structures.
   5931     // FIXME: We also fall through for atomics; not sure what should
   5932     // happen there, though.
   5933   }
   5934 
   5935   // C99 6.5.16.1p1: the left operand is a pointer and the right is
   5936   // a null pointer constant.
   5937   if ((LHSType->isPointerType() ||
   5938        LHSType->isObjCObjectPointerType() ||
   5939        LHSType->isBlockPointerType())
   5940       && RHS.get()->isNullPointerConstant(Context,
   5941                                           Expr::NPC_ValueDependentIsNull)) {
   5942     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
   5943     return Compatible;
   5944   }
   5945 
   5946   // This check seems unnatural, however it is necessary to ensure the proper
   5947   // conversion of functions/arrays. If the conversion were done for all
   5948   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
   5949   // expressions that suppress this implicit conversion (&, sizeof).
   5950   //
   5951   // Suppress this for references: C++ 8.5.3p5.
   5952   if (!LHSType->isReferenceType()) {
   5953     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
   5954     if (RHS.isInvalid())
   5955       return Incompatible;
   5956   }
   5957 
   5958   CastKind Kind = CK_Invalid;
   5959   Sema::AssignConvertType result =
   5960     CheckAssignmentConstraints(LHSType, RHS, Kind);
   5961 
   5962   // C99 6.5.16.1p2: The value of the right operand is converted to the
   5963   // type of the assignment expression.
   5964   // CheckAssignmentConstraints allows the left-hand side to be a reference,
   5965   // so that we can use references in built-in functions even in C.
   5966   // The getNonReferenceType() call makes sure that the resulting expression
   5967   // does not have reference type.
   5968   if (result != Incompatible && RHS.get()->getType() != LHSType)
   5969     RHS = ImpCastExprToType(RHS.take(),
   5970                             LHSType.getNonLValueExprType(Context), Kind);
   5971   return result;
   5972 }
   5973 
   5974 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
   5975                                ExprResult &RHS) {
   5976   Diag(Loc, diag::err_typecheck_invalid_operands)
   5977     << LHS.get()->getType() << RHS.get()->getType()
   5978     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   5979   return QualType();
   5980 }
   5981 
   5982 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
   5983                                    SourceLocation Loc, bool IsCompAssign) {
   5984   if (!IsCompAssign) {
   5985     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
   5986     if (LHS.isInvalid())
   5987       return QualType();
   5988   }
   5989   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
   5990   if (RHS.isInvalid())
   5991     return QualType();
   5992 
   5993   // For conversion purposes, we ignore any qualifiers.
   5994   // For example, "const float" and "float" are equivalent.
   5995   QualType LHSType =
   5996     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
   5997   QualType RHSType =
   5998     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
   5999 
   6000   // If the vector types are identical, return.
   6001   if (LHSType == RHSType)
   6002     return LHSType;
   6003 
   6004   // Handle the case of equivalent AltiVec and GCC vector types
   6005   if (LHSType->isVectorType() && RHSType->isVectorType() &&
   6006       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
   6007     if (LHSType->isExtVectorType()) {
   6008       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   6009       return LHSType;
   6010     }
   6011 
   6012     if (!IsCompAssign)
   6013       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
   6014     return RHSType;
   6015   }
   6016 
   6017   if (getLangOpts().LaxVectorConversions &&
   6018       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
   6019     // If we are allowing lax vector conversions, and LHS and RHS are both
   6020     // vectors, the total size only needs to be the same. This is a
   6021     // bitcast; no bits are changed but the result type is different.
   6022     // FIXME: Should we really be allowing this?
   6023     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   6024     return LHSType;
   6025   }
   6026 
   6027   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
   6028   // swap back (so that we don't reverse the inputs to a subtract, for instance.
   6029   bool swapped = false;
   6030   if (RHSType->isExtVectorType() && !IsCompAssign) {
   6031     swapped = true;
   6032     std::swap(RHS, LHS);
   6033     std::swap(RHSType, LHSType);
   6034   }
   6035 
   6036   // Handle the case of an ext vector and scalar.
   6037   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
   6038     QualType EltTy = LV->getElementType();
   6039     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
   6040       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
   6041       if (order > 0)
   6042         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
   6043       if (order >= 0) {
   6044         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
   6045         if (swapped) std::swap(RHS, LHS);
   6046         return LHSType;
   6047       }
   6048     }
   6049     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
   6050         RHSType->isRealFloatingType()) {
   6051       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
   6052       if (order > 0)
   6053         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
   6054       if (order >= 0) {
   6055         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
   6056         if (swapped) std::swap(RHS, LHS);
   6057         return LHSType;
   6058       }
   6059     }
   6060   }
   6061 
   6062   // Vectors of different size or scalar and non-ext-vector are errors.
   6063   if (swapped) std::swap(RHS, LHS);
   6064   Diag(Loc, diag::err_typecheck_vector_not_convertable)
   6065     << LHS.get()->getType() << RHS.get()->getType()
   6066     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6067   return QualType();
   6068 }
   6069 
   6070 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
   6071 // expression.  These are mainly cases where the null pointer is used as an
   6072 // integer instead of a pointer.
   6073 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
   6074                                 SourceLocation Loc, bool IsCompare) {
   6075   // The canonical way to check for a GNU null is with isNullPointerConstant,
   6076   // but we use a bit of a hack here for speed; this is a relatively
   6077   // hot path, and isNullPointerConstant is slow.
   6078   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
   6079   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
   6080 
   6081   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
   6082 
   6083   // Avoid analyzing cases where the result will either be invalid (and
   6084   // diagnosed as such) or entirely valid and not something to warn about.
   6085   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
   6086       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
   6087     return;
   6088 
   6089   // Comparison operations would not make sense with a null pointer no matter
   6090   // what the other expression is.
   6091   if (!IsCompare) {
   6092     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
   6093         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
   6094         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
   6095     return;
   6096   }
   6097 
   6098   // The rest of the operations only make sense with a null pointer
   6099   // if the other expression is a pointer.
   6100   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
   6101       NonNullType->canDecayToPointerType())
   6102     return;
   6103 
   6104   S.Diag(Loc, diag::warn_null_in_comparison_operation)
   6105       << LHSNull /* LHS is NULL */ << NonNullType
   6106       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6107 }
   6108 
   6109 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
   6110                                            SourceLocation Loc,
   6111                                            bool IsCompAssign, bool IsDiv) {
   6112   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   6113 
   6114   if (LHS.get()->getType()->isVectorType() ||
   6115       RHS.get()->getType()->isVectorType())
   6116     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
   6117 
   6118   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
   6119   if (LHS.isInvalid() || RHS.isInvalid())
   6120     return QualType();
   6121 
   6122 
   6123   if (compType.isNull() || !compType->isArithmeticType())
   6124     return InvalidOperands(Loc, LHS, RHS);
   6125 
   6126   // Check for division by zero.
   6127   if (IsDiv &&
   6128       RHS.get()->isNullPointerConstant(Context,
   6129                                        Expr::NPC_ValueDependentIsNotNull))
   6130     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
   6131                                           << RHS.get()->getSourceRange());
   6132 
   6133   return compType;
   6134 }
   6135 
   6136 QualType Sema::CheckRemainderOperands(
   6137   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
   6138   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   6139 
   6140   if (LHS.get()->getType()->isVectorType() ||
   6141       RHS.get()->getType()->isVectorType()) {
   6142     if (LHS.get()->getType()->hasIntegerRepresentation() &&
   6143         RHS.get()->getType()->hasIntegerRepresentation())
   6144       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
   6145     return InvalidOperands(Loc, LHS, RHS);
   6146   }
   6147 
   6148   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
   6149   if (LHS.isInvalid() || RHS.isInvalid())
   6150     return QualType();
   6151 
   6152   if (compType.isNull() || !compType->isIntegerType())
   6153     return InvalidOperands(Loc, LHS, RHS);
   6154 
   6155   // Check for remainder by zero.
   6156   if (RHS.get()->isNullPointerConstant(Context,
   6157                                        Expr::NPC_ValueDependentIsNotNull))
   6158     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
   6159                                  << RHS.get()->getSourceRange());
   6160 
   6161   return compType;
   6162 }
   6163 
   6164 /// \brief Diagnose invalid arithmetic on two void pointers.
   6165 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
   6166                                                 Expr *LHSExpr, Expr *RHSExpr) {
   6167   S.Diag(Loc, S.getLangOpts().CPlusPlus
   6168                 ? diag::err_typecheck_pointer_arith_void_type
   6169                 : diag::ext_gnu_void_ptr)
   6170     << 1 /* two pointers */ << LHSExpr->getSourceRange()
   6171                             << RHSExpr->getSourceRange();
   6172 }
   6173 
   6174 /// \brief Diagnose invalid arithmetic on a void pointer.
   6175 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
   6176                                             Expr *Pointer) {
   6177   S.Diag(Loc, S.getLangOpts().CPlusPlus
   6178                 ? diag::err_typecheck_pointer_arith_void_type
   6179                 : diag::ext_gnu_void_ptr)
   6180     << 0 /* one pointer */ << Pointer->getSourceRange();
   6181 }
   6182 
   6183 /// \brief Diagnose invalid arithmetic on two function pointers.
   6184 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
   6185                                                     Expr *LHS, Expr *RHS) {
   6186   assert(LHS->getType()->isAnyPointerType());
   6187   assert(RHS->getType()->isAnyPointerType());
   6188   S.Diag(Loc, S.getLangOpts().CPlusPlus
   6189                 ? diag::err_typecheck_pointer_arith_function_type
   6190                 : diag::ext_gnu_ptr_func_arith)
   6191     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
   6192     // We only show the second type if it differs from the first.
   6193     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
   6194                                                    RHS->getType())
   6195     << RHS->getType()->getPointeeType()
   6196     << LHS->getSourceRange() << RHS->getSourceRange();
   6197 }
   6198 
   6199 /// \brief Diagnose invalid arithmetic on a function pointer.
   6200 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
   6201                                                 Expr *Pointer) {
   6202   assert(Pointer->getType()->isAnyPointerType());
   6203   S.Diag(Loc, S.getLangOpts().CPlusPlus
   6204                 ? diag::err_typecheck_pointer_arith_function_type
   6205                 : diag::ext_gnu_ptr_func_arith)
   6206     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
   6207     << 0 /* one pointer, so only one type */
   6208     << Pointer->getSourceRange();
   6209 }
   6210 
   6211 /// \brief Emit error if Operand is incomplete pointer type
   6212 ///
   6213 /// \returns True if pointer has incomplete type
   6214 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
   6215                                                  Expr *Operand) {
   6216   assert(Operand->getType()->isAnyPointerType() &&
   6217          !Operand->getType()->isDependentType());
   6218   QualType PointeeTy = Operand->getType()->getPointeeType();
   6219   return S.RequireCompleteType(Loc, PointeeTy,
   6220                                diag::err_typecheck_arithmetic_incomplete_type,
   6221                                PointeeTy, Operand->getSourceRange());
   6222 }
   6223 
   6224 /// \brief Check the validity of an arithmetic pointer operand.
   6225 ///
   6226 /// If the operand has pointer type, this code will check for pointer types
   6227 /// which are invalid in arithmetic operations. These will be diagnosed
   6228 /// appropriately, including whether or not the use is supported as an
   6229 /// extension.
   6230 ///
   6231 /// \returns True when the operand is valid to use (even if as an extension).
   6232 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
   6233                                             Expr *Operand) {
   6234   if (!Operand->getType()->isAnyPointerType()) return true;
   6235 
   6236   QualType PointeeTy = Operand->getType()->getPointeeType();
   6237   if (PointeeTy->isVoidType()) {
   6238     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
   6239     return !S.getLangOpts().CPlusPlus;
   6240   }
   6241   if (PointeeTy->isFunctionType()) {
   6242     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
   6243     return !S.getLangOpts().CPlusPlus;
   6244   }
   6245 
   6246   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
   6247 
   6248   return true;
   6249 }
   6250 
   6251 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
   6252 /// operands.
   6253 ///
   6254 /// This routine will diagnose any invalid arithmetic on pointer operands much
   6255 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
   6256 /// for emitting a single diagnostic even for operations where both LHS and RHS
   6257 /// are (potentially problematic) pointers.
   6258 ///
   6259 /// \returns True when the operand is valid to use (even if as an extension).
   6260 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
   6261                                                 Expr *LHSExpr, Expr *RHSExpr) {
   6262   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
   6263   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
   6264   if (!isLHSPointer && !isRHSPointer) return true;
   6265 
   6266   QualType LHSPointeeTy, RHSPointeeTy;
   6267   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
   6268   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
   6269 
   6270   // Check for arithmetic on pointers to incomplete types.
   6271   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
   6272   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
   6273   if (isLHSVoidPtr || isRHSVoidPtr) {
   6274     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
   6275     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
   6276     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
   6277 
   6278     return !S.getLangOpts().CPlusPlus;
   6279   }
   6280 
   6281   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
   6282   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
   6283   if (isLHSFuncPtr || isRHSFuncPtr) {
   6284     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
   6285     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
   6286                                                                 RHSExpr);
   6287     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
   6288 
   6289     return !S.getLangOpts().CPlusPlus;
   6290   }
   6291 
   6292   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
   6293     return false;
   6294   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
   6295     return false;
   6296 
   6297   return true;
   6298 }
   6299 
   6300 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
   6301 /// literal.
   6302 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
   6303                                   Expr *LHSExpr, Expr *RHSExpr) {
   6304   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
   6305   Expr* IndexExpr = RHSExpr;
   6306   if (!StrExpr) {
   6307     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
   6308     IndexExpr = LHSExpr;
   6309   }
   6310 
   6311   bool IsStringPlusInt = StrExpr &&
   6312       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
   6313   if (!IsStringPlusInt)
   6314     return;
   6315 
   6316   llvm::APSInt index;
   6317   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
   6318     unsigned StrLenWithNull = StrExpr->getLength() + 1;
   6319     if (index.isNonNegative() &&
   6320         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
   6321                               index.isUnsigned()))
   6322       return;
   6323   }
   6324 
   6325   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
   6326   Self.Diag(OpLoc, diag::warn_string_plus_int)
   6327       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
   6328 
   6329   // Only print a fixit for "str" + int, not for int + "str".
   6330   if (IndexExpr == RHSExpr) {
   6331     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
   6332     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
   6333         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
   6334         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
   6335         << FixItHint::CreateInsertion(EndLoc, "]");
   6336   } else
   6337     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
   6338 }
   6339 
   6340 /// \brief Emit error when two pointers are incompatible.
   6341 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
   6342                                            Expr *LHSExpr, Expr *RHSExpr) {
   6343   assert(LHSExpr->getType()->isAnyPointerType());
   6344   assert(RHSExpr->getType()->isAnyPointerType());
   6345   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
   6346     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
   6347     << RHSExpr->getSourceRange();
   6348 }
   6349 
   6350 QualType Sema::CheckAdditionOperands( // C99 6.5.6
   6351     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
   6352     QualType* CompLHSTy) {
   6353   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   6354 
   6355   if (LHS.get()->getType()->isVectorType() ||
   6356       RHS.get()->getType()->isVectorType()) {
   6357     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
   6358     if (CompLHSTy) *CompLHSTy = compType;
   6359     return compType;
   6360   }
   6361 
   6362   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
   6363   if (LHS.isInvalid() || RHS.isInvalid())
   6364     return QualType();
   6365 
   6366   // Diagnose "string literal" '+' int.
   6367   if (Opc == BO_Add)
   6368     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
   6369 
   6370   // handle the common case first (both operands are arithmetic).
   6371   if (!compType.isNull() && compType->isArithmeticType()) {
   6372     if (CompLHSTy) *CompLHSTy = compType;
   6373     return compType;
   6374   }
   6375 
   6376   // Type-checking.  Ultimately the pointer's going to be in PExp;
   6377   // note that we bias towards the LHS being the pointer.
   6378   Expr *PExp = LHS.get(), *IExp = RHS.get();
   6379 
   6380   bool isObjCPointer;
   6381   if (PExp->getType()->isPointerType()) {
   6382     isObjCPointer = false;
   6383   } else if (PExp->getType()->isObjCObjectPointerType()) {
   6384     isObjCPointer = true;
   6385   } else {
   6386     std::swap(PExp, IExp);
   6387     if (PExp->getType()->isPointerType()) {
   6388       isObjCPointer = false;
   6389     } else if (PExp->getType()->isObjCObjectPointerType()) {
   6390       isObjCPointer = true;
   6391     } else {
   6392       return InvalidOperands(Loc, LHS, RHS);
   6393     }
   6394   }
   6395   assert(PExp->getType()->isAnyPointerType());
   6396 
   6397   if (!IExp->getType()->isIntegerType())
   6398     return InvalidOperands(Loc, LHS, RHS);
   6399 
   6400   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
   6401     return QualType();
   6402 
   6403   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
   6404     return QualType();
   6405 
   6406   // Check array bounds for pointer arithemtic
   6407   CheckArrayAccess(PExp, IExp);
   6408 
   6409   if (CompLHSTy) {
   6410     QualType LHSTy = Context.isPromotableBitField(LHS.get());
   6411     if (LHSTy.isNull()) {
   6412       LHSTy = LHS.get()->getType();
   6413       if (LHSTy->isPromotableIntegerType())
   6414         LHSTy = Context.getPromotedIntegerType(LHSTy);
   6415     }
   6416     *CompLHSTy = LHSTy;
   6417   }
   6418 
   6419   return PExp->getType();
   6420 }
   6421 
   6422 // C99 6.5.6
   6423 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
   6424                                         SourceLocation Loc,
   6425                                         QualType* CompLHSTy) {
   6426   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   6427 
   6428   if (LHS.get()->getType()->isVectorType() ||
   6429       RHS.get()->getType()->isVectorType()) {
   6430     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
   6431     if (CompLHSTy) *CompLHSTy = compType;
   6432     return compType;
   6433   }
   6434 
   6435   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
   6436   if (LHS.isInvalid() || RHS.isInvalid())
   6437     return QualType();
   6438 
   6439   // Enforce type constraints: C99 6.5.6p3.
   6440 
   6441   // Handle the common case first (both operands are arithmetic).
   6442   if (!compType.isNull() && compType->isArithmeticType()) {
   6443     if (CompLHSTy) *CompLHSTy = compType;
   6444     return compType;
   6445   }
   6446 
   6447   // Either ptr - int   or   ptr - ptr.
   6448   if (LHS.get()->getType()->isAnyPointerType()) {
   6449     QualType lpointee = LHS.get()->getType()->getPointeeType();
   6450 
   6451     // Diagnose bad cases where we step over interface counts.
   6452     if (LHS.get()->getType()->isObjCObjectPointerType() &&
   6453         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
   6454       return QualType();
   6455 
   6456     // The result type of a pointer-int computation is the pointer type.
   6457     if (RHS.get()->getType()->isIntegerType()) {
   6458       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
   6459         return QualType();
   6460 
   6461       // Check array bounds for pointer arithemtic
   6462       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
   6463                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
   6464 
   6465       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
   6466       return LHS.get()->getType();
   6467     }
   6468 
   6469     // Handle pointer-pointer subtractions.
   6470     if (const PointerType *RHSPTy
   6471           = RHS.get()->getType()->getAs<PointerType>()) {
   6472       QualType rpointee = RHSPTy->getPointeeType();
   6473 
   6474       if (getLangOpts().CPlusPlus) {
   6475         // Pointee types must be the same: C++ [expr.add]
   6476         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
   6477           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
   6478         }
   6479       } else {
   6480         // Pointee types must be compatible C99 6.5.6p3
   6481         if (!Context.typesAreCompatible(
   6482                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
   6483                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
   6484           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
   6485           return QualType();
   6486         }
   6487       }
   6488 
   6489       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
   6490                                                LHS.get(), RHS.get()))
   6491         return QualType();
   6492 
   6493       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
   6494       return Context.getPointerDiffType();
   6495     }
   6496   }
   6497 
   6498   return InvalidOperands(Loc, LHS, RHS);
   6499 }
   6500 
   6501 static bool isScopedEnumerationType(QualType T) {
   6502   if (const EnumType *ET = dyn_cast<EnumType>(T))
   6503     return ET->getDecl()->isScoped();
   6504   return false;
   6505 }
   6506 
   6507 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
   6508                                    SourceLocation Loc, unsigned Opc,
   6509                                    QualType LHSType) {
   6510   llvm::APSInt Right;
   6511   // Check right/shifter operand
   6512   if (RHS.get()->isValueDependent() ||
   6513       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
   6514     return;
   6515 
   6516   if (Right.isNegative()) {
   6517     S.DiagRuntimeBehavior(Loc, RHS.get(),
   6518                           S.PDiag(diag::warn_shift_negative)
   6519                             << RHS.get()->getSourceRange());
   6520     return;
   6521   }
   6522   llvm::APInt LeftBits(Right.getBitWidth(),
   6523                        S.Context.getTypeSize(LHS.get()->getType()));
   6524   if (Right.uge(LeftBits)) {
   6525     S.DiagRuntimeBehavior(Loc, RHS.get(),
   6526                           S.PDiag(diag::warn_shift_gt_typewidth)
   6527                             << RHS.get()->getSourceRange());
   6528     return;
   6529   }
   6530   if (Opc != BO_Shl)
   6531     return;
   6532 
   6533   // When left shifting an ICE which is signed, we can check for overflow which
   6534   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
   6535   // integers have defined behavior modulo one more than the maximum value
   6536   // representable in the result type, so never warn for those.
   6537   llvm::APSInt Left;
   6538   if (LHS.get()->isValueDependent() ||
   6539       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
   6540       LHSType->hasUnsignedIntegerRepresentation())
   6541     return;
   6542   llvm::APInt ResultBits =
   6543       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
   6544   if (LeftBits.uge(ResultBits))
   6545     return;
   6546   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
   6547   Result = Result.shl(Right);
   6548 
   6549   // Print the bit representation of the signed integer as an unsigned
   6550   // hexadecimal number.
   6551   SmallString<40> HexResult;
   6552   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
   6553 
   6554   // If we are only missing a sign bit, this is less likely to result in actual
   6555   // bugs -- if the result is cast back to an unsigned type, it will have the
   6556   // expected value. Thus we place this behind a different warning that can be
   6557   // turned off separately if needed.
   6558   if (LeftBits == ResultBits - 1) {
   6559     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
   6560         << HexResult.str() << LHSType
   6561         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6562     return;
   6563   }
   6564 
   6565   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
   6566     << HexResult.str() << Result.getMinSignedBits() << LHSType
   6567     << Left.getBitWidth() << LHS.get()->getSourceRange()
   6568     << RHS.get()->getSourceRange();
   6569 }
   6570 
   6571 // C99 6.5.7
   6572 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
   6573                                   SourceLocation Loc, unsigned Opc,
   6574                                   bool IsCompAssign) {
   6575   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   6576 
   6577   // C99 6.5.7p2: Each of the operands shall have integer type.
   6578   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
   6579       !RHS.get()->getType()->hasIntegerRepresentation())
   6580     return InvalidOperands(Loc, LHS, RHS);
   6581 
   6582   // C++0x: Don't allow scoped enums. FIXME: Use something better than
   6583   // hasIntegerRepresentation() above instead of this.
   6584   if (isScopedEnumerationType(LHS.get()->getType()) ||
   6585       isScopedEnumerationType(RHS.get()->getType())) {
   6586     return InvalidOperands(Loc, LHS, RHS);
   6587   }
   6588 
   6589   // Vector shifts promote their scalar inputs to vector type.
   6590   if (LHS.get()->getType()->isVectorType() ||
   6591       RHS.get()->getType()->isVectorType())
   6592     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
   6593 
   6594   // Shifts don't perform usual arithmetic conversions, they just do integer
   6595   // promotions on each operand. C99 6.5.7p3
   6596 
   6597   // For the LHS, do usual unary conversions, but then reset them away
   6598   // if this is a compound assignment.
   6599   ExprResult OldLHS = LHS;
   6600   LHS = UsualUnaryConversions(LHS.take());
   6601   if (LHS.isInvalid())
   6602     return QualType();
   6603   QualType LHSType = LHS.get()->getType();
   6604   if (IsCompAssign) LHS = OldLHS;
   6605 
   6606   // The RHS is simpler.
   6607   RHS = UsualUnaryConversions(RHS.take());
   6608   if (RHS.isInvalid())
   6609     return QualType();
   6610 
   6611   // Sanity-check shift operands
   6612   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
   6613 
   6614   // "The type of the result is that of the promoted left operand."
   6615   return LHSType;
   6616 }
   6617 
   6618 static bool IsWithinTemplateSpecialization(Decl *D) {
   6619   if (DeclContext *DC = D->getDeclContext()) {
   6620     if (isa<ClassTemplateSpecializationDecl>(DC))
   6621       return true;
   6622     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
   6623       return FD->isFunctionTemplateSpecialization();
   6624   }
   6625   return false;
   6626 }
   6627 
   6628 /// If two different enums are compared, raise a warning.
   6629 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
   6630                                 ExprResult &RHS) {
   6631   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
   6632   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
   6633 
   6634   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
   6635   if (!LHSEnumType)
   6636     return;
   6637   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
   6638   if (!RHSEnumType)
   6639     return;
   6640 
   6641   // Ignore anonymous enums.
   6642   if (!LHSEnumType->getDecl()->getIdentifier())
   6643     return;
   6644   if (!RHSEnumType->getDecl()->getIdentifier())
   6645     return;
   6646 
   6647   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
   6648     return;
   6649 
   6650   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
   6651       << LHSStrippedType << RHSStrippedType
   6652       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6653 }
   6654 
   6655 /// \brief Diagnose bad pointer comparisons.
   6656 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
   6657                                               ExprResult &LHS, ExprResult &RHS,
   6658                                               bool IsError) {
   6659   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
   6660                       : diag::ext_typecheck_comparison_of_distinct_pointers)
   6661     << LHS.get()->getType() << RHS.get()->getType()
   6662     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6663 }
   6664 
   6665 /// \brief Returns false if the pointers are converted to a composite type,
   6666 /// true otherwise.
   6667 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
   6668                                            ExprResult &LHS, ExprResult &RHS) {
   6669   // C++ [expr.rel]p2:
   6670   //   [...] Pointer conversions (4.10) and qualification
   6671   //   conversions (4.4) are performed on pointer operands (or on
   6672   //   a pointer operand and a null pointer constant) to bring
   6673   //   them to their composite pointer type. [...]
   6674   //
   6675   // C++ [expr.eq]p1 uses the same notion for (in)equality
   6676   // comparisons of pointers.
   6677 
   6678   // C++ [expr.eq]p2:
   6679   //   In addition, pointers to members can be compared, or a pointer to
   6680   //   member and a null pointer constant. Pointer to member conversions
   6681   //   (4.11) and qualification conversions (4.4) are performed to bring
   6682   //   them to a common type. If one operand is a null pointer constant,
   6683   //   the common type is the type of the other operand. Otherwise, the
   6684   //   common type is a pointer to member type similar (4.4) to the type
   6685   //   of one of the operands, with a cv-qualification signature (4.4)
   6686   //   that is the union of the cv-qualification signatures of the operand
   6687   //   types.
   6688 
   6689   QualType LHSType = LHS.get()->getType();
   6690   QualType RHSType = RHS.get()->getType();
   6691   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
   6692          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
   6693 
   6694   bool NonStandardCompositeType = false;
   6695   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
   6696   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
   6697   if (T.isNull()) {
   6698     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
   6699     return true;
   6700   }
   6701 
   6702   if (NonStandardCompositeType)
   6703     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
   6704       << LHSType << RHSType << T << LHS.get()->getSourceRange()
   6705       << RHS.get()->getSourceRange();
   6706 
   6707   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
   6708   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
   6709   return false;
   6710 }
   6711 
   6712 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
   6713                                                     ExprResult &LHS,
   6714                                                     ExprResult &RHS,
   6715                                                     bool IsError) {
   6716   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
   6717                       : diag::ext_typecheck_comparison_of_fptr_to_void)
   6718     << LHS.get()->getType() << RHS.get()->getType()
   6719     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6720 }
   6721 
   6722 static bool isObjCObjectLiteral(ExprResult &E) {
   6723   switch (E.get()->getStmtClass()) {
   6724   case Stmt::ObjCArrayLiteralClass:
   6725   case Stmt::ObjCDictionaryLiteralClass:
   6726   case Stmt::ObjCStringLiteralClass:
   6727   case Stmt::ObjCBoxedExprClass:
   6728     return true;
   6729   default:
   6730     // Note that ObjCBoolLiteral is NOT an object literal!
   6731     return false;
   6732   }
   6733 }
   6734 
   6735 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
   6736   // Get the LHS object's interface type.
   6737   QualType Type = LHS->getType();
   6738   QualType InterfaceType;
   6739   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
   6740     InterfaceType = PTy->getPointeeType();
   6741     if (const ObjCObjectType *iQFaceTy =
   6742         InterfaceType->getAsObjCQualifiedInterfaceType())
   6743       InterfaceType = iQFaceTy->getBaseType();
   6744   } else {
   6745     // If this is not actually an Objective-C object, bail out.
   6746     return false;
   6747   }
   6748 
   6749   // If the RHS isn't an Objective-C object, bail out.
   6750   if (!RHS->getType()->isObjCObjectPointerType())
   6751     return false;
   6752 
   6753   // Try to find the -isEqual: method.
   6754   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
   6755   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
   6756                                                       InterfaceType,
   6757                                                       /*instance=*/true);
   6758   if (!Method) {
   6759     if (Type->isObjCIdType()) {
   6760       // For 'id', just check the global pool.
   6761       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
   6762                                                   /*receiverId=*/true,
   6763                                                   /*warn=*/false);
   6764     } else {
   6765       // Check protocols.
   6766       Method = S.LookupMethodInQualifiedType(IsEqualSel,
   6767                                              cast<ObjCObjectPointerType>(Type),
   6768                                              /*instance=*/true);
   6769     }
   6770   }
   6771 
   6772   if (!Method)
   6773     return false;
   6774 
   6775   QualType T = Method->param_begin()[0]->getType();
   6776   if (!T->isObjCObjectPointerType())
   6777     return false;
   6778 
   6779   QualType R = Method->getResultType();
   6780   if (!R->isScalarType())
   6781     return false;
   6782 
   6783   return true;
   6784 }
   6785 
   6786 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
   6787                                           ExprResult &LHS, ExprResult &RHS,
   6788                                           BinaryOperator::Opcode Opc){
   6789   Expr *Literal;
   6790   Expr *Other;
   6791   if (isObjCObjectLiteral(LHS)) {
   6792     Literal = LHS.get();
   6793     Other = RHS.get();
   6794   } else {
   6795     Literal = RHS.get();
   6796     Other = LHS.get();
   6797   }
   6798 
   6799   // Don't warn on comparisons against nil.
   6800   Other = Other->IgnoreParenCasts();
   6801   if (Other->isNullPointerConstant(S.getASTContext(),
   6802                                    Expr::NPC_ValueDependentIsNotNull))
   6803     return;
   6804 
   6805   // This should be kept in sync with warn_objc_literal_comparison.
   6806   // LK_String should always be last, since it has its own warning flag.
   6807   enum {
   6808     LK_Array,
   6809     LK_Dictionary,
   6810     LK_Numeric,
   6811     LK_Boxed,
   6812     LK_String
   6813   } LiteralKind;
   6814 
   6815   switch (Literal->getStmtClass()) {
   6816   case Stmt::ObjCStringLiteralClass:
   6817     // "string literal"
   6818     LiteralKind = LK_String;
   6819     break;
   6820   case Stmt::ObjCArrayLiteralClass:
   6821     // "array literal"
   6822     LiteralKind = LK_Array;
   6823     break;
   6824   case Stmt::ObjCDictionaryLiteralClass:
   6825     // "dictionary literal"
   6826     LiteralKind = LK_Dictionary;
   6827     break;
   6828   case Stmt::ObjCBoxedExprClass: {
   6829     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
   6830     switch (Inner->getStmtClass()) {
   6831     case Stmt::IntegerLiteralClass:
   6832     case Stmt::FloatingLiteralClass:
   6833     case Stmt::CharacterLiteralClass:
   6834     case Stmt::ObjCBoolLiteralExprClass:
   6835     case Stmt::CXXBoolLiteralExprClass:
   6836       // "numeric literal"
   6837       LiteralKind = LK_Numeric;
   6838       break;
   6839     case Stmt::ImplicitCastExprClass: {
   6840       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
   6841       // Boolean literals can be represented by implicit casts.
   6842       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
   6843         LiteralKind = LK_Numeric;
   6844         break;
   6845       }
   6846       // FALLTHROUGH
   6847     }
   6848     default:
   6849       // "boxed expression"
   6850       LiteralKind = LK_Boxed;
   6851       break;
   6852     }
   6853     break;
   6854   }
   6855   default:
   6856     llvm_unreachable("Unknown Objective-C object literal kind");
   6857   }
   6858 
   6859   if (LiteralKind == LK_String)
   6860     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
   6861       << Literal->getSourceRange();
   6862   else
   6863     S.Diag(Loc, diag::warn_objc_literal_comparison)
   6864       << LiteralKind << Literal->getSourceRange();
   6865 
   6866   if (BinaryOperator::isEqualityOp(Opc) &&
   6867       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
   6868     SourceLocation Start = LHS.get()->getLocStart();
   6869     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
   6870     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
   6871 
   6872     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
   6873       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
   6874       << FixItHint::CreateReplacement(OpRange, "isEqual:")
   6875       << FixItHint::CreateInsertion(End, "]");
   6876   }
   6877 }
   6878 
   6879 // C99 6.5.8, C++ [expr.rel]
   6880 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
   6881                                     SourceLocation Loc, unsigned OpaqueOpc,
   6882                                     bool IsRelational) {
   6883   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
   6884 
   6885   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
   6886 
   6887   // Handle vector comparisons separately.
   6888   if (LHS.get()->getType()->isVectorType() ||
   6889       RHS.get()->getType()->isVectorType())
   6890     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
   6891 
   6892   QualType LHSType = LHS.get()->getType();
   6893   QualType RHSType = RHS.get()->getType();
   6894 
   6895   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
   6896   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
   6897 
   6898   checkEnumComparison(*this, Loc, LHS, RHS);
   6899 
   6900   if (!LHSType->hasFloatingRepresentation() &&
   6901       !(LHSType->isBlockPointerType() && IsRelational) &&
   6902       !LHS.get()->getLocStart().isMacroID() &&
   6903       !RHS.get()->getLocStart().isMacroID()) {
   6904     // For non-floating point types, check for self-comparisons of the form
   6905     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
   6906     // often indicate logic errors in the program.
   6907     //
   6908     // NOTE: Don't warn about comparison expressions resulting from macro
   6909     // expansion. Also don't warn about comparisons which are only self
   6910     // comparisons within a template specialization. The warnings should catch
   6911     // obvious cases in the definition of the template anyways. The idea is to
   6912     // warn when the typed comparison operator will always evaluate to the same
   6913     // result.
   6914     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
   6915       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
   6916         if (DRL->getDecl() == DRR->getDecl() &&
   6917             !IsWithinTemplateSpecialization(DRL->getDecl())) {
   6918           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
   6919                               << 0 // self-
   6920                               << (Opc == BO_EQ
   6921                                   || Opc == BO_LE
   6922                                   || Opc == BO_GE));
   6923         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
   6924                    !DRL->getDecl()->getType()->isReferenceType() &&
   6925                    !DRR->getDecl()->getType()->isReferenceType()) {
   6926             // what is it always going to eval to?
   6927             char always_evals_to;
   6928             switch(Opc) {
   6929             case BO_EQ: // e.g. array1 == array2
   6930               always_evals_to = 0; // false
   6931               break;
   6932             case BO_NE: // e.g. array1 != array2
   6933               always_evals_to = 1; // true
   6934               break;
   6935             default:
   6936               // best we can say is 'a constant'
   6937               always_evals_to = 2; // e.g. array1 <= array2
   6938               break;
   6939             }
   6940             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
   6941                                 << 1 // array
   6942                                 << always_evals_to);
   6943         }
   6944       }
   6945     }
   6946 
   6947     if (isa<CastExpr>(LHSStripped))
   6948       LHSStripped = LHSStripped->IgnoreParenCasts();
   6949     if (isa<CastExpr>(RHSStripped))
   6950       RHSStripped = RHSStripped->IgnoreParenCasts();
   6951 
   6952     // Warn about comparisons against a string constant (unless the other
   6953     // operand is null), the user probably wants strcmp.
   6954     Expr *literalString = 0;
   6955     Expr *literalStringStripped = 0;
   6956     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
   6957         !RHSStripped->isNullPointerConstant(Context,
   6958                                             Expr::NPC_ValueDependentIsNull)) {
   6959       literalString = LHS.get();
   6960       literalStringStripped = LHSStripped;
   6961     } else if ((isa<StringLiteral>(RHSStripped) ||
   6962                 isa<ObjCEncodeExpr>(RHSStripped)) &&
   6963                !LHSStripped->isNullPointerConstant(Context,
   6964                                             Expr::NPC_ValueDependentIsNull)) {
   6965       literalString = RHS.get();
   6966       literalStringStripped = RHSStripped;
   6967     }
   6968 
   6969     if (literalString) {
   6970       std::string resultComparison;
   6971       switch (Opc) {
   6972       case BO_LT: resultComparison = ") < 0"; break;
   6973       case BO_GT: resultComparison = ") > 0"; break;
   6974       case BO_LE: resultComparison = ") <= 0"; break;
   6975       case BO_GE: resultComparison = ") >= 0"; break;
   6976       case BO_EQ: resultComparison = ") == 0"; break;
   6977       case BO_NE: resultComparison = ") != 0"; break;
   6978       default: llvm_unreachable("Invalid comparison operator");
   6979       }
   6980 
   6981       DiagRuntimeBehavior(Loc, 0,
   6982         PDiag(diag::warn_stringcompare)
   6983           << isa<ObjCEncodeExpr>(literalStringStripped)
   6984           << literalString->getSourceRange());
   6985     }
   6986   }
   6987 
   6988   // C99 6.5.8p3 / C99 6.5.9p4
   6989   if (LHS.get()->getType()->isArithmeticType() &&
   6990       RHS.get()->getType()->isArithmeticType()) {
   6991     UsualArithmeticConversions(LHS, RHS);
   6992     if (LHS.isInvalid() || RHS.isInvalid())
   6993       return QualType();
   6994   }
   6995   else {
   6996     LHS = UsualUnaryConversions(LHS.take());
   6997     if (LHS.isInvalid())
   6998       return QualType();
   6999 
   7000     RHS = UsualUnaryConversions(RHS.take());
   7001     if (RHS.isInvalid())
   7002       return QualType();
   7003   }
   7004 
   7005   LHSType = LHS.get()->getType();
   7006   RHSType = RHS.get()->getType();
   7007 
   7008   // The result of comparisons is 'bool' in C++, 'int' in C.
   7009   QualType ResultTy = Context.getLogicalOperationType();
   7010 
   7011   if (IsRelational) {
   7012     if (LHSType->isRealType() && RHSType->isRealType())
   7013       return ResultTy;
   7014   } else {
   7015     // Check for comparisons of floating point operands using != and ==.
   7016     if (LHSType->hasFloatingRepresentation())
   7017       CheckFloatComparison(Loc, LHS.get(), RHS.get());
   7018 
   7019     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
   7020       return ResultTy;
   7021   }
   7022 
   7023   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
   7024                                               Expr::NPC_ValueDependentIsNull);
   7025   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
   7026                                               Expr::NPC_ValueDependentIsNull);
   7027 
   7028   // All of the following pointer-related warnings are GCC extensions, except
   7029   // when handling null pointer constants.
   7030   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
   7031     QualType LCanPointeeTy =
   7032       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
   7033     QualType RCanPointeeTy =
   7034       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
   7035 
   7036     if (getLangOpts().CPlusPlus) {
   7037       if (LCanPointeeTy == RCanPointeeTy)
   7038         return ResultTy;
   7039       if (!IsRelational &&
   7040           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
   7041         // Valid unless comparison between non-null pointer and function pointer
   7042         // This is a gcc extension compatibility comparison.
   7043         // In a SFINAE context, we treat this as a hard error to maintain
   7044         // conformance with the C++ standard.
   7045         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
   7046             && !LHSIsNull && !RHSIsNull) {
   7047           diagnoseFunctionPointerToVoidComparison(
   7048               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
   7049 
   7050           if (isSFINAEContext())
   7051             return QualType();
   7052 
   7053           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   7054           return ResultTy;
   7055         }
   7056       }
   7057 
   7058       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
   7059         return QualType();
   7060       else
   7061         return ResultTy;
   7062     }
   7063     // C99 6.5.9p2 and C99 6.5.8p2
   7064     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
   7065                                    RCanPointeeTy.getUnqualifiedType())) {
   7066       // Valid unless a relational comparison of function pointers
   7067       if (IsRelational && LCanPointeeTy->isFunctionType()) {
   7068         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
   7069           << LHSType << RHSType << LHS.get()->getSourceRange()
   7070           << RHS.get()->getSourceRange();
   7071       }
   7072     } else if (!IsRelational &&
   7073                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
   7074       // Valid unless comparison between non-null pointer and function pointer
   7075       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
   7076           && !LHSIsNull && !RHSIsNull)
   7077         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
   7078                                                 /*isError*/false);
   7079     } else {
   7080       // Invalid
   7081       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
   7082     }
   7083     if (LCanPointeeTy != RCanPointeeTy) {
   7084       if (LHSIsNull && !RHSIsNull)
   7085         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
   7086       else
   7087         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   7088     }
   7089     return ResultTy;
   7090   }
   7091 
   7092   if (getLangOpts().CPlusPlus) {
   7093     // Comparison of nullptr_t with itself.
   7094     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
   7095       return ResultTy;
   7096 
   7097     // Comparison of pointers with null pointer constants and equality
   7098     // comparisons of member pointers to null pointer constants.
   7099     if (RHSIsNull &&
   7100         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
   7101          (!IsRelational &&
   7102           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
   7103       RHS = ImpCastExprToType(RHS.take(), LHSType,
   7104                         LHSType->isMemberPointerType()
   7105                           ? CK_NullToMemberPointer
   7106                           : CK_NullToPointer);
   7107       return ResultTy;
   7108     }
   7109     if (LHSIsNull &&
   7110         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
   7111          (!IsRelational &&
   7112           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
   7113       LHS = ImpCastExprToType(LHS.take(), RHSType,
   7114                         RHSType->isMemberPointerType()
   7115                           ? CK_NullToMemberPointer
   7116                           : CK_NullToPointer);
   7117       return ResultTy;
   7118     }
   7119 
   7120     // Comparison of member pointers.
   7121     if (!IsRelational &&
   7122         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
   7123       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
   7124         return QualType();
   7125       else
   7126         return ResultTy;
   7127     }
   7128 
   7129     // Handle scoped enumeration types specifically, since they don't promote
   7130     // to integers.
   7131     if (LHS.get()->getType()->isEnumeralType() &&
   7132         Context.hasSameUnqualifiedType(LHS.get()->getType(),
   7133                                        RHS.get()->getType()))
   7134       return ResultTy;
   7135   }
   7136 
   7137   // Handle block pointer types.
   7138   if (!IsRelational && LHSType->isBlockPointerType() &&
   7139       RHSType->isBlockPointerType()) {
   7140     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
   7141     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
   7142 
   7143     if (!LHSIsNull && !RHSIsNull &&
   7144         !Context.typesAreCompatible(lpointee, rpointee)) {
   7145       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
   7146         << LHSType << RHSType << LHS.get()->getSourceRange()
   7147         << RHS.get()->getSourceRange();
   7148     }
   7149     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   7150     return ResultTy;
   7151   }
   7152 
   7153   // Allow block pointers to be compared with null pointer constants.
   7154   if (!IsRelational
   7155       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
   7156           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
   7157     if (!LHSIsNull && !RHSIsNull) {
   7158       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
   7159              ->getPointeeType()->isVoidType())
   7160             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
   7161                 ->getPointeeType()->isVoidType())))
   7162         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
   7163           << LHSType << RHSType << LHS.get()->getSourceRange()
   7164           << RHS.get()->getSourceRange();
   7165     }
   7166     if (LHSIsNull && !RHSIsNull)
   7167       LHS = ImpCastExprToType(LHS.take(), RHSType,
   7168                               RHSType->isPointerType() ? CK_BitCast
   7169                                 : CK_AnyPointerToBlockPointerCast);
   7170     else
   7171       RHS = ImpCastExprToType(RHS.take(), LHSType,
   7172                               LHSType->isPointerType() ? CK_BitCast
   7173                                 : CK_AnyPointerToBlockPointerCast);
   7174     return ResultTy;
   7175   }
   7176 
   7177   if (LHSType->isObjCObjectPointerType() ||
   7178       RHSType->isObjCObjectPointerType()) {
   7179     const PointerType *LPT = LHSType->getAs<PointerType>();
   7180     const PointerType *RPT = RHSType->getAs<PointerType>();
   7181     if (LPT || RPT) {
   7182       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
   7183       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
   7184 
   7185       if (!LPtrToVoid && !RPtrToVoid &&
   7186           !Context.typesAreCompatible(LHSType, RHSType)) {
   7187         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
   7188                                           /*isError*/false);
   7189       }
   7190       if (LHSIsNull && !RHSIsNull)
   7191         LHS = ImpCastExprToType(LHS.take(), RHSType,
   7192                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
   7193       else
   7194         RHS = ImpCastExprToType(RHS.take(), LHSType,
   7195                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
   7196       return ResultTy;
   7197     }
   7198     if (LHSType->isObjCObjectPointerType() &&
   7199         RHSType->isObjCObjectPointerType()) {
   7200       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
   7201         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
   7202                                           /*isError*/false);
   7203       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
   7204         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
   7205 
   7206       if (LHSIsNull && !RHSIsNull)
   7207         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
   7208       else
   7209         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
   7210       return ResultTy;
   7211     }
   7212   }
   7213   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
   7214       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
   7215     unsigned DiagID = 0;
   7216     bool isError = false;
   7217     if ((LHSIsNull && LHSType->isIntegerType()) ||
   7218         (RHSIsNull && RHSType->isIntegerType())) {
   7219       if (IsRelational && !getLangOpts().CPlusPlus)
   7220         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
   7221     } else if (IsRelational && !getLangOpts().CPlusPlus)
   7222       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
   7223     else if (getLangOpts().CPlusPlus) {
   7224       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
   7225       isError = true;
   7226     } else
   7227       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
   7228 
   7229     if (DiagID) {
   7230       Diag(Loc, DiagID)
   7231         << LHSType << RHSType << LHS.get()->getSourceRange()
   7232         << RHS.get()->getSourceRange();
   7233       if (isError)
   7234         return QualType();
   7235     }
   7236 
   7237     if (LHSType->isIntegerType())
   7238       LHS = ImpCastExprToType(LHS.take(), RHSType,
   7239                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
   7240     else
   7241       RHS = ImpCastExprToType(RHS.take(), LHSType,
   7242                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
   7243     return ResultTy;
   7244   }
   7245 
   7246   // Handle block pointers.
   7247   if (!IsRelational && RHSIsNull
   7248       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
   7249     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
   7250     return ResultTy;
   7251   }
   7252   if (!IsRelational && LHSIsNull
   7253       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
   7254     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
   7255     return ResultTy;
   7256   }
   7257 
   7258   return InvalidOperands(Loc, LHS, RHS);
   7259 }
   7260 
   7261 
   7262 // Return a signed type that is of identical size and number of elements.
   7263 // For floating point vectors, return an integer type of identical size
   7264 // and number of elements.
   7265 QualType Sema::GetSignedVectorType(QualType V) {
   7266   const VectorType *VTy = V->getAs<VectorType>();
   7267   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
   7268   if (TypeSize == Context.getTypeSize(Context.CharTy))
   7269     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
   7270   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
   7271     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
   7272   else if (TypeSize == Context.getTypeSize(Context.IntTy))
   7273     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
   7274   else if (TypeSize == Context.getTypeSize(Context.LongTy))
   7275     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
   7276   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
   7277          "Unhandled vector element size in vector compare");
   7278   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
   7279 }
   7280 
   7281 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
   7282 /// operates on extended vector types.  Instead of producing an IntTy result,
   7283 /// like a scalar comparison, a vector comparison produces a vector of integer
   7284 /// types.
   7285 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
   7286                                           SourceLocation Loc,
   7287                                           bool IsRelational) {
   7288   // Check to make sure we're operating on vectors of the same type and width,
   7289   // Allowing one side to be a scalar of element type.
   7290   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
   7291   if (vType.isNull())
   7292     return vType;
   7293 
   7294   QualType LHSType = LHS.get()->getType();
   7295 
   7296   // If AltiVec, the comparison results in a numeric type, i.e.
   7297   // bool for C++, int for C
   7298   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
   7299     return Context.getLogicalOperationType();
   7300 
   7301   // For non-floating point types, check for self-comparisons of the form
   7302   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
   7303   // often indicate logic errors in the program.
   7304   if (!LHSType->hasFloatingRepresentation()) {
   7305     if (DeclRefExpr* DRL
   7306           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
   7307       if (DeclRefExpr* DRR
   7308             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
   7309         if (DRL->getDecl() == DRR->getDecl())
   7310           DiagRuntimeBehavior(Loc, 0,
   7311                               PDiag(diag::warn_comparison_always)
   7312                                 << 0 // self-
   7313                                 << 2 // "a constant"
   7314                               );
   7315   }
   7316 
   7317   // Check for comparisons of floating point operands using != and ==.
   7318   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
   7319     assert (RHS.get()->getType()->hasFloatingRepresentation());
   7320     CheckFloatComparison(Loc, LHS.get(), RHS.get());
   7321   }
   7322 
   7323   // Return a signed type for the vector.
   7324   return GetSignedVectorType(LHSType);
   7325 }
   7326 
   7327 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
   7328                                           SourceLocation Loc) {
   7329   // Ensure that either both operands are of the same vector type, or
   7330   // one operand is of a vector type and the other is of its element type.
   7331   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
   7332   if (vType.isNull() || vType->isFloatingType())
   7333     return InvalidOperands(Loc, LHS, RHS);
   7334 
   7335   return GetSignedVectorType(LHS.get()->getType());
   7336 }
   7337 
   7338 inline QualType Sema::CheckBitwiseOperands(
   7339   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
   7340   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   7341 
   7342   if (LHS.get()->getType()->isVectorType() ||
   7343       RHS.get()->getType()->isVectorType()) {
   7344     if (LHS.get()->getType()->hasIntegerRepresentation() &&
   7345         RHS.get()->getType()->hasIntegerRepresentation())
   7346       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
   7347 
   7348     return InvalidOperands(Loc, LHS, RHS);
   7349   }
   7350 
   7351   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
   7352   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
   7353                                                  IsCompAssign);
   7354   if (LHSResult.isInvalid() || RHSResult.isInvalid())
   7355     return QualType();
   7356   LHS = LHSResult.take();
   7357   RHS = RHSResult.take();
   7358 
   7359   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
   7360     return compType;
   7361   return InvalidOperands(Loc, LHS, RHS);
   7362 }
   7363 
   7364 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
   7365   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
   7366 
   7367   // Check vector operands differently.
   7368   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
   7369     return CheckVectorLogicalOperands(LHS, RHS, Loc);
   7370 
   7371   // Diagnose cases where the user write a logical and/or but probably meant a
   7372   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
   7373   // is a constant.
   7374   if (LHS.get()->getType()->isIntegerType() &&
   7375       !LHS.get()->getType()->isBooleanType() &&
   7376       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
   7377       // Don't warn in macros or template instantiations.
   7378       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
   7379     // If the RHS can be constant folded, and if it constant folds to something
   7380     // that isn't 0 or 1 (which indicate a potential logical operation that
   7381     // happened to fold to true/false) then warn.
   7382     // Parens on the RHS are ignored.
   7383     llvm::APSInt Result;
   7384     if (RHS.get()->EvaluateAsInt(Result, Context))
   7385       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
   7386           (Result != 0 && Result != 1)) {
   7387         Diag(Loc, diag::warn_logical_instead_of_bitwise)
   7388           << RHS.get()->getSourceRange()
   7389           << (Opc == BO_LAnd ? "&&" : "||");
   7390         // Suggest replacing the logical operator with the bitwise version
   7391         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
   7392             << (Opc == BO_LAnd ? "&" : "|")
   7393             << FixItHint::CreateReplacement(SourceRange(
   7394                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
   7395                                                 getLangOpts())),
   7396                                             Opc == BO_LAnd ? "&" : "|");
   7397         if (Opc == BO_LAnd)
   7398           // Suggest replacing "Foo() && kNonZero" with "Foo()"
   7399           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
   7400               << FixItHint::CreateRemoval(
   7401                   SourceRange(
   7402                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
   7403                                                  0, getSourceManager(),
   7404                                                  getLangOpts()),
   7405                       RHS.get()->getLocEnd()));
   7406       }
   7407   }
   7408 
   7409   if (!Context.getLangOpts().CPlusPlus) {
   7410     LHS = UsualUnaryConversions(LHS.take());
   7411     if (LHS.isInvalid())
   7412       return QualType();
   7413 
   7414     RHS = UsualUnaryConversions(RHS.take());
   7415     if (RHS.isInvalid())
   7416       return QualType();
   7417 
   7418     if (!LHS.get()->getType()->isScalarType() ||
   7419         !RHS.get()->getType()->isScalarType())
   7420       return InvalidOperands(Loc, LHS, RHS);
   7421 
   7422     return Context.IntTy;
   7423   }
   7424 
   7425   // The following is safe because we only use this method for
   7426   // non-overloadable operands.
   7427 
   7428   // C++ [expr.log.and]p1
   7429   // C++ [expr.log.or]p1
   7430   // The operands are both contextually converted to type bool.
   7431   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
   7432   if (LHSRes.isInvalid())
   7433     return InvalidOperands(Loc, LHS, RHS);
   7434   LHS = LHSRes;
   7435 
   7436   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
   7437   if (RHSRes.isInvalid())
   7438     return InvalidOperands(Loc, LHS, RHS);
   7439   RHS = RHSRes;
   7440 
   7441   // C++ [expr.log.and]p2
   7442   // C++ [expr.log.or]p2
   7443   // The result is a bool.
   7444   return Context.BoolTy;
   7445 }
   7446 
   7447 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
   7448 /// is a read-only property; return true if so. A readonly property expression
   7449 /// depends on various declarations and thus must be treated specially.
   7450 ///
   7451 static bool IsReadonlyProperty(Expr *E, Sema &S) {
   7452   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
   7453   if (!PropExpr) return false;
   7454   if (PropExpr->isImplicitProperty()) return false;
   7455 
   7456   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
   7457   QualType BaseType = PropExpr->isSuperReceiver() ?
   7458                             PropExpr->getSuperReceiverType() :
   7459                             PropExpr->getBase()->getType();
   7460 
   7461   if (const ObjCObjectPointerType *OPT =
   7462       BaseType->getAsObjCInterfacePointerType())
   7463     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
   7464       if (S.isPropertyReadonly(PDecl, IFace))
   7465         return true;
   7466   return false;
   7467 }
   7468 
   7469 static bool IsReadonlyMessage(Expr *E, Sema &S) {
   7470   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
   7471   if (!ME) return false;
   7472   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
   7473   ObjCMessageExpr *Base =
   7474     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
   7475   if (!Base) return false;
   7476   return Base->getMethodDecl() != 0;
   7477 }
   7478 
   7479 /// Is the given expression (which must be 'const') a reference to a
   7480 /// variable which was originally non-const, but which has become
   7481 /// 'const' due to being captured within a block?
   7482 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
   7483 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
   7484   assert(E->isLValue() && E->getType().isConstQualified());
   7485   E = E->IgnoreParens();
   7486 
   7487   // Must be a reference to a declaration from an enclosing scope.
   7488   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
   7489   if (!DRE) return NCCK_None;
   7490   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
   7491 
   7492   // The declaration must be a variable which is not declared 'const'.
   7493   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
   7494   if (!var) return NCCK_None;
   7495   if (var->getType().isConstQualified()) return NCCK_None;
   7496   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
   7497 
   7498   // Decide whether the first capture was for a block or a lambda.
   7499   DeclContext *DC = S.CurContext;
   7500   while (DC->getParent() != var->getDeclContext())
   7501     DC = DC->getParent();
   7502   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
   7503 }
   7504 
   7505 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
   7506 /// emit an error and return true.  If so, return false.
   7507 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
   7508   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
   7509   SourceLocation OrigLoc = Loc;
   7510   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
   7511                                                               &Loc);
   7512   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
   7513     IsLV = Expr::MLV_ReadonlyProperty;
   7514   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
   7515     IsLV = Expr::MLV_InvalidMessageExpression;
   7516   if (IsLV == Expr::MLV_Valid)
   7517     return false;
   7518 
   7519   unsigned Diag = 0;
   7520   bool NeedType = false;
   7521   switch (IsLV) { // C99 6.5.16p2
   7522   case Expr::MLV_ConstQualified:
   7523     Diag = diag::err_typecheck_assign_const;
   7524 
   7525     // Use a specialized diagnostic when we're assigning to an object
   7526     // from an enclosing function or block.
   7527     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
   7528       if (NCCK == NCCK_Block)
   7529         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
   7530       else
   7531         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
   7532       break;
   7533     }
   7534 
   7535     // In ARC, use some specialized diagnostics for occasions where we
   7536     // infer 'const'.  These are always pseudo-strong variables.
   7537     if (S.getLangOpts().ObjCAutoRefCount) {
   7538       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
   7539       if (declRef && isa<VarDecl>(declRef->getDecl())) {
   7540         VarDecl *var = cast<VarDecl>(declRef->getDecl());
   7541 
   7542         // Use the normal diagnostic if it's pseudo-__strong but the
   7543         // user actually wrote 'const'.
   7544         if (var->isARCPseudoStrong() &&
   7545             (!var->getTypeSourceInfo() ||
   7546              !var->getTypeSourceInfo()->getType().isConstQualified())) {
   7547           // There are two pseudo-strong cases:
   7548           //  - self
   7549           ObjCMethodDecl *method = S.getCurMethodDecl();
   7550           if (method && var == method->getSelfDecl())
   7551             Diag = method->isClassMethod()
   7552               ? diag::err_typecheck_arc_assign_self_class_method
   7553               : diag::err_typecheck_arc_assign_self;
   7554 
   7555           //  - fast enumeration variables
   7556           else
   7557             Diag = diag::err_typecheck_arr_assign_enumeration;
   7558 
   7559           SourceRange Assign;
   7560           if (Loc != OrigLoc)
   7561             Assign = SourceRange(OrigLoc, OrigLoc);
   7562           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
   7563           // We need to preserve the AST regardless, so migration tool
   7564           // can do its job.
   7565           return false;
   7566         }
   7567       }
   7568     }
   7569 
   7570     break;
   7571   case Expr::MLV_ArrayType:
   7572   case Expr::MLV_ArrayTemporary:
   7573     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
   7574     NeedType = true;
   7575     break;
   7576   case Expr::MLV_NotObjectType:
   7577     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
   7578     NeedType = true;
   7579     break;
   7580   case Expr::MLV_LValueCast:
   7581     Diag = diag::err_typecheck_lvalue_casts_not_supported;
   7582     break;
   7583   case Expr::MLV_Valid:
   7584     llvm_unreachable("did not take early return for MLV_Valid");
   7585   case Expr::MLV_InvalidExpression:
   7586   case Expr::MLV_MemberFunction:
   7587   case Expr::MLV_ClassTemporary:
   7588     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
   7589     break;
   7590   case Expr::MLV_IncompleteType:
   7591   case Expr::MLV_IncompleteVoidType:
   7592     return S.RequireCompleteType(Loc, E->getType(),
   7593              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
   7594   case Expr::MLV_DuplicateVectorComponents:
   7595     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
   7596     break;
   7597   case Expr::MLV_ReadonlyProperty:
   7598   case Expr::MLV_NoSetterProperty:
   7599     llvm_unreachable("readonly properties should be processed differently");
   7600   case Expr::MLV_InvalidMessageExpression:
   7601     Diag = diag::error_readonly_message_assignment;
   7602     break;
   7603   case Expr::MLV_SubObjCPropertySetting:
   7604     Diag = diag::error_no_subobject_property_setting;
   7605     break;
   7606   }
   7607 
   7608   SourceRange Assign;
   7609   if (Loc != OrigLoc)
   7610     Assign = SourceRange(OrigLoc, OrigLoc);
   7611   if (NeedType)
   7612     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
   7613   else
   7614     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
   7615   return true;
   7616 }
   7617 
   7618 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
   7619                                          SourceLocation Loc,
   7620                                          Sema &Sema) {
   7621   // C / C++ fields
   7622   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
   7623   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
   7624   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
   7625     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
   7626       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
   7627   }
   7628 
   7629   // Objective-C instance variables
   7630   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
   7631   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
   7632   if (OL && OR && OL->getDecl() == OR->getDecl()) {
   7633     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
   7634     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
   7635     if (RL && RR && RL->getDecl() == RR->getDecl())
   7636       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
   7637   }
   7638 }
   7639 
   7640 // C99 6.5.16.1
   7641 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
   7642                                        SourceLocation Loc,
   7643                                        QualType CompoundType) {
   7644   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
   7645 
   7646   // Verify that LHS is a modifiable lvalue, and emit error if not.
   7647   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
   7648     return QualType();
   7649 
   7650   QualType LHSType = LHSExpr->getType();
   7651   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
   7652                                              CompoundType;
   7653   AssignConvertType ConvTy;
   7654   if (CompoundType.isNull()) {
   7655     Expr *RHSCheck = RHS.get();
   7656 
   7657     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
   7658 
   7659     QualType LHSTy(LHSType);
   7660     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
   7661     if (RHS.isInvalid())
   7662       return QualType();
   7663     // Special case of NSObject attributes on c-style pointer types.
   7664     if (ConvTy == IncompatiblePointer &&
   7665         ((Context.isObjCNSObjectType(LHSType) &&
   7666           RHSType->isObjCObjectPointerType()) ||
   7667          (Context.isObjCNSObjectType(RHSType) &&
   7668           LHSType->isObjCObjectPointerType())))
   7669       ConvTy = Compatible;
   7670 
   7671     if (ConvTy == Compatible &&
   7672         LHSType->isObjCObjectType())
   7673         Diag(Loc, diag::err_objc_object_assignment)
   7674           << LHSType;
   7675 
   7676     // If the RHS is a unary plus or minus, check to see if they = and + are
   7677     // right next to each other.  If so, the user may have typo'd "x =+ 4"
   7678     // instead of "x += 4".
   7679     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
   7680       RHSCheck = ICE->getSubExpr();
   7681     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
   7682       if ((UO->getOpcode() == UO_Plus ||
   7683            UO->getOpcode() == UO_Minus) &&
   7684           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
   7685           // Only if the two operators are exactly adjacent.
   7686           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
   7687           // And there is a space or other character before the subexpr of the
   7688           // unary +/-.  We don't want to warn on "x=-1".
   7689           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
   7690           UO->getSubExpr()->getLocStart().isFileID()) {
   7691         Diag(Loc, diag::warn_not_compound_assign)
   7692           << (UO->getOpcode() == UO_Plus ? "+" : "-")
   7693           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
   7694       }
   7695     }
   7696 
   7697     if (ConvTy == Compatible) {
   7698       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
   7699         checkRetainCycles(LHSExpr, RHS.get());
   7700       else if (getLangOpts().ObjCAutoRefCount)
   7701         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
   7702     }
   7703   } else {
   7704     // Compound assignment "x += y"
   7705     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
   7706   }
   7707 
   7708   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
   7709                                RHS.get(), AA_Assigning))
   7710     return QualType();
   7711 
   7712   CheckForNullPointerDereference(*this, LHSExpr);
   7713 
   7714   // C99 6.5.16p3: The type of an assignment expression is the type of the
   7715   // left operand unless the left operand has qualified type, in which case
   7716   // it is the unqualified version of the type of the left operand.
   7717   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
   7718   // is converted to the type of the assignment expression (above).
   7719   // C++ 5.17p1: the type of the assignment expression is that of its left
   7720   // operand.
   7721   return (getLangOpts().CPlusPlus
   7722           ? LHSType : LHSType.getUnqualifiedType());
   7723 }
   7724 
   7725 // C99 6.5.17
   7726 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
   7727                                    SourceLocation Loc) {
   7728   LHS = S.CheckPlaceholderExpr(LHS.take());
   7729   RHS = S.CheckPlaceholderExpr(RHS.take());
   7730   if (LHS.isInvalid() || RHS.isInvalid())
   7731     return QualType();
   7732 
   7733   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
   7734   // operands, but not unary promotions.
   7735   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
   7736 
   7737   // So we treat the LHS as a ignored value, and in C++ we allow the
   7738   // containing site to determine what should be done with the RHS.
   7739   LHS = S.IgnoredValueConversions(LHS.take());
   7740   if (LHS.isInvalid())
   7741     return QualType();
   7742 
   7743   S.DiagnoseUnusedExprResult(LHS.get());
   7744 
   7745   if (!S.getLangOpts().CPlusPlus) {
   7746     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
   7747     if (RHS.isInvalid())
   7748       return QualType();
   7749     if (!RHS.get()->getType()->isVoidType())
   7750       S.RequireCompleteType(Loc, RHS.get()->getType(),
   7751                             diag::err_incomplete_type);
   7752   }
   7753 
   7754   return RHS.get()->getType();
   7755 }
   7756 
   7757 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
   7758 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
   7759 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
   7760                                                ExprValueKind &VK,
   7761                                                SourceLocation OpLoc,
   7762                                                bool IsInc, bool IsPrefix) {
   7763   if (Op->isTypeDependent())
   7764     return S.Context.DependentTy;
   7765 
   7766   QualType ResType = Op->getType();
   7767   // Atomic types can be used for increment / decrement where the non-atomic
   7768   // versions can, so ignore the _Atomic() specifier for the purpose of
   7769   // checking.
   7770   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
   7771     ResType = ResAtomicType->getValueType();
   7772 
   7773   assert(!ResType.isNull() && "no type for increment/decrement expression");
   7774 
   7775   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
   7776     // Decrement of bool is not allowed.
   7777     if (!IsInc) {
   7778       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
   7779       return QualType();
   7780     }
   7781     // Increment of bool sets it to true, but is deprecated.
   7782     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
   7783   } else if (ResType->isRealType()) {
   7784     // OK!
   7785   } else if (ResType->isPointerType()) {
   7786     // C99 6.5.2.4p2, 6.5.6p2
   7787     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
   7788       return QualType();
   7789   } else if (ResType->isObjCObjectPointerType()) {
   7790     // On modern runtimes, ObjC pointer arithmetic is forbidden.
   7791     // Otherwise, we just need a complete type.
   7792     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
   7793         checkArithmeticOnObjCPointer(S, OpLoc, Op))
   7794       return QualType();
   7795   } else if (ResType->isAnyComplexType()) {
   7796     // C99 does not support ++/-- on complex types, we allow as an extension.
   7797     S.Diag(OpLoc, diag::ext_integer_increment_complex)
   7798       << ResType << Op->getSourceRange();
   7799   } else if (ResType->isPlaceholderType()) {
   7800     ExprResult PR = S.CheckPlaceholderExpr(Op);
   7801     if (PR.isInvalid()) return QualType();
   7802     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
   7803                                           IsInc, IsPrefix);
   7804   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
   7805     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
   7806   } else {
   7807     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
   7808       << ResType << int(IsInc) << Op->getSourceRange();
   7809     return QualType();
   7810   }
   7811   // At this point, we know we have a real, complex or pointer type.
   7812   // Now make sure the operand is a modifiable lvalue.
   7813   if (CheckForModifiableLvalue(Op, OpLoc, S))
   7814     return QualType();
   7815   // In C++, a prefix increment is the same type as the operand. Otherwise
   7816   // (in C or with postfix), the increment is the unqualified type of the
   7817   // operand.
   7818   if (IsPrefix && S.getLangOpts().CPlusPlus) {
   7819     VK = VK_LValue;
   7820     return ResType;
   7821   } else {
   7822     VK = VK_RValue;
   7823     return ResType.getUnqualifiedType();
   7824   }
   7825 }
   7826 
   7827 
   7828 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
   7829 /// This routine allows us to typecheck complex/recursive expressions
   7830 /// where the declaration is needed for type checking. We only need to
   7831 /// handle cases when the expression references a function designator
   7832 /// or is an lvalue. Here are some examples:
   7833 ///  - &(x) => x
   7834 ///  - &*****f => f for f a function designator.
   7835 ///  - &s.xx => s
   7836 ///  - &s.zz[1].yy -> s, if zz is an array
   7837 ///  - *(x + 1) -> x, if x is an array
   7838 ///  - &"123"[2] -> 0
   7839 ///  - & __real__ x -> x
   7840 static ValueDecl *getPrimaryDecl(Expr *E) {
   7841   switch (E->getStmtClass()) {
   7842   case Stmt::DeclRefExprClass:
   7843     return cast<DeclRefExpr>(E)->getDecl();
   7844   case Stmt::MemberExprClass:
   7845     // If this is an arrow operator, the address is an offset from
   7846     // the base's value, so the object the base refers to is
   7847     // irrelevant.
   7848     if (cast<MemberExpr>(E)->isArrow())
   7849       return 0;
   7850     // Otherwise, the expression refers to a part of the base
   7851     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
   7852   case Stmt::ArraySubscriptExprClass: {
   7853     // FIXME: This code shouldn't be necessary!  We should catch the implicit
   7854     // promotion of register arrays earlier.
   7855     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
   7856     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
   7857       if (ICE->getSubExpr()->getType()->isArrayType())
   7858         return getPrimaryDecl(ICE->getSubExpr());
   7859     }
   7860     return 0;
   7861   }
   7862   case Stmt::UnaryOperatorClass: {
   7863     UnaryOperator *UO = cast<UnaryOperator>(E);
   7864 
   7865     switch(UO->getOpcode()) {
   7866     case UO_Real:
   7867     case UO_Imag:
   7868     case UO_Extension:
   7869       return getPrimaryDecl(UO->getSubExpr());
   7870     default:
   7871       return 0;
   7872     }
   7873   }
   7874   case Stmt::ParenExprClass:
   7875     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
   7876   case Stmt::ImplicitCastExprClass:
   7877     // If the result of an implicit cast is an l-value, we care about
   7878     // the sub-expression; otherwise, the result here doesn't matter.
   7879     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
   7880   default:
   7881     return 0;
   7882   }
   7883 }
   7884 
   7885 namespace {
   7886   enum {
   7887     AO_Bit_Field = 0,
   7888     AO_Vector_Element = 1,
   7889     AO_Property_Expansion = 2,
   7890     AO_Register_Variable = 3,
   7891     AO_No_Error = 4
   7892   };
   7893 }
   7894 /// \brief Diagnose invalid operand for address of operations.
   7895 ///
   7896 /// \param Type The type of operand which cannot have its address taken.
   7897 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
   7898                                          Expr *E, unsigned Type) {
   7899   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
   7900 }
   7901 
   7902 /// CheckAddressOfOperand - The operand of & must be either a function
   7903 /// designator or an lvalue designating an object. If it is an lvalue, the
   7904 /// object cannot be declared with storage class register or be a bit field.
   7905 /// Note: The usual conversions are *not* applied to the operand of the &
   7906 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
   7907 /// In C++, the operand might be an overloaded function name, in which case
   7908 /// we allow the '&' but retain the overloaded-function type.
   7909 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
   7910                                       SourceLocation OpLoc) {
   7911   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
   7912     if (PTy->getKind() == BuiltinType::Overload) {
   7913       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
   7914         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
   7915           << OrigOp.get()->getSourceRange();
   7916         return QualType();
   7917       }
   7918 
   7919       return S.Context.OverloadTy;
   7920     }
   7921 
   7922     if (PTy->getKind() == BuiltinType::UnknownAny)
   7923       return S.Context.UnknownAnyTy;
   7924 
   7925     if (PTy->getKind() == BuiltinType::BoundMember) {
   7926       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
   7927         << OrigOp.get()->getSourceRange();
   7928       return QualType();
   7929     }
   7930 
   7931     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
   7932     if (OrigOp.isInvalid()) return QualType();
   7933   }
   7934 
   7935   if (OrigOp.get()->isTypeDependent())
   7936     return S.Context.DependentTy;
   7937 
   7938   assert(!OrigOp.get()->getType()->isPlaceholderType());
   7939 
   7940   // Make sure to ignore parentheses in subsequent checks
   7941   Expr *op = OrigOp.get()->IgnoreParens();
   7942 
   7943   if (S.getLangOpts().C99) {
   7944     // Implement C99-only parts of addressof rules.
   7945     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
   7946       if (uOp->getOpcode() == UO_Deref)
   7947         // Per C99 6.5.3.2, the address of a deref always returns a valid result
   7948         // (assuming the deref expression is valid).
   7949         return uOp->getSubExpr()->getType();
   7950     }
   7951     // Technically, there should be a check for array subscript
   7952     // expressions here, but the result of one is always an lvalue anyway.
   7953   }
   7954   ValueDecl *dcl = getPrimaryDecl(op);
   7955   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
   7956   unsigned AddressOfError = AO_No_Error;
   7957 
   7958   if (lval == Expr::LV_ClassTemporary) {
   7959     bool sfinae = S.isSFINAEContext();
   7960     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
   7961                          : diag::ext_typecheck_addrof_class_temporary)
   7962       << op->getType() << op->getSourceRange();
   7963     if (sfinae)
   7964       return QualType();
   7965   } else if (isa<ObjCSelectorExpr>(op)) {
   7966     return S.Context.getPointerType(op->getType());
   7967   } else if (lval == Expr::LV_MemberFunction) {
   7968     // If it's an instance method, make a member pointer.
   7969     // The expression must have exactly the form &A::foo.
   7970 
   7971     // If the underlying expression isn't a decl ref, give up.
   7972     if (!isa<DeclRefExpr>(op)) {
   7973       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
   7974         << OrigOp.get()->getSourceRange();
   7975       return QualType();
   7976     }
   7977     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
   7978     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
   7979 
   7980     // The id-expression was parenthesized.
   7981     if (OrigOp.get() != DRE) {
   7982       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
   7983         << OrigOp.get()->getSourceRange();
   7984 
   7985     // The method was named without a qualifier.
   7986     } else if (!DRE->getQualifier()) {
   7987       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
   7988         << op->getSourceRange();
   7989     }
   7990 
   7991     return S.Context.getMemberPointerType(op->getType(),
   7992               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
   7993   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
   7994     // C99 6.5.3.2p1
   7995     // The operand must be either an l-value or a function designator
   7996     if (!op->getType()->isFunctionType()) {
   7997       // Use a special diagnostic for loads from property references.
   7998       if (isa<PseudoObjectExpr>(op)) {
   7999         AddressOfError = AO_Property_Expansion;
   8000       } else {
   8001         // FIXME: emit more specific diag...
   8002         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
   8003           << op->getSourceRange();
   8004         return QualType();
   8005       }
   8006     }
   8007   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
   8008     // The operand cannot be a bit-field
   8009     AddressOfError = AO_Bit_Field;
   8010   } else if (op->getObjectKind() == OK_VectorComponent) {
   8011     // The operand cannot be an element of a vector
   8012     AddressOfError = AO_Vector_Element;
   8013   } else if (dcl) { // C99 6.5.3.2p1
   8014     // We have an lvalue with a decl. Make sure the decl is not declared
   8015     // with the register storage-class specifier.
   8016     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
   8017       // in C++ it is not error to take address of a register
   8018       // variable (c++03 7.1.1P3)
   8019       if (vd->getStorageClass() == SC_Register &&
   8020           !S.getLangOpts().CPlusPlus) {
   8021         AddressOfError = AO_Register_Variable;
   8022       }
   8023     } else if (isa<FunctionTemplateDecl>(dcl)) {
   8024       return S.Context.OverloadTy;
   8025     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
   8026       // Okay: we can take the address of a field.
   8027       // Could be a pointer to member, though, if there is an explicit
   8028       // scope qualifier for the class.
   8029       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
   8030         DeclContext *Ctx = dcl->getDeclContext();
   8031         if (Ctx && Ctx->isRecord()) {
   8032           if (dcl->getType()->isReferenceType()) {
   8033             S.Diag(OpLoc,
   8034                    diag::err_cannot_form_pointer_to_member_of_reference_type)
   8035               << dcl->getDeclName() << dcl->getType();
   8036             return QualType();
   8037           }
   8038 
   8039           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
   8040             Ctx = Ctx->getParent();
   8041           return S.Context.getMemberPointerType(op->getType(),
   8042                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
   8043         }
   8044       }
   8045     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
   8046       llvm_unreachable("Unknown/unexpected decl type");
   8047   }
   8048 
   8049   if (AddressOfError != AO_No_Error) {
   8050     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
   8051     return QualType();
   8052   }
   8053 
   8054   if (lval == Expr::LV_IncompleteVoidType) {
   8055     // Taking the address of a void variable is technically illegal, but we
   8056     // allow it in cases which are otherwise valid.
   8057     // Example: "extern void x; void* y = &x;".
   8058     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
   8059   }
   8060 
   8061   // If the operand has type "type", the result has type "pointer to type".
   8062   if (op->getType()->isObjCObjectType())
   8063     return S.Context.getObjCObjectPointerType(op->getType());
   8064   return S.Context.getPointerType(op->getType());
   8065 }
   8066 
   8067 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
   8068 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
   8069                                         SourceLocation OpLoc) {
   8070   if (Op->isTypeDependent())
   8071     return S.Context.DependentTy;
   8072 
   8073   ExprResult ConvResult = S.UsualUnaryConversions(Op);
   8074   if (ConvResult.isInvalid())
   8075     return QualType();
   8076   Op = ConvResult.take();
   8077   QualType OpTy = Op->getType();
   8078   QualType Result;
   8079 
   8080   if (isa<CXXReinterpretCastExpr>(Op)) {
   8081     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
   8082     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
   8083                                      Op->getSourceRange());
   8084   }
   8085 
   8086   // Note that per both C89 and C99, indirection is always legal, even if OpTy
   8087   // is an incomplete type or void.  It would be possible to warn about
   8088   // dereferencing a void pointer, but it's completely well-defined, and such a
   8089   // warning is unlikely to catch any mistakes.
   8090   if (const PointerType *PT = OpTy->getAs<PointerType>())
   8091     Result = PT->getPointeeType();
   8092   else if (const ObjCObjectPointerType *OPT =
   8093              OpTy->getAs<ObjCObjectPointerType>())
   8094     Result = OPT->getPointeeType();
   8095   else {
   8096     ExprResult PR = S.CheckPlaceholderExpr(Op);
   8097     if (PR.isInvalid()) return QualType();
   8098     if (PR.take() != Op)
   8099       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
   8100   }
   8101 
   8102   if (Result.isNull()) {
   8103     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
   8104       << OpTy << Op->getSourceRange();
   8105     return QualType();
   8106   }
   8107 
   8108   // Dereferences are usually l-values...
   8109   VK = VK_LValue;
   8110 
   8111   // ...except that certain expressions are never l-values in C.
   8112   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
   8113     VK = VK_RValue;
   8114 
   8115   return Result;
   8116 }
   8117 
   8118 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
   8119   tok::TokenKind Kind) {
   8120   BinaryOperatorKind Opc;
   8121   switch (Kind) {
   8122   default: llvm_unreachable("Unknown binop!");
   8123   case tok::periodstar:           Opc = BO_PtrMemD; break;
   8124   case tok::arrowstar:            Opc = BO_PtrMemI; break;
   8125   case tok::star:                 Opc = BO_Mul; break;
   8126   case tok::slash:                Opc = BO_Div; break;
   8127   case tok::percent:              Opc = BO_Rem; break;
   8128   case tok::plus:                 Opc = BO_Add; break;
   8129   case tok::minus:                Opc = BO_Sub; break;
   8130   case tok::lessless:             Opc = BO_Shl; break;
   8131   case tok::greatergreater:       Opc = BO_Shr; break;
   8132   case tok::lessequal:            Opc = BO_LE; break;
   8133   case tok::less:                 Opc = BO_LT; break;
   8134   case tok::greaterequal:         Opc = BO_GE; break;
   8135   case tok::greater:              Opc = BO_GT; break;
   8136   case tok::exclaimequal:         Opc = BO_NE; break;
   8137   case tok::equalequal:           Opc = BO_EQ; break;
   8138   case tok::amp:                  Opc = BO_And; break;
   8139   case tok::caret:                Opc = BO_Xor; break;
   8140   case tok::pipe:                 Opc = BO_Or; break;
   8141   case tok::ampamp:               Opc = BO_LAnd; break;
   8142   case tok::pipepipe:             Opc = BO_LOr; break;
   8143   case tok::equal:                Opc = BO_Assign; break;
   8144   case tok::starequal:            Opc = BO_MulAssign; break;
   8145   case tok::slashequal:           Opc = BO_DivAssign; break;
   8146   case tok::percentequal:         Opc = BO_RemAssign; break;
   8147   case tok::plusequal:            Opc = BO_AddAssign; break;
   8148   case tok::minusequal:           Opc = BO_SubAssign; break;
   8149   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
   8150   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
   8151   case tok::ampequal:             Opc = BO_AndAssign; break;
   8152   case tok::caretequal:           Opc = BO_XorAssign; break;
   8153   case tok::pipeequal:            Opc = BO_OrAssign; break;
   8154   case tok::comma:                Opc = BO_Comma; break;
   8155   }
   8156   return Opc;
   8157 }
   8158 
   8159 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
   8160   tok::TokenKind Kind) {
   8161   UnaryOperatorKind Opc;
   8162   switch (Kind) {
   8163   default: llvm_unreachable("Unknown unary op!");
   8164   case tok::plusplus:     Opc = UO_PreInc; break;
   8165   case tok::minusminus:   Opc = UO_PreDec; break;
   8166   case tok::amp:          Opc = UO_AddrOf; break;
   8167   case tok::star:         Opc = UO_Deref; break;
   8168   case tok::plus:         Opc = UO_Plus; break;
   8169   case tok::minus:        Opc = UO_Minus; break;
   8170   case tok::tilde:        Opc = UO_Not; break;
   8171   case tok::exclaim:      Opc = UO_LNot; break;
   8172   case tok::kw___real:    Opc = UO_Real; break;
   8173   case tok::kw___imag:    Opc = UO_Imag; break;
   8174   case tok::kw___extension__: Opc = UO_Extension; break;
   8175   }
   8176   return Opc;
   8177 }
   8178 
   8179 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
   8180 /// This warning is only emitted for builtin assignment operations. It is also
   8181 /// suppressed in the event of macro expansions.
   8182 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
   8183                                    SourceLocation OpLoc) {
   8184   if (!S.ActiveTemplateInstantiations.empty())
   8185     return;
   8186   if (OpLoc.isInvalid() || OpLoc.isMacroID())
   8187     return;
   8188   LHSExpr = LHSExpr->IgnoreParenImpCasts();
   8189   RHSExpr = RHSExpr->IgnoreParenImpCasts();
   8190   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
   8191   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
   8192   if (!LHSDeclRef || !RHSDeclRef ||
   8193       LHSDeclRef->getLocation().isMacroID() ||
   8194       RHSDeclRef->getLocation().isMacroID())
   8195     return;
   8196   const ValueDecl *LHSDecl =
   8197     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
   8198   const ValueDecl *RHSDecl =
   8199     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
   8200   if (LHSDecl != RHSDecl)
   8201     return;
   8202   if (LHSDecl->getType().isVolatileQualified())
   8203     return;
   8204   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
   8205     if (RefTy->getPointeeType().isVolatileQualified())
   8206       return;
   8207 
   8208   S.Diag(OpLoc, diag::warn_self_assignment)
   8209       << LHSDeclRef->getType()
   8210       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
   8211 }
   8212 
   8213 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
   8214 /// operator @p Opc at location @c TokLoc. This routine only supports
   8215 /// built-in operations; ActOnBinOp handles overloaded operators.
   8216 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
   8217                                     BinaryOperatorKind Opc,
   8218                                     Expr *LHSExpr, Expr *RHSExpr) {
   8219   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
   8220     // The syntax only allows initializer lists on the RHS of assignment,
   8221     // so we don't need to worry about accepting invalid code for
   8222     // non-assignment operators.
   8223     // C++11 5.17p9:
   8224     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
   8225     //   of x = {} is x = T().
   8226     InitializationKind Kind =
   8227         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
   8228     InitializedEntity Entity =
   8229         InitializedEntity::InitializeTemporary(LHSExpr->getType());
   8230     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
   8231     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
   8232     if (Init.isInvalid())
   8233       return Init;
   8234     RHSExpr = Init.take();
   8235   }
   8236 
   8237   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
   8238   QualType ResultTy;     // Result type of the binary operator.
   8239   // The following two variables are used for compound assignment operators
   8240   QualType CompLHSTy;    // Type of LHS after promotions for computation
   8241   QualType CompResultTy; // Type of computation result
   8242   ExprValueKind VK = VK_RValue;
   8243   ExprObjectKind OK = OK_Ordinary;
   8244 
   8245   switch (Opc) {
   8246   case BO_Assign:
   8247     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
   8248     if (getLangOpts().CPlusPlus &&
   8249         LHS.get()->getObjectKind() != OK_ObjCProperty) {
   8250       VK = LHS.get()->getValueKind();
   8251       OK = LHS.get()->getObjectKind();
   8252     }
   8253     if (!ResultTy.isNull())
   8254       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
   8255     break;
   8256   case BO_PtrMemD:
   8257   case BO_PtrMemI:
   8258     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
   8259                                             Opc == BO_PtrMemI);
   8260     break;
   8261   case BO_Mul:
   8262   case BO_Div:
   8263     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
   8264                                            Opc == BO_Div);
   8265     break;
   8266   case BO_Rem:
   8267     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
   8268     break;
   8269   case BO_Add:
   8270     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
   8271     break;
   8272   case BO_Sub:
   8273     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
   8274     break;
   8275   case BO_Shl:
   8276   case BO_Shr:
   8277     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
   8278     break;
   8279   case BO_LE:
   8280   case BO_LT:
   8281   case BO_GE:
   8282   case BO_GT:
   8283     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
   8284     break;
   8285   case BO_EQ:
   8286   case BO_NE:
   8287     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
   8288     break;
   8289   case BO_And:
   8290   case BO_Xor:
   8291   case BO_Or:
   8292     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
   8293     break;
   8294   case BO_LAnd:
   8295   case BO_LOr:
   8296     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
   8297     break;
   8298   case BO_MulAssign:
   8299   case BO_DivAssign:
   8300     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
   8301                                                Opc == BO_DivAssign);
   8302     CompLHSTy = CompResultTy;
   8303     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8304       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8305     break;
   8306   case BO_RemAssign:
   8307     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
   8308     CompLHSTy = CompResultTy;
   8309     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8310       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8311     break;
   8312   case BO_AddAssign:
   8313     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
   8314     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8315       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8316     break;
   8317   case BO_SubAssign:
   8318     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
   8319     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8320       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8321     break;
   8322   case BO_ShlAssign:
   8323   case BO_ShrAssign:
   8324     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
   8325     CompLHSTy = CompResultTy;
   8326     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8327       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8328     break;
   8329   case BO_AndAssign:
   8330   case BO_XorAssign:
   8331   case BO_OrAssign:
   8332     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
   8333     CompLHSTy = CompResultTy;
   8334     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
   8335       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
   8336     break;
   8337   case BO_Comma:
   8338     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
   8339     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
   8340       VK = RHS.get()->getValueKind();
   8341       OK = RHS.get()->getObjectKind();
   8342     }
   8343     break;
   8344   }
   8345   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
   8346     return ExprError();
   8347 
   8348   // Check for array bounds violations for both sides of the BinaryOperator
   8349   CheckArrayAccess(LHS.get());
   8350   CheckArrayAccess(RHS.get());
   8351 
   8352   if (CompResultTy.isNull())
   8353     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
   8354                                               ResultTy, VK, OK, OpLoc));
   8355   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
   8356       OK_ObjCProperty) {
   8357     VK = VK_LValue;
   8358     OK = LHS.get()->getObjectKind();
   8359   }
   8360   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
   8361                                                     ResultTy, VK, OK, CompLHSTy,
   8362                                                     CompResultTy, OpLoc));
   8363 }
   8364 
   8365 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
   8366 /// operators are mixed in a way that suggests that the programmer forgot that
   8367 /// comparison operators have higher precedence. The most typical example of
   8368 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
   8369 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
   8370                                       SourceLocation OpLoc, Expr *LHSExpr,
   8371                                       Expr *RHSExpr) {
   8372   typedef BinaryOperator BinOp;
   8373   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
   8374                 RHSopc = static_cast<BinOp::Opcode>(-1);
   8375   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
   8376     LHSopc = BO->getOpcode();
   8377   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
   8378     RHSopc = BO->getOpcode();
   8379 
   8380   // Subs are not binary operators.
   8381   if (LHSopc == -1 && RHSopc == -1)
   8382     return;
   8383 
   8384   // Bitwise operations are sometimes used as eager logical ops.
   8385   // Don't diagnose this.
   8386   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
   8387       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
   8388     return;
   8389 
   8390   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
   8391   bool isRightComp = BinOp::isComparisonOp(RHSopc);
   8392   if (!isLeftComp && !isRightComp) return;
   8393 
   8394   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
   8395                                                    OpLoc)
   8396                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
   8397   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
   8398                                  : BinOp::getOpcodeStr(RHSopc);
   8399   SourceRange ParensRange = isLeftComp ?
   8400       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
   8401                   RHSExpr->getLocEnd())
   8402     : SourceRange(LHSExpr->getLocStart(),
   8403                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
   8404 
   8405   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
   8406     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
   8407   SuggestParentheses(Self, OpLoc,
   8408     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
   8409     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
   8410   SuggestParentheses(Self, OpLoc,
   8411     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
   8412     ParensRange);
   8413 }
   8414 
   8415 /// \brief It accepts a '&' expr that is inside a '|' one.
   8416 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
   8417 /// in parentheses.
   8418 static void
   8419 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
   8420                                        BinaryOperator *Bop) {
   8421   assert(Bop->getOpcode() == BO_And);
   8422   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
   8423       << Bop->getSourceRange() << OpLoc;
   8424   SuggestParentheses(Self, Bop->getOperatorLoc(),
   8425     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
   8426     Bop->getSourceRange());
   8427 }
   8428 
   8429 /// \brief It accepts a '&&' expr that is inside a '||' one.
   8430 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
   8431 /// in parentheses.
   8432 static void
   8433 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
   8434                                        BinaryOperator *Bop) {
   8435   assert(Bop->getOpcode() == BO_LAnd);
   8436   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
   8437       << Bop->getSourceRange() << OpLoc;
   8438   SuggestParentheses(Self, Bop->getOperatorLoc(),
   8439     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
   8440     Bop->getSourceRange());
   8441 }
   8442 
   8443 /// \brief Returns true if the given expression can be evaluated as a constant
   8444 /// 'true'.
   8445 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
   8446   bool Res;
   8447   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
   8448 }
   8449 
   8450 /// \brief Returns true if the given expression can be evaluated as a constant
   8451 /// 'false'.
   8452 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
   8453   bool Res;
   8454   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
   8455 }
   8456 
   8457 /// \brief Look for '&&' in the left hand of a '||' expr.
   8458 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
   8459                                              Expr *LHSExpr, Expr *RHSExpr) {
   8460   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
   8461     if (Bop->getOpcode() == BO_LAnd) {
   8462       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
   8463       if (EvaluatesAsFalse(S, RHSExpr))
   8464         return;
   8465       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
   8466       if (!EvaluatesAsTrue(S, Bop->getLHS()))
   8467         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
   8468     } else if (Bop->getOpcode() == BO_LOr) {
   8469       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
   8470         // If it's "a || b && 1 || c" we didn't warn earlier for
   8471         // "a || b && 1", but warn now.
   8472         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
   8473           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
   8474       }
   8475     }
   8476   }
   8477 }
   8478 
   8479 /// \brief Look for '&&' in the right hand of a '||' expr.
   8480 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
   8481                                              Expr *LHSExpr, Expr *RHSExpr) {
   8482   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
   8483     if (Bop->getOpcode() == BO_LAnd) {
   8484       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
   8485       if (EvaluatesAsFalse(S, LHSExpr))
   8486         return;
   8487       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
   8488       if (!EvaluatesAsTrue(S, Bop->getRHS()))
   8489         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
   8490     }
   8491   }
   8492 }
   8493 
   8494 /// \brief Look for '&' in the left or right hand of a '|' expr.
   8495 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
   8496                                              Expr *OrArg) {
   8497   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
   8498     if (Bop->getOpcode() == BO_And)
   8499       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
   8500   }
   8501 }
   8502 
   8503 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
   8504 /// precedence.
   8505 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
   8506                                     SourceLocation OpLoc, Expr *LHSExpr,
   8507                                     Expr *RHSExpr){
   8508   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
   8509   if (BinaryOperator::isBitwiseOp(Opc))
   8510     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
   8511 
   8512   // Diagnose "arg1 & arg2 | arg3"
   8513   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
   8514     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
   8515     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
   8516   }
   8517 
   8518   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
   8519   // We don't warn for 'assert(a || b && "bad")' since this is safe.
   8520   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
   8521     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
   8522     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
   8523   }
   8524 }
   8525 
   8526 // Binary Operators.  'Tok' is the token for the operator.
   8527 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
   8528                             tok::TokenKind Kind,
   8529                             Expr *LHSExpr, Expr *RHSExpr) {
   8530   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
   8531   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
   8532   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
   8533 
   8534   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
   8535   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
   8536 
   8537   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
   8538 }
   8539 
   8540 /// Build an overloaded binary operator expression in the given scope.
   8541 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
   8542                                        BinaryOperatorKind Opc,
   8543                                        Expr *LHS, Expr *RHS) {
   8544   // Find all of the overloaded operators visible from this
   8545   // point. We perform both an operator-name lookup from the local
   8546   // scope and an argument-dependent lookup based on the types of
   8547   // the arguments.
   8548   UnresolvedSet<16> Functions;
   8549   OverloadedOperatorKind OverOp
   8550     = BinaryOperator::getOverloadedOperator(Opc);
   8551   if (Sc && OverOp != OO_None)
   8552     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
   8553                                    RHS->getType(), Functions);
   8554 
   8555   // Build the (potentially-overloaded, potentially-dependent)
   8556   // binary operation.
   8557   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
   8558 }
   8559 
   8560 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
   8561                             BinaryOperatorKind Opc,
   8562                             Expr *LHSExpr, Expr *RHSExpr) {
   8563   // We want to end up calling one of checkPseudoObjectAssignment
   8564   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
   8565   // both expressions are overloadable or either is type-dependent),
   8566   // or CreateBuiltinBinOp (in any other case).  We also want to get
   8567   // any placeholder types out of the way.
   8568 
   8569   // Handle pseudo-objects in the LHS.
   8570   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
   8571     // Assignments with a pseudo-object l-value need special analysis.
   8572     if (pty->getKind() == BuiltinType::PseudoObject &&
   8573         BinaryOperator::isAssignmentOp(Opc))
   8574       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
   8575 
   8576     // Don't resolve overloads if the other type is overloadable.
   8577     if (pty->getKind() == BuiltinType::Overload) {
   8578       // We can't actually test that if we still have a placeholder,
   8579       // though.  Fortunately, none of the exceptions we see in that
   8580       // code below are valid when the LHS is an overload set.  Note
   8581       // that an overload set can be dependently-typed, but it never
   8582       // instantiates to having an overloadable type.
   8583       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
   8584       if (resolvedRHS.isInvalid()) return ExprError();
   8585       RHSExpr = resolvedRHS.take();
   8586 
   8587       if (RHSExpr->isTypeDependent() ||
   8588           RHSExpr->getType()->isOverloadableType())
   8589         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8590     }
   8591 
   8592     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
   8593     if (LHS.isInvalid()) return ExprError();
   8594     LHSExpr = LHS.take();
   8595   }
   8596 
   8597   // Handle pseudo-objects in the RHS.
   8598   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
   8599     // An overload in the RHS can potentially be resolved by the type
   8600     // being assigned to.
   8601     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
   8602       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
   8603         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8604 
   8605       if (LHSExpr->getType()->isOverloadableType())
   8606         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8607 
   8608       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
   8609     }
   8610 
   8611     // Don't resolve overloads if the other type is overloadable.
   8612     if (pty->getKind() == BuiltinType::Overload &&
   8613         LHSExpr->getType()->isOverloadableType())
   8614       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8615 
   8616     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
   8617     if (!resolvedRHS.isUsable()) return ExprError();
   8618     RHSExpr = resolvedRHS.take();
   8619   }
   8620 
   8621   if (getLangOpts().CPlusPlus) {
   8622     // If either expression is type-dependent, always build an
   8623     // overloaded op.
   8624     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
   8625       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8626 
   8627     // Otherwise, build an overloaded op if either expression has an
   8628     // overloadable type.
   8629     if (LHSExpr->getType()->isOverloadableType() ||
   8630         RHSExpr->getType()->isOverloadableType())
   8631       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   8632   }
   8633 
   8634   // Build a built-in binary operation.
   8635   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
   8636 }
   8637 
   8638 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
   8639                                       UnaryOperatorKind Opc,
   8640                                       Expr *InputExpr) {
   8641   ExprResult Input = Owned(InputExpr);
   8642   ExprValueKind VK = VK_RValue;
   8643   ExprObjectKind OK = OK_Ordinary;
   8644   QualType resultType;
   8645   switch (Opc) {
   8646   case UO_PreInc:
   8647   case UO_PreDec:
   8648   case UO_PostInc:
   8649   case UO_PostDec:
   8650     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
   8651                                                 Opc == UO_PreInc ||
   8652                                                 Opc == UO_PostInc,
   8653                                                 Opc == UO_PreInc ||
   8654                                                 Opc == UO_PreDec);
   8655     break;
   8656   case UO_AddrOf:
   8657     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
   8658     break;
   8659   case UO_Deref: {
   8660     Input = DefaultFunctionArrayLvalueConversion(Input.take());
   8661     if (Input.isInvalid()) return ExprError();
   8662     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
   8663     break;
   8664   }
   8665   case UO_Plus:
   8666   case UO_Minus:
   8667     Input = UsualUnaryConversions(Input.take());
   8668     if (Input.isInvalid()) return ExprError();
   8669     resultType = Input.get()->getType();
   8670     if (resultType->isDependentType())
   8671       break;
   8672     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
   8673         resultType->isVectorType())
   8674       break;
   8675     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
   8676              resultType->isEnumeralType())
   8677       break;
   8678     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
   8679              Opc == UO_Plus &&
   8680              resultType->isPointerType())
   8681       break;
   8682 
   8683     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
   8684       << resultType << Input.get()->getSourceRange());
   8685 
   8686   case UO_Not: // bitwise complement
   8687     Input = UsualUnaryConversions(Input.take());
   8688     if (Input.isInvalid()) return ExprError();
   8689     resultType = Input.get()->getType();
   8690     if (resultType->isDependentType())
   8691       break;
   8692     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
   8693     if (resultType->isComplexType() || resultType->isComplexIntegerType())
   8694       // C99 does not support '~' for complex conjugation.
   8695       Diag(OpLoc, diag::ext_integer_complement_complex)
   8696         << resultType << Input.get()->getSourceRange();
   8697     else if (resultType->hasIntegerRepresentation())
   8698       break;
   8699     else {
   8700       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
   8701         << resultType << Input.get()->getSourceRange());
   8702     }
   8703     break;
   8704 
   8705   case UO_LNot: // logical negation
   8706     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
   8707     Input = DefaultFunctionArrayLvalueConversion(Input.take());
   8708     if (Input.isInvalid()) return ExprError();
   8709     resultType = Input.get()->getType();
   8710 
   8711     // Though we still have to promote half FP to float...
   8712     if (resultType->isHalfType()) {
   8713       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
   8714       resultType = Context.FloatTy;
   8715     }
   8716 
   8717     if (resultType->isDependentType())
   8718       break;
   8719     if (resultType->isScalarType()) {
   8720       // C99 6.5.3.3p1: ok, fallthrough;
   8721       if (Context.getLangOpts().CPlusPlus) {
   8722         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
   8723         // operand contextually converted to bool.
   8724         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
   8725                                   ScalarTypeToBooleanCastKind(resultType));
   8726       }
   8727     } else if (resultType->isExtVectorType()) {
   8728       // Vector logical not returns the signed variant of the operand type.
   8729       resultType = GetSignedVectorType(resultType);
   8730       break;
   8731     } else {
   8732       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
   8733         << resultType << Input.get()->getSourceRange());
   8734     }
   8735 
   8736     // LNot always has type int. C99 6.5.3.3p5.
   8737     // In C++, it's bool. C++ 5.3.1p8
   8738     resultType = Context.getLogicalOperationType();
   8739     break;
   8740   case UO_Real:
   8741   case UO_Imag:
   8742     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
   8743     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
   8744     // complex l-values to ordinary l-values and all other values to r-values.
   8745     if (Input.isInvalid()) return ExprError();
   8746     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
   8747       if (Input.get()->getValueKind() != VK_RValue &&
   8748           Input.get()->getObjectKind() == OK_Ordinary)
   8749         VK = Input.get()->getValueKind();
   8750     } else if (!getLangOpts().CPlusPlus) {
   8751       // In C, a volatile scalar is read by __imag. In C++, it is not.
   8752       Input = DefaultLvalueConversion(Input.take());
   8753     }
   8754     break;
   8755   case UO_Extension:
   8756     resultType = Input.get()->getType();
   8757     VK = Input.get()->getValueKind();
   8758     OK = Input.get()->getObjectKind();
   8759     break;
   8760   }
   8761   if (resultType.isNull() || Input.isInvalid())
   8762     return ExprError();
   8763 
   8764   // Check for array bounds violations in the operand of the UnaryOperator,
   8765   // except for the '*' and '&' operators that have to be handled specially
   8766   // by CheckArrayAccess (as there are special cases like &array[arraysize]
   8767   // that are explicitly defined as valid by the standard).
   8768   if (Opc != UO_AddrOf && Opc != UO_Deref)
   8769     CheckArrayAccess(Input.get());
   8770 
   8771   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
   8772                                            VK, OK, OpLoc));
   8773 }
   8774 
   8775 /// \brief Determine whether the given expression is a qualified member
   8776 /// access expression, of a form that could be turned into a pointer to member
   8777 /// with the address-of operator.
   8778 static bool isQualifiedMemberAccess(Expr *E) {
   8779   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   8780     if (!DRE->getQualifier())
   8781       return false;
   8782 
   8783     ValueDecl *VD = DRE->getDecl();
   8784     if (!VD->isCXXClassMember())
   8785       return false;
   8786 
   8787     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
   8788       return true;
   8789     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
   8790       return Method->isInstance();
   8791 
   8792     return false;
   8793   }
   8794 
   8795   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
   8796     if (!ULE->getQualifier())
   8797       return false;
   8798 
   8799     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
   8800                                            DEnd = ULE->decls_end();
   8801          D != DEnd; ++D) {
   8802       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
   8803         if (Method->isInstance())
   8804           return true;
   8805       } else {
   8806         // Overload set does not contain methods.
   8807         break;
   8808       }
   8809     }
   8810 
   8811     return false;
   8812   }
   8813 
   8814   return false;
   8815 }
   8816 
   8817 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
   8818                               UnaryOperatorKind Opc, Expr *Input) {
   8819   // First things first: handle placeholders so that the
   8820   // overloaded-operator check considers the right type.
   8821   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
   8822     // Increment and decrement of pseudo-object references.
   8823     if (pty->getKind() == BuiltinType::PseudoObject &&
   8824         UnaryOperator::isIncrementDecrementOp(Opc))
   8825       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
   8826 
   8827     // extension is always a builtin operator.
   8828     if (Opc == UO_Extension)
   8829       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
   8830 
   8831     // & gets special logic for several kinds of placeholder.
   8832     // The builtin code knows what to do.
   8833     if (Opc == UO_AddrOf &&
   8834         (pty->getKind() == BuiltinType::Overload ||
   8835          pty->getKind() == BuiltinType::UnknownAny ||
   8836          pty->getKind() == BuiltinType::BoundMember))
   8837       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
   8838 
   8839     // Anything else needs to be handled now.
   8840     ExprResult Result = CheckPlaceholderExpr(Input);
   8841     if (Result.isInvalid()) return ExprError();
   8842     Input = Result.take();
   8843   }
   8844 
   8845   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
   8846       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
   8847       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
   8848     // Find all of the overloaded operators visible from this
   8849     // point. We perform both an operator-name lookup from the local
   8850     // scope and an argument-dependent lookup based on the types of
   8851     // the arguments.
   8852     UnresolvedSet<16> Functions;
   8853     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
   8854     if (S && OverOp != OO_None)
   8855       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
   8856                                    Functions);
   8857 
   8858     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
   8859   }
   8860 
   8861   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
   8862 }
   8863 
   8864 // Unary Operators.  'Tok' is the token for the operator.
   8865 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
   8866                               tok::TokenKind Op, Expr *Input) {
   8867   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
   8868 }
   8869 
   8870 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
   8871 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
   8872                                 LabelDecl *TheDecl) {
   8873   TheDecl->setUsed();
   8874   // Create the AST node.  The address of a label always has type 'void*'.
   8875   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
   8876                                        Context.getPointerType(Context.VoidTy)));
   8877 }
   8878 
   8879 /// Given the last statement in a statement-expression, check whether
   8880 /// the result is a producing expression (like a call to an
   8881 /// ns_returns_retained function) and, if so, rebuild it to hoist the
   8882 /// release out of the full-expression.  Otherwise, return null.
   8883 /// Cannot fail.
   8884 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
   8885   // Should always be wrapped with one of these.
   8886   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
   8887   if (!cleanups) return 0;
   8888 
   8889   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
   8890   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
   8891     return 0;
   8892 
   8893   // Splice out the cast.  This shouldn't modify any interesting
   8894   // features of the statement.
   8895   Expr *producer = cast->getSubExpr();
   8896   assert(producer->getType() == cast->getType());
   8897   assert(producer->getValueKind() == cast->getValueKind());
   8898   cleanups->setSubExpr(producer);
   8899   return cleanups;
   8900 }
   8901 
   8902 void Sema::ActOnStartStmtExpr() {
   8903   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
   8904 }
   8905 
   8906 void Sema::ActOnStmtExprError() {
   8907   // Note that function is also called by TreeTransform when leaving a
   8908   // StmtExpr scope without rebuilding anything.
   8909 
   8910   DiscardCleanupsInEvaluationContext();
   8911   PopExpressionEvaluationContext();
   8912 }
   8913 
   8914 ExprResult
   8915 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
   8916                     SourceLocation RPLoc) { // "({..})"
   8917   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
   8918   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
   8919 
   8920   if (hasAnyUnrecoverableErrorsInThisFunction())
   8921     DiscardCleanupsInEvaluationContext();
   8922   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
   8923   PopExpressionEvaluationContext();
   8924 
   8925   bool isFileScope
   8926     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
   8927   if (isFileScope)
   8928     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
   8929 
   8930   // FIXME: there are a variety of strange constraints to enforce here, for
   8931   // example, it is not possible to goto into a stmt expression apparently.
   8932   // More semantic analysis is needed.
   8933 
   8934   // If there are sub stmts in the compound stmt, take the type of the last one
   8935   // as the type of the stmtexpr.
   8936   QualType Ty = Context.VoidTy;
   8937   bool StmtExprMayBindToTemp = false;
   8938   if (!Compound->body_empty()) {
   8939     Stmt *LastStmt = Compound->body_back();
   8940     LabelStmt *LastLabelStmt = 0;
   8941     // If LastStmt is a label, skip down through into the body.
   8942     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
   8943       LastLabelStmt = Label;
   8944       LastStmt = Label->getSubStmt();
   8945     }
   8946 
   8947     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
   8948       // Do function/array conversion on the last expression, but not
   8949       // lvalue-to-rvalue.  However, initialize an unqualified type.
   8950       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
   8951       if (LastExpr.isInvalid())
   8952         return ExprError();
   8953       Ty = LastExpr.get()->getType().getUnqualifiedType();
   8954 
   8955       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
   8956         // In ARC, if the final expression ends in a consume, splice
   8957         // the consume out and bind it later.  In the alternate case
   8958         // (when dealing with a retainable type), the result
   8959         // initialization will create a produce.  In both cases the
   8960         // result will be +1, and we'll need to balance that out with
   8961         // a bind.
   8962         if (Expr *rebuiltLastStmt
   8963               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
   8964           LastExpr = rebuiltLastStmt;
   8965         } else {
   8966           LastExpr = PerformCopyInitialization(
   8967                             InitializedEntity::InitializeResult(LPLoc,
   8968                                                                 Ty,
   8969                                                                 false),
   8970                                                    SourceLocation(),
   8971                                                LastExpr);
   8972         }
   8973 
   8974         if (LastExpr.isInvalid())
   8975           return ExprError();
   8976         if (LastExpr.get() != 0) {
   8977           if (!LastLabelStmt)
   8978             Compound->setLastStmt(LastExpr.take());
   8979           else
   8980             LastLabelStmt->setSubStmt(LastExpr.take());
   8981           StmtExprMayBindToTemp = true;
   8982         }
   8983       }
   8984     }
   8985   }
   8986 
   8987   // FIXME: Check that expression type is complete/non-abstract; statement
   8988   // expressions are not lvalues.
   8989   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
   8990   if (StmtExprMayBindToTemp)
   8991     return MaybeBindToTemporary(ResStmtExpr);
   8992   return Owned(ResStmtExpr);
   8993 }
   8994 
   8995 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
   8996                                       TypeSourceInfo *TInfo,
   8997                                       OffsetOfComponent *CompPtr,
   8998                                       unsigned NumComponents,
   8999                                       SourceLocation RParenLoc) {
   9000   QualType ArgTy = TInfo->getType();
   9001   bool Dependent = ArgTy->isDependentType();
   9002   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
   9003 
   9004   // We must have at least one component that refers to the type, and the first
   9005   // one is known to be a field designator.  Verify that the ArgTy represents
   9006   // a struct/union/class.
   9007   if (!Dependent && !ArgTy->isRecordType())
   9008     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
   9009                        << ArgTy << TypeRange);
   9010 
   9011   // Type must be complete per C99 7.17p3 because a declaring a variable
   9012   // with an incomplete type would be ill-formed.
   9013   if (!Dependent
   9014       && RequireCompleteType(BuiltinLoc, ArgTy,
   9015                              diag::err_offsetof_incomplete_type, TypeRange))
   9016     return ExprError();
   9017 
   9018   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
   9019   // GCC extension, diagnose them.
   9020   // FIXME: This diagnostic isn't actually visible because the location is in
   9021   // a system header!
   9022   if (NumComponents != 1)
   9023     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
   9024       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
   9025 
   9026   bool DidWarnAboutNonPOD = false;
   9027   QualType CurrentType = ArgTy;
   9028   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
   9029   SmallVector<OffsetOfNode, 4> Comps;
   9030   SmallVector<Expr*, 4> Exprs;
   9031   for (unsigned i = 0; i != NumComponents; ++i) {
   9032     const OffsetOfComponent &OC = CompPtr[i];
   9033     if (OC.isBrackets) {
   9034       // Offset of an array sub-field.  TODO: Should we allow vector elements?
   9035       if (!CurrentType->isDependentType()) {
   9036         const ArrayType *AT = Context.getAsArrayType(CurrentType);
   9037         if(!AT)
   9038           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
   9039                            << CurrentType);
   9040         CurrentType = AT->getElementType();
   9041       } else
   9042         CurrentType = Context.DependentTy;
   9043 
   9044       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
   9045       if (IdxRval.isInvalid())
   9046         return ExprError();
   9047       Expr *Idx = IdxRval.take();
   9048 
   9049       // The expression must be an integral expression.
   9050       // FIXME: An integral constant expression?
   9051       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
   9052           !Idx->getType()->isIntegerType())
   9053         return ExprError(Diag(Idx->getLocStart(),
   9054                               diag::err_typecheck_subscript_not_integer)
   9055                          << Idx->getSourceRange());
   9056 
   9057       // Record this array index.
   9058       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
   9059       Exprs.push_back(Idx);
   9060       continue;
   9061     }
   9062 
   9063     // Offset of a field.
   9064     if (CurrentType->isDependentType()) {
   9065       // We have the offset of a field, but we can't look into the dependent
   9066       // type. Just record the identifier of the field.
   9067       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
   9068       CurrentType = Context.DependentTy;
   9069       continue;
   9070     }
   9071 
   9072     // We need to have a complete type to look into.
   9073     if (RequireCompleteType(OC.LocStart, CurrentType,
   9074                             diag::err_offsetof_incomplete_type))
   9075       return ExprError();
   9076 
   9077     // Look for the designated field.
   9078     const RecordType *RC = CurrentType->getAs<RecordType>();
   9079     if (!RC)
   9080       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
   9081                        << CurrentType);
   9082     RecordDecl *RD = RC->getDecl();
   9083 
   9084     // C++ [lib.support.types]p5:
   9085     //   The macro offsetof accepts a restricted set of type arguments in this
   9086     //   International Standard. type shall be a POD structure or a POD union
   9087     //   (clause 9).
   9088     // C++11 [support.types]p4:
   9089     //   If type is not a standard-layout class (Clause 9), the results are
   9090     //   undefined.
   9091     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
   9092       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
   9093       unsigned DiagID =
   9094         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
   9095                             : diag::warn_offsetof_non_pod_type;
   9096 
   9097       if (!IsSafe && !DidWarnAboutNonPOD &&
   9098           DiagRuntimeBehavior(BuiltinLoc, 0,
   9099                               PDiag(DiagID)
   9100                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
   9101                               << CurrentType))
   9102         DidWarnAboutNonPOD = true;
   9103     }
   9104 
   9105     // Look for the field.
   9106     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
   9107     LookupQualifiedName(R, RD);
   9108     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
   9109     IndirectFieldDecl *IndirectMemberDecl = 0;
   9110     if (!MemberDecl) {
   9111       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
   9112         MemberDecl = IndirectMemberDecl->getAnonField();
   9113     }
   9114 
   9115     if (!MemberDecl)
   9116       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
   9117                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
   9118                                                               OC.LocEnd));
   9119 
   9120     // C99 7.17p3:
   9121     //   (If the specified member is a bit-field, the behavior is undefined.)
   9122     //
   9123     // We diagnose this as an error.
   9124     if (MemberDecl->isBitField()) {
   9125       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
   9126         << MemberDecl->getDeclName()
   9127         << SourceRange(BuiltinLoc, RParenLoc);
   9128       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
   9129       return ExprError();
   9130     }
   9131 
   9132     RecordDecl *Parent = MemberDecl->getParent();
   9133     if (IndirectMemberDecl)
   9134       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
   9135 
   9136     // If the member was found in a base class, introduce OffsetOfNodes for
   9137     // the base class indirections.
   9138     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   9139                        /*DetectVirtual=*/false);
   9140     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
   9141       CXXBasePath &Path = Paths.front();
   9142       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
   9143            B != BEnd; ++B)
   9144         Comps.push_back(OffsetOfNode(B->Base));
   9145     }
   9146 
   9147     if (IndirectMemberDecl) {
   9148       for (IndirectFieldDecl::chain_iterator FI =
   9149            IndirectMemberDecl->chain_begin(),
   9150            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
   9151         assert(isa<FieldDecl>(*FI));
   9152         Comps.push_back(OffsetOfNode(OC.LocStart,
   9153                                      cast<FieldDecl>(*FI), OC.LocEnd));
   9154       }
   9155     } else
   9156       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
   9157 
   9158     CurrentType = MemberDecl->getType().getNonReferenceType();
   9159   }
   9160 
   9161   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
   9162                                     TInfo, Comps, Exprs, RParenLoc));
   9163 }
   9164 
   9165 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
   9166                                       SourceLocation BuiltinLoc,
   9167                                       SourceLocation TypeLoc,
   9168                                       ParsedType ParsedArgTy,
   9169                                       OffsetOfComponent *CompPtr,
   9170                                       unsigned NumComponents,
   9171                                       SourceLocation RParenLoc) {
   9172 
   9173   TypeSourceInfo *ArgTInfo;
   9174   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
   9175   if (ArgTy.isNull())
   9176     return ExprError();
   9177 
   9178   if (!ArgTInfo)
   9179     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
   9180 
   9181   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
   9182                               RParenLoc);
   9183 }
   9184 
   9185 
   9186 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
   9187                                  Expr *CondExpr,
   9188                                  Expr *LHSExpr, Expr *RHSExpr,
   9189                                  SourceLocation RPLoc) {
   9190   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
   9191 
   9192   ExprValueKind VK = VK_RValue;
   9193   ExprObjectKind OK = OK_Ordinary;
   9194   QualType resType;
   9195   bool ValueDependent = false;
   9196   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
   9197     resType = Context.DependentTy;
   9198     ValueDependent = true;
   9199   } else {
   9200     // The conditional expression is required to be a constant expression.
   9201     llvm::APSInt condEval(32);
   9202     ExprResult CondICE
   9203       = VerifyIntegerConstantExpression(CondExpr, &condEval,
   9204           diag::err_typecheck_choose_expr_requires_constant, false);
   9205     if (CondICE.isInvalid())
   9206       return ExprError();
   9207     CondExpr = CondICE.take();
   9208 
   9209     // If the condition is > zero, then the AST type is the same as the LSHExpr.
   9210     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
   9211 
   9212     resType = ActiveExpr->getType();
   9213     ValueDependent = ActiveExpr->isValueDependent();
   9214     VK = ActiveExpr->getValueKind();
   9215     OK = ActiveExpr->getObjectKind();
   9216   }
   9217 
   9218   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
   9219                                         resType, VK, OK, RPLoc,
   9220                                         resType->isDependentType(),
   9221                                         ValueDependent));
   9222 }
   9223 
   9224 //===----------------------------------------------------------------------===//
   9225 // Clang Extensions.
   9226 //===----------------------------------------------------------------------===//
   9227 
   9228 /// ActOnBlockStart - This callback is invoked when a block literal is started.
   9229 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
   9230   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
   9231   PushBlockScope(CurScope, Block);
   9232   CurContext->addDecl(Block);
   9233   if (CurScope)
   9234     PushDeclContext(CurScope, Block);
   9235   else
   9236     CurContext = Block;
   9237 
   9238   getCurBlock()->HasImplicitReturnType = true;
   9239 
   9240   // Enter a new evaluation context to insulate the block from any
   9241   // cleanups from the enclosing full-expression.
   9242   PushExpressionEvaluationContext(PotentiallyEvaluated);
   9243 }
   9244 
   9245 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
   9246                                Scope *CurScope) {
   9247   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
   9248   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
   9249   BlockScopeInfo *CurBlock = getCurBlock();
   9250 
   9251   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
   9252   QualType T = Sig->getType();
   9253 
   9254   // FIXME: We should allow unexpanded parameter packs here, but that would,
   9255   // in turn, make the block expression contain unexpanded parameter packs.
   9256   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
   9257     // Drop the parameters.
   9258     FunctionProtoType::ExtProtoInfo EPI;
   9259     EPI.HasTrailingReturn = false;
   9260     EPI.TypeQuals |= DeclSpec::TQ_const;
   9261     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
   9262                                 EPI);
   9263     Sig = Context.getTrivialTypeSourceInfo(T);
   9264   }
   9265 
   9266   // GetTypeForDeclarator always produces a function type for a block
   9267   // literal signature.  Furthermore, it is always a FunctionProtoType
   9268   // unless the function was written with a typedef.
   9269   assert(T->isFunctionType() &&
   9270          "GetTypeForDeclarator made a non-function block signature");
   9271 
   9272   // Look for an explicit signature in that function type.
   9273   FunctionProtoTypeLoc ExplicitSignature;
   9274 
   9275   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
   9276   if (isa<FunctionProtoTypeLoc>(tmp)) {
   9277     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
   9278 
   9279     // Check whether that explicit signature was synthesized by
   9280     // GetTypeForDeclarator.  If so, don't save that as part of the
   9281     // written signature.
   9282     if (ExplicitSignature.getLocalRangeBegin() ==
   9283         ExplicitSignature.getLocalRangeEnd()) {
   9284       // This would be much cheaper if we stored TypeLocs instead of
   9285       // TypeSourceInfos.
   9286       TypeLoc Result = ExplicitSignature.getResultLoc();
   9287       unsigned Size = Result.getFullDataSize();
   9288       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
   9289       Sig->getTypeLoc().initializeFullCopy(Result, Size);
   9290 
   9291       ExplicitSignature = FunctionProtoTypeLoc();
   9292     }
   9293   }
   9294 
   9295   CurBlock->TheDecl->setSignatureAsWritten(Sig);
   9296   CurBlock->FunctionType = T;
   9297 
   9298   const FunctionType *Fn = T->getAs<FunctionType>();
   9299   QualType RetTy = Fn->getResultType();
   9300   bool isVariadic =
   9301     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
   9302 
   9303   CurBlock->TheDecl->setIsVariadic(isVariadic);
   9304 
   9305   // Don't allow returning a objc interface by value.
   9306   if (RetTy->isObjCObjectType()) {
   9307     Diag(ParamInfo.getLocStart(),
   9308          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
   9309     return;
   9310   }
   9311 
   9312   // Context.DependentTy is used as a placeholder for a missing block
   9313   // return type.  TODO:  what should we do with declarators like:
   9314   //   ^ * { ... }
   9315   // If the answer is "apply template argument deduction"....
   9316   if (RetTy != Context.DependentTy) {
   9317     CurBlock->ReturnType = RetTy;
   9318     CurBlock->TheDecl->setBlockMissingReturnType(false);
   9319     CurBlock->HasImplicitReturnType = false;
   9320   }
   9321 
   9322   // Push block parameters from the declarator if we had them.
   9323   SmallVector<ParmVarDecl*, 8> Params;
   9324   if (ExplicitSignature) {
   9325     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
   9326       ParmVarDecl *Param = ExplicitSignature.getArg(I);
   9327       if (Param->getIdentifier() == 0 &&
   9328           !Param->isImplicit() &&
   9329           !Param->isInvalidDecl() &&
   9330           !getLangOpts().CPlusPlus)
   9331         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
   9332       Params.push_back(Param);
   9333     }
   9334 
   9335   // Fake up parameter variables if we have a typedef, like
   9336   //   ^ fntype { ... }
   9337   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
   9338     for (FunctionProtoType::arg_type_iterator
   9339            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
   9340       ParmVarDecl *Param =
   9341         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
   9342                                    ParamInfo.getLocStart(),
   9343                                    *I);
   9344       Params.push_back(Param);
   9345     }
   9346   }
   9347 
   9348   // Set the parameters on the block decl.
   9349   if (!Params.empty()) {
   9350     CurBlock->TheDecl->setParams(Params);
   9351     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
   9352                              CurBlock->TheDecl->param_end(),
   9353                              /*CheckParameterNames=*/false);
   9354   }
   9355 
   9356   // Finally we can process decl attributes.
   9357   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
   9358 
   9359   // Put the parameter variables in scope.  We can bail out immediately
   9360   // if we don't have any.
   9361   if (Params.empty())
   9362     return;
   9363 
   9364   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
   9365          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
   9366     (*AI)->setOwningFunction(CurBlock->TheDecl);
   9367 
   9368     // If this has an identifier, add it to the scope stack.
   9369     if ((*AI)->getIdentifier()) {
   9370       CheckShadow(CurBlock->TheScope, *AI);
   9371 
   9372       PushOnScopeChains(*AI, CurBlock->TheScope);
   9373     }
   9374   }
   9375 }
   9376 
   9377 /// ActOnBlockError - If there is an error parsing a block, this callback
   9378 /// is invoked to pop the information about the block from the action impl.
   9379 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
   9380   // Leave the expression-evaluation context.
   9381   DiscardCleanupsInEvaluationContext();
   9382   PopExpressionEvaluationContext();
   9383 
   9384   // Pop off CurBlock, handle nested blocks.
   9385   PopDeclContext();
   9386   PopFunctionScopeInfo();
   9387 }
   9388 
   9389 /// ActOnBlockStmtExpr - This is called when the body of a block statement
   9390 /// literal was successfully completed.  ^(int x){...}
   9391 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
   9392                                     Stmt *Body, Scope *CurScope) {
   9393   // If blocks are disabled, emit an error.
   9394   if (!LangOpts.Blocks)
   9395     Diag(CaretLoc, diag::err_blocks_disable);
   9396 
   9397   // Leave the expression-evaluation context.
   9398   if (hasAnyUnrecoverableErrorsInThisFunction())
   9399     DiscardCleanupsInEvaluationContext();
   9400   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
   9401   PopExpressionEvaluationContext();
   9402 
   9403   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
   9404 
   9405   if (BSI->HasImplicitReturnType)
   9406     deduceClosureReturnType(*BSI);
   9407 
   9408   PopDeclContext();
   9409 
   9410   QualType RetTy = Context.VoidTy;
   9411   if (!BSI->ReturnType.isNull())
   9412     RetTy = BSI->ReturnType;
   9413 
   9414   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
   9415   QualType BlockTy;
   9416 
   9417   // Set the captured variables on the block.
   9418   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
   9419   SmallVector<BlockDecl::Capture, 4> Captures;
   9420   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
   9421     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
   9422     if (Cap.isThisCapture())
   9423       continue;
   9424     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
   9425                               Cap.isNested(), Cap.getCopyExpr());
   9426     Captures.push_back(NewCap);
   9427   }
   9428   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
   9429                             BSI->CXXThisCaptureIndex != 0);
   9430 
   9431   // If the user wrote a function type in some form, try to use that.
   9432   if (!BSI->FunctionType.isNull()) {
   9433     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
   9434 
   9435     FunctionType::ExtInfo Ext = FTy->getExtInfo();
   9436     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
   9437 
   9438     // Turn protoless block types into nullary block types.
   9439     if (isa<FunctionNoProtoType>(FTy)) {
   9440       FunctionProtoType::ExtProtoInfo EPI;
   9441       EPI.ExtInfo = Ext;
   9442       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
   9443 
   9444     // Otherwise, if we don't need to change anything about the function type,
   9445     // preserve its sugar structure.
   9446     } else if (FTy->getResultType() == RetTy &&
   9447                (!NoReturn || FTy->getNoReturnAttr())) {
   9448       BlockTy = BSI->FunctionType;
   9449 
   9450     // Otherwise, make the minimal modifications to the function type.
   9451     } else {
   9452       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
   9453       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   9454       EPI.TypeQuals = 0; // FIXME: silently?
   9455       EPI.ExtInfo = Ext;
   9456       BlockTy = Context.getFunctionType(RetTy,
   9457                                         FPT->arg_type_begin(),
   9458                                         FPT->getNumArgs(),
   9459                                         EPI);
   9460     }
   9461 
   9462   // If we don't have a function type, just build one from nothing.
   9463   } else {
   9464     FunctionProtoType::ExtProtoInfo EPI;
   9465     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
   9466     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
   9467   }
   9468 
   9469   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
   9470                            BSI->TheDecl->param_end());
   9471   BlockTy = Context.getBlockPointerType(BlockTy);
   9472 
   9473   // If needed, diagnose invalid gotos and switches in the block.
   9474   if (getCurFunction()->NeedsScopeChecking() &&
   9475       !hasAnyUnrecoverableErrorsInThisFunction() &&
   9476       !PP.isCodeCompletionEnabled())
   9477     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
   9478 
   9479   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
   9480 
   9481   // Try to apply the named return value optimization. We have to check again
   9482   // if we can do this, though, because blocks keep return statements around
   9483   // to deduce an implicit return type.
   9484   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
   9485       !BSI->TheDecl->isDependentContext())
   9486     computeNRVO(Body, getCurBlock());
   9487 
   9488   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
   9489   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
   9490   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
   9491 
   9492   // If the block isn't obviously global, i.e. it captures anything at
   9493   // all, then we need to do a few things in the surrounding context:
   9494   if (Result->getBlockDecl()->hasCaptures()) {
   9495     // First, this expression has a new cleanup object.
   9496     ExprCleanupObjects.push_back(Result->getBlockDecl());
   9497     ExprNeedsCleanups = true;
   9498 
   9499     // It also gets a branch-protected scope if any of the captured
   9500     // variables needs destruction.
   9501     for (BlockDecl::capture_const_iterator
   9502            ci = Result->getBlockDecl()->capture_begin(),
   9503            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
   9504       const VarDecl *var = ci->getVariable();
   9505       if (var->getType().isDestructedType() != QualType::DK_none) {
   9506         getCurFunction()->setHasBranchProtectedScope();
   9507         break;
   9508       }
   9509     }
   9510   }
   9511 
   9512   return Owned(Result);
   9513 }
   9514 
   9515 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
   9516                                         Expr *E, ParsedType Ty,
   9517                                         SourceLocation RPLoc) {
   9518   TypeSourceInfo *TInfo;
   9519   GetTypeFromParser(Ty, &TInfo);
   9520   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
   9521 }
   9522 
   9523 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
   9524                                 Expr *E, TypeSourceInfo *TInfo,
   9525                                 SourceLocation RPLoc) {
   9526   Expr *OrigExpr = E;
   9527 
   9528   // Get the va_list type
   9529   QualType VaListType = Context.getBuiltinVaListType();
   9530   if (VaListType->isArrayType()) {
   9531     // Deal with implicit array decay; for example, on x86-64,
   9532     // va_list is an array, but it's supposed to decay to
   9533     // a pointer for va_arg.
   9534     VaListType = Context.getArrayDecayedType(VaListType);
   9535     // Make sure the input expression also decays appropriately.
   9536     ExprResult Result = UsualUnaryConversions(E);
   9537     if (Result.isInvalid())
   9538       return ExprError();
   9539     E = Result.take();
   9540   } else {
   9541     // Otherwise, the va_list argument must be an l-value because
   9542     // it is modified by va_arg.
   9543     if (!E->isTypeDependent() &&
   9544         CheckForModifiableLvalue(E, BuiltinLoc, *this))
   9545       return ExprError();
   9546   }
   9547 
   9548   if (!E->isTypeDependent() &&
   9549       !Context.hasSameType(VaListType, E->getType())) {
   9550     return ExprError(Diag(E->getLocStart(),
   9551                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
   9552       << OrigExpr->getType() << E->getSourceRange());
   9553   }
   9554 
   9555   if (!TInfo->getType()->isDependentType()) {
   9556     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
   9557                             diag::err_second_parameter_to_va_arg_incomplete,
   9558                             TInfo->getTypeLoc()))
   9559       return ExprError();
   9560 
   9561     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
   9562                                TInfo->getType(),
   9563                                diag::err_second_parameter_to_va_arg_abstract,
   9564                                TInfo->getTypeLoc()))
   9565       return ExprError();
   9566 
   9567     if (!TInfo->getType().isPODType(Context)) {
   9568       Diag(TInfo->getTypeLoc().getBeginLoc(),
   9569            TInfo->getType()->isObjCLifetimeType()
   9570              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
   9571              : diag::warn_second_parameter_to_va_arg_not_pod)
   9572         << TInfo->getType()
   9573         << TInfo->getTypeLoc().getSourceRange();
   9574     }
   9575 
   9576     // Check for va_arg where arguments of the given type will be promoted
   9577     // (i.e. this va_arg is guaranteed to have undefined behavior).
   9578     QualType PromoteType;
   9579     if (TInfo->getType()->isPromotableIntegerType()) {
   9580       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
   9581       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
   9582         PromoteType = QualType();
   9583     }
   9584     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
   9585       PromoteType = Context.DoubleTy;
   9586     if (!PromoteType.isNull())
   9587       Diag(TInfo->getTypeLoc().getBeginLoc(),
   9588           diag::warn_second_parameter_to_va_arg_never_compatible)
   9589         << TInfo->getType()
   9590         << PromoteType
   9591         << TInfo->getTypeLoc().getSourceRange();
   9592   }
   9593 
   9594   QualType T = TInfo->getType().getNonLValueExprType(Context);
   9595   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
   9596 }
   9597 
   9598 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
   9599   // The type of __null will be int or long, depending on the size of
   9600   // pointers on the target.
   9601   QualType Ty;
   9602   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
   9603   if (pw == Context.getTargetInfo().getIntWidth())
   9604     Ty = Context.IntTy;
   9605   else if (pw == Context.getTargetInfo().getLongWidth())
   9606     Ty = Context.LongTy;
   9607   else if (pw == Context.getTargetInfo().getLongLongWidth())
   9608     Ty = Context.LongLongTy;
   9609   else {
   9610     llvm_unreachable("I don't know size of pointer!");
   9611   }
   9612 
   9613   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
   9614 }
   9615 
   9616 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
   9617                                            Expr *SrcExpr, FixItHint &Hint) {
   9618   if (!SemaRef.getLangOpts().ObjC1)
   9619     return;
   9620 
   9621   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
   9622   if (!PT)
   9623     return;
   9624 
   9625   // Check if the destination is of type 'id'.
   9626   if (!PT->isObjCIdType()) {
   9627     // Check if the destination is the 'NSString' interface.
   9628     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
   9629     if (!ID || !ID->getIdentifier()->isStr("NSString"))
   9630       return;
   9631   }
   9632 
   9633   // Ignore any parens, implicit casts (should only be
   9634   // array-to-pointer decays), and not-so-opaque values.  The last is
   9635   // important for making this trigger for property assignments.
   9636   SrcExpr = SrcExpr->IgnoreParenImpCasts();
   9637   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
   9638     if (OV->getSourceExpr())
   9639       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
   9640 
   9641   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
   9642   if (!SL || !SL->isAscii())
   9643     return;
   9644 
   9645   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
   9646 }
   9647 
   9648 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
   9649                                     SourceLocation Loc,
   9650                                     QualType DstType, QualType SrcType,
   9651                                     Expr *SrcExpr, AssignmentAction Action,
   9652                                     bool *Complained) {
   9653   if (Complained)
   9654     *Complained = false;
   9655 
   9656   // Decode the result (notice that AST's are still created for extensions).
   9657   bool CheckInferredResultType = false;
   9658   bool isInvalid = false;
   9659   unsigned DiagKind = 0;
   9660   FixItHint Hint;
   9661   ConversionFixItGenerator ConvHints;
   9662   bool MayHaveConvFixit = false;
   9663   bool MayHaveFunctionDiff = false;
   9664 
   9665   switch (ConvTy) {
   9666   case Compatible:
   9667       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
   9668       return false;
   9669 
   9670   case PointerToInt:
   9671     DiagKind = diag::ext_typecheck_convert_pointer_int;
   9672     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
   9673     MayHaveConvFixit = true;
   9674     break;
   9675   case IntToPointer:
   9676     DiagKind = diag::ext_typecheck_convert_int_pointer;
   9677     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
   9678     MayHaveConvFixit = true;
   9679     break;
   9680   case IncompatiblePointer:
   9681     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
   9682     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
   9683     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
   9684       SrcType->isObjCObjectPointerType();
   9685     if (Hint.isNull() && !CheckInferredResultType) {
   9686       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
   9687     }
   9688     MayHaveConvFixit = true;
   9689     break;
   9690   case IncompatiblePointerSign:
   9691     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
   9692     break;
   9693   case FunctionVoidPointer:
   9694     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
   9695     break;
   9696   case IncompatiblePointerDiscardsQualifiers: {
   9697     // Perform array-to-pointer decay if necessary.
   9698     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
   9699 
   9700     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
   9701     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
   9702     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
   9703       DiagKind = diag::err_typecheck_incompatible_address_space;
   9704       break;
   9705 
   9706 
   9707     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
   9708       DiagKind = diag::err_typecheck_incompatible_ownership;
   9709       break;
   9710     }
   9711 
   9712     llvm_unreachable("unknown error case for discarding qualifiers!");
   9713     // fallthrough
   9714   }
   9715   case CompatiblePointerDiscardsQualifiers:
   9716     // If the qualifiers lost were because we were applying the
   9717     // (deprecated) C++ conversion from a string literal to a char*
   9718     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
   9719     // Ideally, this check would be performed in
   9720     // checkPointerTypesForAssignment. However, that would require a
   9721     // bit of refactoring (so that the second argument is an
   9722     // expression, rather than a type), which should be done as part
   9723     // of a larger effort to fix checkPointerTypesForAssignment for
   9724     // C++ semantics.
   9725     if (getLangOpts().CPlusPlus &&
   9726         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
   9727       return false;
   9728     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
   9729     break;
   9730   case IncompatibleNestedPointerQualifiers:
   9731     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
   9732     break;
   9733   case IntToBlockPointer:
   9734     DiagKind = diag::err_int_to_block_pointer;
   9735     break;
   9736   case IncompatibleBlockPointer:
   9737     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
   9738     break;
   9739   case IncompatibleObjCQualifiedId:
   9740     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
   9741     // it can give a more specific diagnostic.
   9742     DiagKind = diag::warn_incompatible_qualified_id;
   9743     break;
   9744   case IncompatibleVectors:
   9745     DiagKind = diag::warn_incompatible_vectors;
   9746     break;
   9747   case IncompatibleObjCWeakRef:
   9748     DiagKind = diag::err_arc_weak_unavailable_assign;
   9749     break;
   9750   case Incompatible:
   9751     DiagKind = diag::err_typecheck_convert_incompatible;
   9752     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
   9753     MayHaveConvFixit = true;
   9754     isInvalid = true;
   9755     MayHaveFunctionDiff = true;
   9756     break;
   9757   }
   9758 
   9759   QualType FirstType, SecondType;
   9760   switch (Action) {
   9761   case AA_Assigning:
   9762   case AA_Initializing:
   9763     // The destination type comes first.
   9764     FirstType = DstType;
   9765     SecondType = SrcType;
   9766     break;
   9767 
   9768   case AA_Returning:
   9769   case AA_Passing:
   9770   case AA_Converting:
   9771   case AA_Sending:
   9772   case AA_Casting:
   9773     // The source type comes first.
   9774     FirstType = SrcType;
   9775     SecondType = DstType;
   9776     break;
   9777   }
   9778 
   9779   PartialDiagnostic FDiag = PDiag(DiagKind);
   9780   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
   9781 
   9782   // If we can fix the conversion, suggest the FixIts.
   9783   assert(ConvHints.isNull() || Hint.isNull());
   9784   if (!ConvHints.isNull()) {
   9785     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
   9786          HE = ConvHints.Hints.end(); HI != HE; ++HI)
   9787       FDiag << *HI;
   9788   } else {
   9789     FDiag << Hint;
   9790   }
   9791   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
   9792 
   9793   if (MayHaveFunctionDiff)
   9794     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
   9795 
   9796   Diag(Loc, FDiag);
   9797 
   9798   if (SecondType == Context.OverloadTy)
   9799     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
   9800                               FirstType);
   9801 
   9802   if (CheckInferredResultType)
   9803     EmitRelatedResultTypeNote(SrcExpr);
   9804 
   9805   if (Complained)
   9806     *Complained = true;
   9807   return isInvalid;
   9808 }
   9809 
   9810 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
   9811                                                  llvm::APSInt *Result) {
   9812   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
   9813   public:
   9814     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
   9815       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
   9816     }
   9817   } Diagnoser;
   9818 
   9819   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
   9820 }
   9821 
   9822 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
   9823                                                  llvm::APSInt *Result,
   9824                                                  unsigned DiagID,
   9825                                                  bool AllowFold) {
   9826   class IDDiagnoser : public VerifyICEDiagnoser {
   9827     unsigned DiagID;
   9828 
   9829   public:
   9830     IDDiagnoser(unsigned DiagID)
   9831       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
   9832 
   9833     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
   9834       S.Diag(Loc, DiagID) << SR;
   9835     }
   9836   } Diagnoser(DiagID);
   9837 
   9838   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
   9839 }
   9840 
   9841 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
   9842                                             SourceRange SR) {
   9843   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
   9844 }
   9845 
   9846 ExprResult
   9847 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
   9848                                       VerifyICEDiagnoser &Diagnoser,
   9849                                       bool AllowFold) {
   9850   SourceLocation DiagLoc = E->getLocStart();
   9851 
   9852   if (getLangOpts().CPlusPlus0x) {
   9853     // C++11 [expr.const]p5:
   9854     //   If an expression of literal class type is used in a context where an
   9855     //   integral constant expression is required, then that class type shall
   9856     //   have a single non-explicit conversion function to an integral or
   9857     //   unscoped enumeration type
   9858     ExprResult Converted;
   9859     if (!Diagnoser.Suppress) {
   9860       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
   9861       public:
   9862         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
   9863 
   9864         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
   9865                                                  QualType T) {
   9866           return S.Diag(Loc, diag::err_ice_not_integral) << T;
   9867         }
   9868 
   9869         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
   9870                                                      SourceLocation Loc,
   9871                                                      QualType T) {
   9872           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
   9873         }
   9874 
   9875         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
   9876                                                        SourceLocation Loc,
   9877                                                        QualType T,
   9878                                                        QualType ConvTy) {
   9879           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
   9880         }
   9881 
   9882         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
   9883                                                    CXXConversionDecl *Conv,
   9884                                                    QualType ConvTy) {
   9885           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
   9886                    << ConvTy->isEnumeralType() << ConvTy;
   9887         }
   9888 
   9889         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
   9890                                                     QualType T) {
   9891           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
   9892         }
   9893 
   9894         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
   9895                                                 CXXConversionDecl *Conv,
   9896                                                 QualType ConvTy) {
   9897           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
   9898                    << ConvTy->isEnumeralType() << ConvTy;
   9899         }
   9900 
   9901         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
   9902                                                      SourceLocation Loc,
   9903                                                      QualType T,
   9904                                                      QualType ConvTy) {
   9905           return DiagnosticBuilder::getEmpty();
   9906         }
   9907       } ConvertDiagnoser;
   9908 
   9909       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
   9910                                                      ConvertDiagnoser,
   9911                                              /*AllowScopedEnumerations*/ false);
   9912     } else {
   9913       // The caller wants to silently enquire whether this is an ICE. Don't
   9914       // produce any diagnostics if it isn't.
   9915       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
   9916       public:
   9917         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
   9918 
   9919         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
   9920                                                  QualType T) {
   9921           return DiagnosticBuilder::getEmpty();
   9922         }
   9923 
   9924         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
   9925                                                      SourceLocation Loc,
   9926                                                      QualType T) {
   9927           return DiagnosticBuilder::getEmpty();
   9928         }
   9929 
   9930         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
   9931                                                        SourceLocation Loc,
   9932                                                        QualType T,
   9933                                                        QualType ConvTy) {
   9934           return DiagnosticBuilder::getEmpty();
   9935         }
   9936 
   9937         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
   9938                                                    CXXConversionDecl *Conv,
   9939                                                    QualType ConvTy) {
   9940           return DiagnosticBuilder::getEmpty();
   9941         }
   9942 
   9943         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
   9944                                                     QualType T) {
   9945           return DiagnosticBuilder::getEmpty();
   9946         }
   9947 
   9948         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
   9949                                                 CXXConversionDecl *Conv,
   9950                                                 QualType ConvTy) {
   9951           return DiagnosticBuilder::getEmpty();
   9952         }
   9953 
   9954         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
   9955                                                      SourceLocation Loc,
   9956                                                      QualType T,
   9957                                                      QualType ConvTy) {
   9958           return DiagnosticBuilder::getEmpty();
   9959         }
   9960       } ConvertDiagnoser;
   9961 
   9962       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
   9963                                                      ConvertDiagnoser, false);
   9964     }
   9965     if (Converted.isInvalid())
   9966       return Converted;
   9967     E = Converted.take();
   9968     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
   9969       return ExprError();
   9970   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
   9971     // An ICE must be of integral or unscoped enumeration type.
   9972     if (!Diagnoser.Suppress)
   9973       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
   9974     return ExprError();
   9975   }
   9976 
   9977   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
   9978   // in the non-ICE case.
   9979   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
   9980     if (Result)
   9981       *Result = E->EvaluateKnownConstInt(Context);
   9982     return Owned(E);
   9983   }
   9984 
   9985   Expr::EvalResult EvalResult;
   9986   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
   9987   EvalResult.Diag = &Notes;
   9988 
   9989   // Try to evaluate the expression, and produce diagnostics explaining why it's
   9990   // not a constant expression as a side-effect.
   9991   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
   9992                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
   9993 
   9994   // In C++11, we can rely on diagnostics being produced for any expression
   9995   // which is not a constant expression. If no diagnostics were produced, then
   9996   // this is a constant expression.
   9997   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
   9998     if (Result)
   9999       *Result = EvalResult.Val.getInt();
   10000     return Owned(E);
   10001   }
   10002 
   10003   // If our only note is the usual "invalid subexpression" note, just point
   10004   // the caret at its location rather than producing an essentially
   10005   // redundant note.
   10006   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
   10007         diag::note_invalid_subexpr_in_const_expr) {
   10008     DiagLoc = Notes[0].first;
   10009     Notes.clear();
   10010   }
   10011 
   10012   if (!Folded || !AllowFold) {
   10013     if (!Diagnoser.Suppress) {
   10014       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
   10015       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
   10016         Diag(Notes[I].first, Notes[I].second);
   10017     }
   10018 
   10019     return ExprError();
   10020   }
   10021 
   10022   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
   10023   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
   10024     Diag(Notes[I].first, Notes[I].second);
   10025 
   10026   if (Result)
   10027     *Result = EvalResult.Val.getInt();
   10028   return Owned(E);
   10029 }
   10030 
   10031 namespace {
   10032   // Handle the case where we conclude a expression which we speculatively
   10033   // considered to be unevaluated is actually evaluated.
   10034   class TransformToPE : public TreeTransform<TransformToPE> {
   10035     typedef TreeTransform<TransformToPE> BaseTransform;
   10036 
   10037   public:
   10038     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
   10039 
   10040     // Make sure we redo semantic analysis
   10041     bool AlwaysRebuild() { return true; }
   10042 
   10043     // Make sure we handle LabelStmts correctly.
   10044     // FIXME: This does the right thing, but maybe we need a more general
   10045     // fix to TreeTransform?
   10046     StmtResult TransformLabelStmt(LabelStmt *S) {
   10047       S->getDecl()->setStmt(0);
   10048       return BaseTransform::TransformLabelStmt(S);
   10049     }
   10050 
   10051     // We need to special-case DeclRefExprs referring to FieldDecls which
   10052     // are not part of a member pointer formation; normal TreeTransforming
   10053     // doesn't catch this case because of the way we represent them in the AST.
   10054     // FIXME: This is a bit ugly; is it really the best way to handle this
   10055     // case?
   10056     //
   10057     // Error on DeclRefExprs referring to FieldDecls.
   10058     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
   10059       if (isa<FieldDecl>(E->getDecl()) &&
   10060           !SemaRef.isUnevaluatedContext())
   10061         return SemaRef.Diag(E->getLocation(),
   10062                             diag::err_invalid_non_static_member_use)
   10063             << E->getDecl() << E->getSourceRange();
   10064 
   10065       return BaseTransform::TransformDeclRefExpr(E);
   10066     }
   10067 
   10068     // Exception: filter out member pointer formation
   10069     ExprResult TransformUnaryOperator(UnaryOperator *E) {
   10070       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
   10071         return E;
   10072 
   10073       return BaseTransform::TransformUnaryOperator(E);
   10074     }
   10075 
   10076     ExprResult TransformLambdaExpr(LambdaExpr *E) {
   10077       // Lambdas never need to be transformed.
   10078       return E;
   10079     }
   10080   };
   10081 }
   10082 
   10083 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
   10084   assert(ExprEvalContexts.back().Context == Unevaluated &&
   10085          "Should only transform unevaluated expressions");
   10086   ExprEvalContexts.back().Context =
   10087       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
   10088   if (ExprEvalContexts.back().Context == Unevaluated)
   10089     return E;
   10090   return TransformToPE(*this).TransformExpr(E);
   10091 }
   10092 
   10093 void
   10094 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
   10095                                       Decl *LambdaContextDecl,
   10096                                       bool IsDecltype) {
   10097   ExprEvalContexts.push_back(
   10098              ExpressionEvaluationContextRecord(NewContext,
   10099                                                ExprCleanupObjects.size(),
   10100                                                ExprNeedsCleanups,
   10101                                                LambdaContextDecl,
   10102                                                IsDecltype));
   10103   ExprNeedsCleanups = false;
   10104   if (!MaybeODRUseExprs.empty())
   10105     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
   10106 }
   10107 
   10108 void Sema::PopExpressionEvaluationContext() {
   10109   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
   10110 
   10111   if (!Rec.Lambdas.empty()) {
   10112     if (Rec.Context == Unevaluated) {
   10113       // C++11 [expr.prim.lambda]p2:
   10114       //   A lambda-expression shall not appear in an unevaluated operand
   10115       //   (Clause 5).
   10116       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
   10117         Diag(Rec.Lambdas[I]->getLocStart(),
   10118              diag::err_lambda_unevaluated_operand);
   10119     } else {
   10120       // Mark the capture expressions odr-used. This was deferred
   10121       // during lambda expression creation.
   10122       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
   10123         LambdaExpr *Lambda = Rec.Lambdas[I];
   10124         for (LambdaExpr::capture_init_iterator
   10125                   C = Lambda->capture_init_begin(),
   10126                CEnd = Lambda->capture_init_end();
   10127              C != CEnd; ++C) {
   10128           MarkDeclarationsReferencedInExpr(*C);
   10129         }
   10130       }
   10131     }
   10132   }
   10133 
   10134   // When are coming out of an unevaluated context, clear out any
   10135   // temporaries that we may have created as part of the evaluation of
   10136   // the expression in that context: they aren't relevant because they
   10137   // will never be constructed.
   10138   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
   10139     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
   10140                              ExprCleanupObjects.end());
   10141     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
   10142     CleanupVarDeclMarking();
   10143     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
   10144   // Otherwise, merge the contexts together.
   10145   } else {
   10146     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
   10147     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
   10148                             Rec.SavedMaybeODRUseExprs.end());
   10149   }
   10150 
   10151   // Pop the current expression evaluation context off the stack.
   10152   ExprEvalContexts.pop_back();
   10153 }
   10154 
   10155 void Sema::DiscardCleanupsInEvaluationContext() {
   10156   ExprCleanupObjects.erase(
   10157          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
   10158          ExprCleanupObjects.end());
   10159   ExprNeedsCleanups = false;
   10160   MaybeODRUseExprs.clear();
   10161 }
   10162 
   10163 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
   10164   if (!E->getType()->isVariablyModifiedType())
   10165     return E;
   10166   return TranformToPotentiallyEvaluated(E);
   10167 }
   10168 
   10169 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
   10170   // Do not mark anything as "used" within a dependent context; wait for
   10171   // an instantiation.
   10172   if (SemaRef.CurContext->isDependentContext())
   10173     return false;
   10174 
   10175   switch (SemaRef.ExprEvalContexts.back().Context) {
   10176     case Sema::Unevaluated:
   10177       // We are in an expression that is not potentially evaluated; do nothing.
   10178       // (Depending on how you read the standard, we actually do need to do
   10179       // something here for null pointer constants, but the standard's
   10180       // definition of a null pointer constant is completely crazy.)
   10181       return false;
   10182 
   10183     case Sema::ConstantEvaluated:
   10184     case Sema::PotentiallyEvaluated:
   10185       // We are in a potentially evaluated expression (or a constant-expression
   10186       // in C++03); we need to do implicit template instantiation, implicitly
   10187       // define class members, and mark most declarations as used.
   10188       return true;
   10189 
   10190     case Sema::PotentiallyEvaluatedIfUsed:
   10191       // Referenced declarations will only be used if the construct in the
   10192       // containing expression is used.
   10193       return false;
   10194   }
   10195   llvm_unreachable("Invalid context");
   10196 }
   10197 
   10198 /// \brief Mark a function referenced, and check whether it is odr-used
   10199 /// (C++ [basic.def.odr]p2, C99 6.9p3)
   10200 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
   10201   assert(Func && "No function?");
   10202 
   10203   Func->setReferenced();
   10204 
   10205   // Don't mark this function as used multiple times, unless it's a constexpr
   10206   // function which we need to instantiate.
   10207   if (Func->isUsed(false) &&
   10208       !(Func->isConstexpr() && !Func->getBody() &&
   10209         Func->isImplicitlyInstantiable()))
   10210     return;
   10211 
   10212   if (!IsPotentiallyEvaluatedContext(*this))
   10213     return;
   10214 
   10215   // Note that this declaration has been used.
   10216   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
   10217     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
   10218       if (Constructor->isDefaultConstructor()) {
   10219         if (Constructor->isTrivial())
   10220           return;
   10221         if (!Constructor->isUsed(false))
   10222           DefineImplicitDefaultConstructor(Loc, Constructor);
   10223       } else if (Constructor->isCopyConstructor()) {
   10224         if (!Constructor->isUsed(false))
   10225           DefineImplicitCopyConstructor(Loc, Constructor);
   10226       } else if (Constructor->isMoveConstructor()) {
   10227         if (!Constructor->isUsed(false))
   10228           DefineImplicitMoveConstructor(Loc, Constructor);
   10229       }
   10230     }
   10231 
   10232     MarkVTableUsed(Loc, Constructor->getParent());
   10233   } else if (CXXDestructorDecl *Destructor =
   10234                  dyn_cast<CXXDestructorDecl>(Func)) {
   10235     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
   10236         !Destructor->isUsed(false))
   10237       DefineImplicitDestructor(Loc, Destructor);
   10238     if (Destructor->isVirtual())
   10239       MarkVTableUsed(Loc, Destructor->getParent());
   10240   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
   10241     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
   10242         MethodDecl->isOverloadedOperator() &&
   10243         MethodDecl->getOverloadedOperator() == OO_Equal) {
   10244       if (!MethodDecl->isUsed(false)) {
   10245         if (MethodDecl->isCopyAssignmentOperator())
   10246           DefineImplicitCopyAssignment(Loc, MethodDecl);
   10247         else
   10248           DefineImplicitMoveAssignment(Loc, MethodDecl);
   10249       }
   10250     } else if (isa<CXXConversionDecl>(MethodDecl) &&
   10251                MethodDecl->getParent()->isLambda()) {
   10252       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
   10253       if (Conversion->isLambdaToBlockPointerConversion())
   10254         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
   10255       else
   10256         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
   10257     } else if (MethodDecl->isVirtual())
   10258       MarkVTableUsed(Loc, MethodDecl->getParent());
   10259   }
   10260 
   10261   // Recursive functions should be marked when used from another function.
   10262   // FIXME: Is this really right?
   10263   if (CurContext == Func) return;
   10264 
   10265   // Resolve the exception specification for any function which is
   10266   // used: CodeGen will need it.
   10267   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
   10268   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
   10269     ResolveExceptionSpec(Loc, FPT);
   10270 
   10271   // Implicit instantiation of function templates and member functions of
   10272   // class templates.
   10273   if (Func->isImplicitlyInstantiable()) {
   10274     bool AlreadyInstantiated = false;
   10275     SourceLocation PointOfInstantiation = Loc;
   10276     if (FunctionTemplateSpecializationInfo *SpecInfo
   10277                               = Func->getTemplateSpecializationInfo()) {
   10278       if (SpecInfo->getPointOfInstantiation().isInvalid())
   10279         SpecInfo->setPointOfInstantiation(Loc);
   10280       else if (SpecInfo->getTemplateSpecializationKind()
   10281                  == TSK_ImplicitInstantiation) {
   10282         AlreadyInstantiated = true;
   10283         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
   10284       }
   10285     } else if (MemberSpecializationInfo *MSInfo
   10286                                 = Func->getMemberSpecializationInfo()) {
   10287       if (MSInfo->getPointOfInstantiation().isInvalid())
   10288         MSInfo->setPointOfInstantiation(Loc);
   10289       else if (MSInfo->getTemplateSpecializationKind()
   10290                  == TSK_ImplicitInstantiation) {
   10291         AlreadyInstantiated = true;
   10292         PointOfInstantiation = MSInfo->getPointOfInstantiation();
   10293       }
   10294     }
   10295 
   10296     if (!AlreadyInstantiated || Func->isConstexpr()) {
   10297       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
   10298           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
   10299         PendingLocalImplicitInstantiations.push_back(
   10300             std::make_pair(Func, PointOfInstantiation));
   10301       else if (Func->isConstexpr())
   10302         // Do not defer instantiations of constexpr functions, to avoid the
   10303         // expression evaluator needing to call back into Sema if it sees a
   10304         // call to such a function.
   10305         InstantiateFunctionDefinition(PointOfInstantiation, Func);
   10306       else {
   10307         PendingInstantiations.push_back(std::make_pair(Func,
   10308                                                        PointOfInstantiation));
   10309         // Notify the consumer that a function was implicitly instantiated.
   10310         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
   10311       }
   10312     }
   10313   } else {
   10314     // Walk redefinitions, as some of them may be instantiable.
   10315     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
   10316          e(Func->redecls_end()); i != e; ++i) {
   10317       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
   10318         MarkFunctionReferenced(Loc, *i);
   10319     }
   10320   }
   10321 
   10322   // Keep track of used but undefined functions.
   10323   if (!Func->isPure() && !Func->hasBody() &&
   10324       Func->getLinkage() != ExternalLinkage) {
   10325     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
   10326     if (old.isInvalid()) old = Loc;
   10327   }
   10328 
   10329   Func->setUsed(true);
   10330 }
   10331 
   10332 static void
   10333 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
   10334                                    VarDecl *var, DeclContext *DC) {
   10335   DeclContext *VarDC = var->getDeclContext();
   10336 
   10337   //  If the parameter still belongs to the translation unit, then
   10338   //  we're actually just using one parameter in the declaration of
   10339   //  the next.
   10340   if (isa<ParmVarDecl>(var) &&
   10341       isa<TranslationUnitDecl>(VarDC))
   10342     return;
   10343 
   10344   // For C code, don't diagnose about capture if we're not actually in code
   10345   // right now; it's impossible to write a non-constant expression outside of
   10346   // function context, so we'll get other (more useful) diagnostics later.
   10347   //
   10348   // For C++, things get a bit more nasty... it would be nice to suppress this
   10349   // diagnostic for certain cases like using a local variable in an array bound
   10350   // for a member of a local class, but the correct predicate is not obvious.
   10351   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
   10352     return;
   10353 
   10354   if (isa<CXXMethodDecl>(VarDC) &&
   10355       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
   10356     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
   10357       << var->getIdentifier();
   10358   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
   10359     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
   10360       << var->getIdentifier() << fn->getDeclName();
   10361   } else if (isa<BlockDecl>(VarDC)) {
   10362     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
   10363       << var->getIdentifier();
   10364   } else {
   10365     // FIXME: Is there any other context where a local variable can be
   10366     // declared?
   10367     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
   10368       << var->getIdentifier();
   10369   }
   10370 
   10371   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
   10372     << var->getIdentifier();
   10373 
   10374   // FIXME: Add additional diagnostic info about class etc. which prevents
   10375   // capture.
   10376 }
   10377 
   10378 /// \brief Capture the given variable in the given lambda expression.
   10379 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
   10380                                   VarDecl *Var, QualType FieldType,
   10381                                   QualType DeclRefType,
   10382                                   SourceLocation Loc,
   10383                                   bool RefersToEnclosingLocal) {
   10384   CXXRecordDecl *Lambda = LSI->Lambda;
   10385 
   10386   // Build the non-static data member.
   10387   FieldDecl *Field
   10388     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
   10389                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
   10390                         0, false, ICIS_NoInit);
   10391   Field->setImplicit(true);
   10392   Field->setAccess(AS_private);
   10393   Lambda->addDecl(Field);
   10394 
   10395   // C++11 [expr.prim.lambda]p21:
   10396   //   When the lambda-expression is evaluated, the entities that
   10397   //   are captured by copy are used to direct-initialize each
   10398   //   corresponding non-static data member of the resulting closure
   10399   //   object. (For array members, the array elements are
   10400   //   direct-initialized in increasing subscript order.) These
   10401   //   initializations are performed in the (unspecified) order in
   10402   //   which the non-static data members are declared.
   10403 
   10404   // Introduce a new evaluation context for the initialization, so
   10405   // that temporaries introduced as part of the capture are retained
   10406   // to be re-"exported" from the lambda expression itself.
   10407   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
   10408 
   10409   // C++ [expr.prim.labda]p12:
   10410   //   An entity captured by a lambda-expression is odr-used (3.2) in
   10411   //   the scope containing the lambda-expression.
   10412   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
   10413                                           DeclRefType, VK_LValue, Loc);
   10414   Var->setReferenced(true);
   10415   Var->setUsed(true);
   10416 
   10417   // When the field has array type, create index variables for each
   10418   // dimension of the array. We use these index variables to subscript
   10419   // the source array, and other clients (e.g., CodeGen) will perform
   10420   // the necessary iteration with these index variables.
   10421   SmallVector<VarDecl *, 4> IndexVariables;
   10422   QualType BaseType = FieldType;
   10423   QualType SizeType = S.Context.getSizeType();
   10424   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
   10425   while (const ConstantArrayType *Array
   10426                         = S.Context.getAsConstantArrayType(BaseType)) {
   10427     // Create the iteration variable for this array index.
   10428     IdentifierInfo *IterationVarName = 0;
   10429     {
   10430       SmallString<8> Str;
   10431       llvm::raw_svector_ostream OS(Str);
   10432       OS << "__i" << IndexVariables.size();
   10433       IterationVarName = &S.Context.Idents.get(OS.str());
   10434     }
   10435     VarDecl *IterationVar
   10436       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
   10437                         IterationVarName, SizeType,
   10438                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
   10439                         SC_None, SC_None);
   10440     IndexVariables.push_back(IterationVar);
   10441     LSI->ArrayIndexVars.push_back(IterationVar);
   10442 
   10443     // Create a reference to the iteration variable.
   10444     ExprResult IterationVarRef
   10445       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
   10446     assert(!IterationVarRef.isInvalid() &&
   10447            "Reference to invented variable cannot fail!");
   10448     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
   10449     assert(!IterationVarRef.isInvalid() &&
   10450            "Conversion of invented variable cannot fail!");
   10451 
   10452     // Subscript the array with this iteration variable.
   10453     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
   10454                              Ref, Loc, IterationVarRef.take(), Loc);
   10455     if (Subscript.isInvalid()) {
   10456       S.CleanupVarDeclMarking();
   10457       S.DiscardCleanupsInEvaluationContext();
   10458       S.PopExpressionEvaluationContext();
   10459       return ExprError();
   10460     }
   10461 
   10462     Ref = Subscript.take();
   10463     BaseType = Array->getElementType();
   10464   }
   10465 
   10466   // Construct the entity that we will be initializing. For an array, this
   10467   // will be first element in the array, which may require several levels
   10468   // of array-subscript entities.
   10469   SmallVector<InitializedEntity, 4> Entities;
   10470   Entities.reserve(1 + IndexVariables.size());
   10471   Entities.push_back(
   10472     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
   10473   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
   10474     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
   10475                                                             0,
   10476                                                             Entities.back()));
   10477 
   10478   InitializationKind InitKind
   10479     = InitializationKind::CreateDirect(Loc, Loc, Loc);
   10480   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
   10481   ExprResult Result(true);
   10482   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
   10483     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
   10484 
   10485   // If this initialization requires any cleanups (e.g., due to a
   10486   // default argument to a copy constructor), note that for the
   10487   // lambda.
   10488   if (S.ExprNeedsCleanups)
   10489     LSI->ExprNeedsCleanups = true;
   10490 
   10491   // Exit the expression evaluation context used for the capture.
   10492   S.CleanupVarDeclMarking();
   10493   S.DiscardCleanupsInEvaluationContext();
   10494   S.PopExpressionEvaluationContext();
   10495   return Result;
   10496 }
   10497 
   10498 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
   10499                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
   10500                               bool BuildAndDiagnose,
   10501                               QualType &CaptureType,
   10502                               QualType &DeclRefType) {
   10503   bool Nested = false;
   10504 
   10505   DeclContext *DC = CurContext;
   10506   if (Var->getDeclContext() == DC) return true;
   10507   if (!Var->hasLocalStorage()) return true;
   10508 
   10509   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
   10510 
   10511   // Walk up the stack to determine whether we can capture the variable,
   10512   // performing the "simple" checks that don't depend on type. We stop when
   10513   // we've either hit the declared scope of the variable or find an existing
   10514   // capture of that variable.
   10515   CaptureType = Var->getType();
   10516   DeclRefType = CaptureType.getNonReferenceType();
   10517   bool Explicit = (Kind != TryCapture_Implicit);
   10518   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
   10519   do {
   10520     // Only block literals and lambda expressions can capture; other
   10521     // scopes don't work.
   10522     DeclContext *ParentDC;
   10523     if (isa<BlockDecl>(DC))
   10524       ParentDC = DC->getParent();
   10525     else if (isa<CXXMethodDecl>(DC) &&
   10526              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
   10527              cast<CXXRecordDecl>(DC->getParent())->isLambda())
   10528       ParentDC = DC->getParent()->getParent();
   10529     else {
   10530       if (BuildAndDiagnose)
   10531         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
   10532       return true;
   10533     }
   10534 
   10535     CapturingScopeInfo *CSI =
   10536       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
   10537 
   10538     // Check whether we've already captured it.
   10539     if (CSI->CaptureMap.count(Var)) {
   10540       // If we found a capture, any subcaptures are nested.
   10541       Nested = true;
   10542 
   10543       // Retrieve the capture type for this variable.
   10544       CaptureType = CSI->getCapture(Var).getCaptureType();
   10545 
   10546       // Compute the type of an expression that refers to this variable.
   10547       DeclRefType = CaptureType.getNonReferenceType();
   10548 
   10549       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
   10550       if (Cap.isCopyCapture() &&
   10551           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
   10552         DeclRefType.addConst();
   10553       break;
   10554     }
   10555 
   10556     bool IsBlock = isa<BlockScopeInfo>(CSI);
   10557     bool IsLambda = !IsBlock;
   10558 
   10559     // Lambdas are not allowed to capture unnamed variables
   10560     // (e.g. anonymous unions).
   10561     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
   10562     // assuming that's the intent.
   10563     if (IsLambda && !Var->getDeclName()) {
   10564       if (BuildAndDiagnose) {
   10565         Diag(Loc, diag::err_lambda_capture_anonymous_var);
   10566         Diag(Var->getLocation(), diag::note_declared_at);
   10567       }
   10568       return true;
   10569     }
   10570 
   10571     // Prohibit variably-modified types; they're difficult to deal with.
   10572     if (Var->getType()->isVariablyModifiedType()) {
   10573       if (BuildAndDiagnose) {
   10574         if (IsBlock)
   10575           Diag(Loc, diag::err_ref_vm_type);
   10576         else
   10577           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
   10578         Diag(Var->getLocation(), diag::note_previous_decl)
   10579           << Var->getDeclName();
   10580       }
   10581       return true;
   10582     }
   10583 
   10584     // Lambdas are not allowed to capture __block variables; they don't
   10585     // support the expected semantics.
   10586     if (IsLambda && HasBlocksAttr) {
   10587       if (BuildAndDiagnose) {
   10588         Diag(Loc, diag::err_lambda_capture_block)
   10589           << Var->getDeclName();
   10590         Diag(Var->getLocation(), diag::note_previous_decl)
   10591           << Var->getDeclName();
   10592       }
   10593       return true;
   10594     }
   10595 
   10596     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
   10597       // No capture-default
   10598       if (BuildAndDiagnose) {
   10599         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
   10600         Diag(Var->getLocation(), diag::note_previous_decl)
   10601           << Var->getDeclName();
   10602         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
   10603              diag::note_lambda_decl);
   10604       }
   10605       return true;
   10606     }
   10607 
   10608     FunctionScopesIndex--;
   10609     DC = ParentDC;
   10610     Explicit = false;
   10611   } while (!Var->getDeclContext()->Equals(DC));
   10612 
   10613   // Walk back down the scope stack, computing the type of the capture at
   10614   // each step, checking type-specific requirements, and adding captures if
   10615   // requested.
   10616   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
   10617        ++I) {
   10618     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
   10619 
   10620     // Compute the type of the capture and of a reference to the capture within
   10621     // this scope.
   10622     if (isa<BlockScopeInfo>(CSI)) {
   10623       Expr *CopyExpr = 0;
   10624       bool ByRef = false;
   10625 
   10626       // Blocks are not allowed to capture arrays.
   10627       if (CaptureType->isArrayType()) {
   10628         if (BuildAndDiagnose) {
   10629           Diag(Loc, diag::err_ref_array_type);
   10630           Diag(Var->getLocation(), diag::note_previous_decl)
   10631           << Var->getDeclName();
   10632         }
   10633         return true;
   10634       }
   10635 
   10636       // Forbid the block-capture of autoreleasing variables.
   10637       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
   10638         if (BuildAndDiagnose) {
   10639           Diag(Loc, diag::err_arc_autoreleasing_capture)
   10640             << /*block*/ 0;
   10641           Diag(Var->getLocation(), diag::note_previous_decl)
   10642             << Var->getDeclName();
   10643         }
   10644         return true;
   10645       }
   10646 
   10647       if (HasBlocksAttr || CaptureType->isReferenceType()) {
   10648         // Block capture by reference does not change the capture or
   10649         // declaration reference types.
   10650         ByRef = true;
   10651       } else {
   10652         // Block capture by copy introduces 'const'.
   10653         CaptureType = CaptureType.getNonReferenceType().withConst();
   10654         DeclRefType = CaptureType;
   10655 
   10656         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
   10657           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
   10658             // The capture logic needs the destructor, so make sure we mark it.
   10659             // Usually this is unnecessary because most local variables have
   10660             // their destructors marked at declaration time, but parameters are
   10661             // an exception because it's technically only the call site that
   10662             // actually requires the destructor.
   10663             if (isa<ParmVarDecl>(Var))
   10664               FinalizeVarWithDestructor(Var, Record);
   10665 
   10666             // According to the blocks spec, the capture of a variable from
   10667             // the stack requires a const copy constructor.  This is not true
   10668             // of the copy/move done to move a __block variable to the heap.
   10669             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
   10670                                                       DeclRefType.withConst(),
   10671                                                       VK_LValue, Loc);
   10672             ExprResult Result
   10673               = PerformCopyInitialization(
   10674                   InitializedEntity::InitializeBlock(Var->getLocation(),
   10675                                                      CaptureType, false),
   10676                   Loc, Owned(DeclRef));
   10677 
   10678             // Build a full-expression copy expression if initialization
   10679             // succeeded and used a non-trivial constructor.  Recover from
   10680             // errors by pretending that the copy isn't necessary.
   10681             if (!Result.isInvalid() &&
   10682                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
   10683                    ->isTrivial()) {
   10684               Result = MaybeCreateExprWithCleanups(Result);
   10685               CopyExpr = Result.take();
   10686             }
   10687           }
   10688         }
   10689       }
   10690 
   10691       // Actually capture the variable.
   10692       if (BuildAndDiagnose)
   10693         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
   10694                         SourceLocation(), CaptureType, CopyExpr);
   10695       Nested = true;
   10696       continue;
   10697     }
   10698 
   10699     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
   10700 
   10701     // Determine whether we are capturing by reference or by value.
   10702     bool ByRef = false;
   10703     if (I == N - 1 && Kind != TryCapture_Implicit) {
   10704       ByRef = (Kind == TryCapture_ExplicitByRef);
   10705     } else {
   10706       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
   10707     }
   10708 
   10709     // Compute the type of the field that will capture this variable.
   10710     if (ByRef) {
   10711       // C++11 [expr.prim.lambda]p15:
   10712       //   An entity is captured by reference if it is implicitly or
   10713       //   explicitly captured but not captured by copy. It is
   10714       //   unspecified whether additional unnamed non-static data
   10715       //   members are declared in the closure type for entities
   10716       //   captured by reference.
   10717       //
   10718       // FIXME: It is not clear whether we want to build an lvalue reference
   10719       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
   10720       // to do the former, while EDG does the latter. Core issue 1249 will
   10721       // clarify, but for now we follow GCC because it's a more permissive and
   10722       // easily defensible position.
   10723       CaptureType = Context.getLValueReferenceType(DeclRefType);
   10724     } else {
   10725       // C++11 [expr.prim.lambda]p14:
   10726       //   For each entity captured by copy, an unnamed non-static
   10727       //   data member is declared in the closure type. The
   10728       //   declaration order of these members is unspecified. The type
   10729       //   of such a data member is the type of the corresponding
   10730       //   captured entity if the entity is not a reference to an
   10731       //   object, or the referenced type otherwise. [Note: If the
   10732       //   captured entity is a reference to a function, the
   10733       //   corresponding data member is also a reference to a
   10734       //   function. - end note ]
   10735       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
   10736         if (!RefType->getPointeeType()->isFunctionType())
   10737           CaptureType = RefType->getPointeeType();
   10738       }
   10739 
   10740       // Forbid the lambda copy-capture of autoreleasing variables.
   10741       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
   10742         if (BuildAndDiagnose) {
   10743           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
   10744           Diag(Var->getLocation(), diag::note_previous_decl)
   10745             << Var->getDeclName();
   10746         }
   10747         return true;
   10748       }
   10749     }
   10750 
   10751     // Capture this variable in the lambda.
   10752     Expr *CopyExpr = 0;
   10753     if (BuildAndDiagnose) {
   10754       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
   10755                                           DeclRefType, Loc,
   10756                                           I == N-1);
   10757       if (!Result.isInvalid())
   10758         CopyExpr = Result.take();
   10759     }
   10760 
   10761     // Compute the type of a reference to this captured variable.
   10762     if (ByRef)
   10763       DeclRefType = CaptureType.getNonReferenceType();
   10764     else {
   10765       // C++ [expr.prim.lambda]p5:
   10766       //   The closure type for a lambda-expression has a public inline
   10767       //   function call operator [...]. This function call operator is
   10768       //   declared const (9.3.1) if and only if the lambda-expressions
   10769       //   parameter-declaration-clause is not followed by mutable.
   10770       DeclRefType = CaptureType.getNonReferenceType();
   10771       if (!LSI->Mutable && !CaptureType->isReferenceType())
   10772         DeclRefType.addConst();
   10773     }
   10774 
   10775     // Add the capture.
   10776     if (BuildAndDiagnose)
   10777       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
   10778                       EllipsisLoc, CaptureType, CopyExpr);
   10779     Nested = true;
   10780   }
   10781 
   10782   return false;
   10783 }
   10784 
   10785 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
   10786                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
   10787   QualType CaptureType;
   10788   QualType DeclRefType;
   10789   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
   10790                             /*BuildAndDiagnose=*/true, CaptureType,
   10791                             DeclRefType);
   10792 }
   10793 
   10794 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
   10795   QualType CaptureType;
   10796   QualType DeclRefType;
   10797 
   10798   // Determine whether we can capture this variable.
   10799   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
   10800                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
   10801     return QualType();
   10802 
   10803   return DeclRefType;
   10804 }
   10805 
   10806 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
   10807                                SourceLocation Loc) {
   10808   // Keep track of used but undefined variables.
   10809   // FIXME: We shouldn't suppress this warning for static data members.
   10810   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
   10811       Var->getLinkage() != ExternalLinkage &&
   10812       !(Var->isStaticDataMember() && Var->hasInit())) {
   10813     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
   10814     if (old.isInvalid()) old = Loc;
   10815   }
   10816 
   10817   SemaRef.tryCaptureVariable(Var, Loc);
   10818 
   10819   Var->setUsed(true);
   10820 }
   10821 
   10822 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
   10823   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
   10824   // an object that satisfies the requirements for appearing in a
   10825   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
   10826   // is immediately applied."  This function handles the lvalue-to-rvalue
   10827   // conversion part.
   10828   MaybeODRUseExprs.erase(E->IgnoreParens());
   10829 }
   10830 
   10831 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
   10832   if (!Res.isUsable())
   10833     return Res;
   10834 
   10835   // If a constant-expression is a reference to a variable where we delay
   10836   // deciding whether it is an odr-use, just assume we will apply the
   10837   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
   10838   // (a non-type template argument), we have special handling anyway.
   10839   UpdateMarkingForLValueToRValue(Res.get());
   10840   return Res;
   10841 }
   10842 
   10843 void Sema::CleanupVarDeclMarking() {
   10844   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
   10845                                         e = MaybeODRUseExprs.end();
   10846        i != e; ++i) {
   10847     VarDecl *Var;
   10848     SourceLocation Loc;
   10849     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
   10850       Var = cast<VarDecl>(DRE->getDecl());
   10851       Loc = DRE->getLocation();
   10852     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
   10853       Var = cast<VarDecl>(ME->getMemberDecl());
   10854       Loc = ME->getMemberLoc();
   10855     } else {
   10856       llvm_unreachable("Unexpcted expression");
   10857     }
   10858 
   10859     MarkVarDeclODRUsed(*this, Var, Loc);
   10860   }
   10861 
   10862   MaybeODRUseExprs.clear();
   10863 }
   10864 
   10865 // Mark a VarDecl referenced, and perform the necessary handling to compute
   10866 // odr-uses.
   10867 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
   10868                                     VarDecl *Var, Expr *E) {
   10869   Var->setReferenced();
   10870 
   10871   if (!IsPotentiallyEvaluatedContext(SemaRef))
   10872     return;
   10873 
   10874   // Implicit instantiation of static data members of class templates.
   10875   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
   10876     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
   10877     assert(MSInfo && "Missing member specialization information?");
   10878     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
   10879     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
   10880         (!AlreadyInstantiated ||
   10881          Var->isUsableInConstantExpressions(SemaRef.Context))) {
   10882       if (!AlreadyInstantiated) {
   10883         // This is a modification of an existing AST node. Notify listeners.
   10884         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
   10885           L->StaticDataMemberInstantiated(Var);
   10886         MSInfo->setPointOfInstantiation(Loc);
   10887       }
   10888       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
   10889       if (Var->isUsableInConstantExpressions(SemaRef.Context))
   10890         // Do not defer instantiations of variables which could be used in a
   10891         // constant expression.
   10892         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
   10893       else
   10894         SemaRef.PendingInstantiations.push_back(
   10895             std::make_pair(Var, PointOfInstantiation));
   10896     }
   10897   }
   10898 
   10899   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
   10900   // an object that satisfies the requirements for appearing in a
   10901   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
   10902   // is immediately applied."  We check the first part here, and
   10903   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
   10904   // Note that we use the C++11 definition everywhere because nothing in
   10905   // C++03 depends on whether we get the C++03 version correct. This does not
   10906   // apply to references, since they are not objects.
   10907   const VarDecl *DefVD;
   10908   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
   10909       Var->isUsableInConstantExpressions(SemaRef.Context) &&
   10910       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
   10911     SemaRef.MaybeODRUseExprs.insert(E);
   10912   else
   10913     MarkVarDeclODRUsed(SemaRef, Var, Loc);
   10914 }
   10915 
   10916 /// \brief Mark a variable referenced, and check whether it is odr-used
   10917 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
   10918 /// used directly for normal expressions referring to VarDecl.
   10919 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
   10920   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
   10921 }
   10922 
   10923 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
   10924                                Decl *D, Expr *E) {
   10925   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
   10926     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
   10927     return;
   10928   }
   10929 
   10930   SemaRef.MarkAnyDeclReferenced(Loc, D);
   10931 
   10932   // If this is a call to a method via a cast, also mark the method in the
   10933   // derived class used in case codegen can devirtualize the call.
   10934   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
   10935   if (!ME)
   10936     return;
   10937   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
   10938   if (!MD)
   10939     return;
   10940   const Expr *Base = ME->getBase();
   10941   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
   10942   if (!MostDerivedClassDecl)
   10943     return;
   10944   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
   10945   if (!DM)
   10946     return;
   10947   SemaRef.MarkAnyDeclReferenced(Loc, DM);
   10948 }
   10949 
   10950 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
   10951 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
   10952   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
   10953 }
   10954 
   10955 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
   10956 void Sema::MarkMemberReferenced(MemberExpr *E) {
   10957   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
   10958 }
   10959 
   10960 /// \brief Perform marking for a reference to an arbitrary declaration.  It
   10961 /// marks the declaration referenced, and performs odr-use checking for functions
   10962 /// and variables. This method should not be used when building an normal
   10963 /// expression which refers to a variable.
   10964 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
   10965   if (VarDecl *VD = dyn_cast<VarDecl>(D))
   10966     MarkVariableReferenced(Loc, VD);
   10967   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
   10968     MarkFunctionReferenced(Loc, FD);
   10969   else
   10970     D->setReferenced();
   10971 }
   10972 
   10973 namespace {
   10974   // Mark all of the declarations referenced
   10975   // FIXME: Not fully implemented yet! We need to have a better understanding
   10976   // of when we're entering
   10977   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
   10978     Sema &S;
   10979     SourceLocation Loc;
   10980 
   10981   public:
   10982     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
   10983 
   10984     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
   10985 
   10986     bool TraverseTemplateArgument(const TemplateArgument &Arg);
   10987     bool TraverseRecordType(RecordType *T);
   10988   };
   10989 }
   10990 
   10991 bool MarkReferencedDecls::TraverseTemplateArgument(
   10992   const TemplateArgument &Arg) {
   10993   if (Arg.getKind() == TemplateArgument::Declaration) {
   10994     if (Decl *D = Arg.getAsDecl())
   10995       S.MarkAnyDeclReferenced(Loc, D);
   10996   }
   10997 
   10998   return Inherited::TraverseTemplateArgument(Arg);
   10999 }
   11000 
   11001 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
   11002   if (ClassTemplateSpecializationDecl *Spec
   11003                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
   11004     const TemplateArgumentList &Args = Spec->getTemplateArgs();
   11005     return TraverseTemplateArguments(Args.data(), Args.size());
   11006   }
   11007 
   11008   return true;
   11009 }
   11010 
   11011 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
   11012   MarkReferencedDecls Marker(*this, Loc);
   11013   Marker.TraverseType(Context.getCanonicalType(T));
   11014 }
   11015 
   11016 namespace {
   11017   /// \brief Helper class that marks all of the declarations referenced by
   11018   /// potentially-evaluated subexpressions as "referenced".
   11019   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
   11020     Sema &S;
   11021     bool SkipLocalVariables;
   11022 
   11023   public:
   11024     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
   11025 
   11026     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
   11027       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
   11028 
   11029     void VisitDeclRefExpr(DeclRefExpr *E) {
   11030       // If we were asked not to visit local variables, don't.
   11031       if (SkipLocalVariables) {
   11032         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
   11033           if (VD->hasLocalStorage())
   11034             return;
   11035       }
   11036 
   11037       S.MarkDeclRefReferenced(E);
   11038     }
   11039 
   11040     void VisitMemberExpr(MemberExpr *E) {
   11041       S.MarkMemberReferenced(E);
   11042       Inherited::VisitMemberExpr(E);
   11043     }
   11044 
   11045     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
   11046       S.MarkFunctionReferenced(E->getLocStart(),
   11047             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
   11048       Visit(E->getSubExpr());
   11049     }
   11050 
   11051     void VisitCXXNewExpr(CXXNewExpr *E) {
   11052       if (E->getOperatorNew())
   11053         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
   11054       if (E->getOperatorDelete())
   11055         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
   11056       Inherited::VisitCXXNewExpr(E);
   11057     }
   11058 
   11059     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
   11060       if (E->getOperatorDelete())
   11061         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
   11062       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
   11063       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
   11064         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
   11065         S.MarkFunctionReferenced(E->getLocStart(),
   11066                                     S.LookupDestructor(Record));
   11067       }
   11068 
   11069       Inherited::VisitCXXDeleteExpr(E);
   11070     }
   11071 
   11072     void VisitCXXConstructExpr(CXXConstructExpr *E) {
   11073       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
   11074       Inherited::VisitCXXConstructExpr(E);
   11075     }
   11076 
   11077     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
   11078       Visit(E->getExpr());
   11079     }
   11080 
   11081     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
   11082       Inherited::VisitImplicitCastExpr(E);
   11083 
   11084       if (E->getCastKind() == CK_LValueToRValue)
   11085         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
   11086     }
   11087   };
   11088 }
   11089 
   11090 /// \brief Mark any declarations that appear within this expression or any
   11091 /// potentially-evaluated subexpressions as "referenced".
   11092 ///
   11093 /// \param SkipLocalVariables If true, don't mark local variables as
   11094 /// 'referenced'.
   11095 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
   11096                                             bool SkipLocalVariables) {
   11097   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
   11098 }
   11099 
   11100 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
   11101 /// of the program being compiled.
   11102 ///
   11103 /// This routine emits the given diagnostic when the code currently being
   11104 /// type-checked is "potentially evaluated", meaning that there is a
   11105 /// possibility that the code will actually be executable. Code in sizeof()
   11106 /// expressions, code used only during overload resolution, etc., are not
   11107 /// potentially evaluated. This routine will suppress such diagnostics or,
   11108 /// in the absolutely nutty case of potentially potentially evaluated
   11109 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
   11110 /// later.
   11111 ///
   11112 /// This routine should be used for all diagnostics that describe the run-time
   11113 /// behavior of a program, such as passing a non-POD value through an ellipsis.
   11114 /// Failure to do so will likely result in spurious diagnostics or failures
   11115 /// during overload resolution or within sizeof/alignof/typeof/typeid.
   11116 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
   11117                                const PartialDiagnostic &PD) {
   11118   switch (ExprEvalContexts.back().Context) {
   11119   case Unevaluated:
   11120     // The argument will never be evaluated, so don't complain.
   11121     break;
   11122 
   11123   case ConstantEvaluated:
   11124     // Relevant diagnostics should be produced by constant evaluation.
   11125     break;
   11126 
   11127   case PotentiallyEvaluated:
   11128   case PotentiallyEvaluatedIfUsed:
   11129     if (Statement && getCurFunctionOrMethodDecl()) {
   11130       FunctionScopes.back()->PossiblyUnreachableDiags.
   11131         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
   11132     }
   11133     else
   11134       Diag(Loc, PD);
   11135 
   11136     return true;
   11137   }
   11138 
   11139   return false;
   11140 }
   11141 
   11142 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
   11143                                CallExpr *CE, FunctionDecl *FD) {
   11144   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
   11145     return false;
   11146 
   11147   // If we're inside a decltype's expression, don't check for a valid return
   11148   // type or construct temporaries until we know whether this is the last call.
   11149   if (ExprEvalContexts.back().IsDecltype) {
   11150     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
   11151     return false;
   11152   }
   11153 
   11154   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
   11155     FunctionDecl *FD;
   11156     CallExpr *CE;
   11157 
   11158   public:
   11159     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
   11160       : FD(FD), CE(CE) { }
   11161 
   11162     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
   11163       if (!FD) {
   11164         S.Diag(Loc, diag::err_call_incomplete_return)
   11165           << T << CE->getSourceRange();
   11166         return;
   11167       }
   11168 
   11169       S.Diag(Loc, diag::err_call_function_incomplete_return)
   11170         << CE->getSourceRange() << FD->getDeclName() << T;
   11171       S.Diag(FD->getLocation(),
   11172              diag::note_function_with_incomplete_return_type_declared_here)
   11173         << FD->getDeclName();
   11174     }
   11175   } Diagnoser(FD, CE);
   11176 
   11177   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
   11178     return true;
   11179 
   11180   return false;
   11181 }
   11182 
   11183 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
   11184 // will prevent this condition from triggering, which is what we want.
   11185 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
   11186   SourceLocation Loc;
   11187 
   11188   unsigned diagnostic = diag::warn_condition_is_assignment;
   11189   bool IsOrAssign = false;
   11190 
   11191   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
   11192     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
   11193       return;
   11194 
   11195     IsOrAssign = Op->getOpcode() == BO_OrAssign;
   11196 
   11197     // Greylist some idioms by putting them into a warning subcategory.
   11198     if (ObjCMessageExpr *ME
   11199           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
   11200       Selector Sel = ME->getSelector();
   11201 
   11202       // self = [<foo> init...]
   11203       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
   11204         diagnostic = diag::warn_condition_is_idiomatic_assignment;
   11205 
   11206       // <foo> = [<bar> nextObject]
   11207       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
   11208         diagnostic = diag::warn_condition_is_idiomatic_assignment;
   11209     }
   11210 
   11211     Loc = Op->getOperatorLoc();
   11212   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
   11213     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
   11214       return;
   11215 
   11216     IsOrAssign = Op->getOperator() == OO_PipeEqual;
   11217     Loc = Op->getOperatorLoc();
   11218   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
   11219     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
   11220   else {
   11221     // Not an assignment.
   11222     return;
   11223   }
   11224 
   11225   Diag(Loc, diagnostic) << E->getSourceRange();
   11226 
   11227   SourceLocation Open = E->getLocStart();
   11228   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
   11229   Diag(Loc, diag::note_condition_assign_silence)
   11230         << FixItHint::CreateInsertion(Open, "(")
   11231         << FixItHint::CreateInsertion(Close, ")");
   11232 
   11233   if (IsOrAssign)
   11234     Diag(Loc, diag::note_condition_or_assign_to_comparison)
   11235       << FixItHint::CreateReplacement(Loc, "!=");
   11236   else
   11237     Diag(Loc, diag::note_condition_assign_to_comparison)
   11238       << FixItHint::CreateReplacement(Loc, "==");
   11239 }
   11240 
   11241 /// \brief Redundant parentheses over an equality comparison can indicate
   11242 /// that the user intended an assignment used as condition.
   11243 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
   11244   // Don't warn if the parens came from a macro.
   11245   SourceLocation parenLoc = ParenE->getLocStart();
   11246   if (parenLoc.isInvalid() || parenLoc.isMacroID())
   11247     return;
   11248   // Don't warn for dependent expressions.
   11249   if (ParenE->isTypeDependent())
   11250     return;
   11251 
   11252   Expr *E = ParenE->IgnoreParens();
   11253 
   11254   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
   11255     if (opE->getOpcode() == BO_EQ &&
   11256         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
   11257                                                            == Expr::MLV_Valid) {
   11258       SourceLocation Loc = opE->getOperatorLoc();
   11259 
   11260       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
   11261       SourceRange ParenERange = ParenE->getSourceRange();
   11262       Diag(Loc, diag::note_equality_comparison_silence)
   11263         << FixItHint::CreateRemoval(ParenERange.getBegin())
   11264         << FixItHint::CreateRemoval(ParenERange.getEnd());
   11265       Diag(Loc, diag::note_equality_comparison_to_assign)
   11266         << FixItHint::CreateReplacement(Loc, "=");
   11267     }
   11268 }
   11269 
   11270 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
   11271   DiagnoseAssignmentAsCondition(E);
   11272   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
   11273     DiagnoseEqualityWithExtraParens(parenE);
   11274 
   11275   ExprResult result = CheckPlaceholderExpr(E);
   11276   if (result.isInvalid()) return ExprError();
   11277   E = result.take();
   11278 
   11279   if (!E->isTypeDependent()) {
   11280     if (getLangOpts().CPlusPlus)
   11281       return CheckCXXBooleanCondition(E); // C++ 6.4p4
   11282 
   11283     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
   11284     if (ERes.isInvalid())
   11285       return ExprError();
   11286     E = ERes.take();
   11287 
   11288     QualType T = E->getType();
   11289     if (!T->isScalarType()) { // C99 6.8.4.1p1
   11290       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
   11291         << T << E->getSourceRange();
   11292       return ExprError();
   11293     }
   11294   }
   11295 
   11296   return Owned(E);
   11297 }
   11298 
   11299 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
   11300                                        Expr *SubExpr) {
   11301   if (!SubExpr)
   11302     return ExprError();
   11303 
   11304   return CheckBooleanCondition(SubExpr, Loc);
   11305 }
   11306 
   11307 namespace {
   11308   /// A visitor for rebuilding a call to an __unknown_any expression
   11309   /// to have an appropriate type.
   11310   struct RebuildUnknownAnyFunction
   11311     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
   11312 
   11313     Sema &S;
   11314 
   11315     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
   11316 
   11317     ExprResult VisitStmt(Stmt *S) {
   11318       llvm_unreachable("unexpected statement!");
   11319     }
   11320 
   11321     ExprResult VisitExpr(Expr *E) {
   11322       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
   11323         << E->getSourceRange();
   11324       return ExprError();
   11325     }
   11326 
   11327     /// Rebuild an expression which simply semantically wraps another
   11328     /// expression which it shares the type and value kind of.
   11329     template <class T> ExprResult rebuildSugarExpr(T *E) {
   11330       ExprResult SubResult = Visit(E->getSubExpr());
   11331       if (SubResult.isInvalid()) return ExprError();
   11332 
   11333       Expr *SubExpr = SubResult.take();
   11334       E->setSubExpr(SubExpr);
   11335       E->setType(SubExpr->getType());
   11336       E->setValueKind(SubExpr->getValueKind());
   11337       assert(E->getObjectKind() == OK_Ordinary);
   11338       return E;
   11339     }
   11340 
   11341     ExprResult VisitParenExpr(ParenExpr *E) {
   11342       return rebuildSugarExpr(E);
   11343     }
   11344 
   11345     ExprResult VisitUnaryExtension(UnaryOperator *E) {
   11346       return rebuildSugarExpr(E);
   11347     }
   11348 
   11349     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
   11350       ExprResult SubResult = Visit(E->getSubExpr());
   11351       if (SubResult.isInvalid()) return ExprError();
   11352 
   11353       Expr *SubExpr = SubResult.take();
   11354       E->setSubExpr(SubExpr);
   11355       E->setType(S.Context.getPointerType(SubExpr->getType()));
   11356       assert(E->getValueKind() == VK_RValue);
   11357       assert(E->getObjectKind() == OK_Ordinary);
   11358       return E;
   11359     }
   11360 
   11361     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
   11362       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
   11363 
   11364       E->setType(VD->getType());
   11365 
   11366       assert(E->getValueKind() == VK_RValue);
   11367       if (S.getLangOpts().CPlusPlus &&
   11368           !(isa<CXXMethodDecl>(VD) &&
   11369             cast<CXXMethodDecl>(VD)->isInstance()))
   11370         E->setValueKind(VK_LValue);
   11371 
   11372       return E;
   11373     }
   11374 
   11375     ExprResult VisitMemberExpr(MemberExpr *E) {
   11376       return resolveDecl(E, E->getMemberDecl());
   11377     }
   11378 
   11379     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
   11380       return resolveDecl(E, E->getDecl());
   11381     }
   11382   };
   11383 }
   11384 
   11385 /// Given a function expression of unknown-any type, try to rebuild it
   11386 /// to have a function type.
   11387 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
   11388   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
   11389   if (Result.isInvalid()) return ExprError();
   11390   return S.DefaultFunctionArrayConversion(Result.take());
   11391 }
   11392 
   11393 namespace {
   11394   /// A visitor for rebuilding an expression of type __unknown_anytype
   11395   /// into one which resolves the type directly on the referring
   11396   /// expression.  Strict preservation of the original source
   11397   /// structure is not a goal.
   11398   struct RebuildUnknownAnyExpr
   11399     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
   11400 
   11401     Sema &S;
   11402 
   11403     /// The current destination type.
   11404     QualType DestType;
   11405 
   11406     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
   11407       : S(S), DestType(CastType) {}
   11408 
   11409     ExprResult VisitStmt(Stmt *S) {
   11410       llvm_unreachable("unexpected statement!");
   11411     }
   11412 
   11413     ExprResult VisitExpr(Expr *E) {
   11414       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
   11415         << E->getSourceRange();
   11416       return ExprError();
   11417     }
   11418 
   11419     ExprResult VisitCallExpr(CallExpr *E);
   11420     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
   11421 
   11422     /// Rebuild an expression which simply semantically wraps another
   11423     /// expression which it shares the type and value kind of.
   11424     template <class T> ExprResult rebuildSugarExpr(T *E) {
   11425       ExprResult SubResult = Visit(E->getSubExpr());
   11426       if (SubResult.isInvalid()) return ExprError();
   11427       Expr *SubExpr = SubResult.take();
   11428       E->setSubExpr(SubExpr);
   11429       E->setType(SubExpr->getType());
   11430       E->setValueKind(SubExpr->getValueKind());
   11431       assert(E->getObjectKind() == OK_Ordinary);
   11432       return E;
   11433     }
   11434 
   11435     ExprResult VisitParenExpr(ParenExpr *E) {
   11436       return rebuildSugarExpr(E);
   11437     }
   11438 
   11439     ExprResult VisitUnaryExtension(UnaryOperator *E) {
   11440       return rebuildSugarExpr(E);
   11441     }
   11442 
   11443     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
   11444       const PointerType *Ptr = DestType->getAs<PointerType>();
   11445       if (!Ptr) {
   11446         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
   11447           << E->getSourceRange();
   11448         return ExprError();
   11449       }
   11450       assert(E->getValueKind() == VK_RValue);
   11451       assert(E->getObjectKind() == OK_Ordinary);
   11452       E->setType(DestType);
   11453 
   11454       // Build the sub-expression as if it were an object of the pointee type.
   11455       DestType = Ptr->getPointeeType();
   11456       ExprResult SubResult = Visit(E->getSubExpr());
   11457       if (SubResult.isInvalid()) return ExprError();
   11458       E->setSubExpr(SubResult.take());
   11459       return E;
   11460     }
   11461 
   11462     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
   11463 
   11464     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
   11465 
   11466     ExprResult VisitMemberExpr(MemberExpr *E) {
   11467       return resolveDecl(E, E->getMemberDecl());
   11468     }
   11469 
   11470     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
   11471       return resolveDecl(E, E->getDecl());
   11472     }
   11473   };
   11474 }
   11475 
   11476 /// Rebuilds a call expression which yielded __unknown_anytype.
   11477 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
   11478   Expr *CalleeExpr = E->getCallee();
   11479 
   11480   enum FnKind {
   11481     FK_MemberFunction,
   11482     FK_FunctionPointer,
   11483     FK_BlockPointer
   11484   };
   11485 
   11486   FnKind Kind;
   11487   QualType CalleeType = CalleeExpr->getType();
   11488   if (CalleeType == S.Context.BoundMemberTy) {
   11489     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
   11490     Kind = FK_MemberFunction;
   11491     CalleeType = Expr::findBoundMemberType(CalleeExpr);
   11492   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
   11493     CalleeType = Ptr->getPointeeType();
   11494     Kind = FK_FunctionPointer;
   11495   } else {
   11496     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
   11497     Kind = FK_BlockPointer;
   11498   }
   11499   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
   11500 
   11501   // Verify that this is a legal result type of a function.
   11502   if (DestType->isArrayType() || DestType->isFunctionType()) {
   11503     unsigned diagID = diag::err_func_returning_array_function;
   11504     if (Kind == FK_BlockPointer)
   11505       diagID = diag::err_block_returning_array_function;
   11506 
   11507     S.Diag(E->getExprLoc(), diagID)
   11508       << DestType->isFunctionType() << DestType;
   11509     return ExprError();
   11510   }
   11511 
   11512   // Otherwise, go ahead and set DestType as the call's result.
   11513   E->setType(DestType.getNonLValueExprType(S.Context));
   11514   E->setValueKind(Expr::getValueKindForType(DestType));
   11515   assert(E->getObjectKind() == OK_Ordinary);
   11516 
   11517   // Rebuild the function type, replacing the result type with DestType.
   11518   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
   11519     DestType = S.Context.getFunctionType(DestType,
   11520                                          Proto->arg_type_begin(),
   11521                                          Proto->getNumArgs(),
   11522                                          Proto->getExtProtoInfo());
   11523   else
   11524     DestType = S.Context.getFunctionNoProtoType(DestType,
   11525                                                 FnType->getExtInfo());
   11526 
   11527   // Rebuild the appropriate pointer-to-function type.
   11528   switch (Kind) {
   11529   case FK_MemberFunction:
   11530     // Nothing to do.
   11531     break;
   11532 
   11533   case FK_FunctionPointer:
   11534     DestType = S.Context.getPointerType(DestType);
   11535     break;
   11536 
   11537   case FK_BlockPointer:
   11538     DestType = S.Context.getBlockPointerType(DestType);
   11539     break;
   11540   }
   11541 
   11542   // Finally, we can recurse.
   11543   ExprResult CalleeResult = Visit(CalleeExpr);
   11544   if (!CalleeResult.isUsable()) return ExprError();
   11545   E->setCallee(CalleeResult.take());
   11546 
   11547   // Bind a temporary if necessary.
   11548   return S.MaybeBindToTemporary(E);
   11549 }
   11550 
   11551 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
   11552   // Verify that this is a legal result type of a call.
   11553   if (DestType->isArrayType() || DestType->isFunctionType()) {
   11554     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
   11555       << DestType->isFunctionType() << DestType;
   11556     return ExprError();
   11557   }
   11558 
   11559   // Rewrite the method result type if available.
   11560   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
   11561     assert(Method->getResultType() == S.Context.UnknownAnyTy);
   11562     Method->setResultType(DestType);
   11563   }
   11564 
   11565   // Change the type of the message.
   11566   E->setType(DestType.getNonReferenceType());
   11567   E->setValueKind(Expr::getValueKindForType(DestType));
   11568 
   11569   return S.MaybeBindToTemporary(E);
   11570 }
   11571 
   11572 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   11573   // The only case we should ever see here is a function-to-pointer decay.
   11574   if (E->getCastKind() == CK_FunctionToPointerDecay) {
   11575     assert(E->getValueKind() == VK_RValue);
   11576     assert(E->getObjectKind() == OK_Ordinary);
   11577 
   11578     E->setType(DestType);
   11579 
   11580     // Rebuild the sub-expression as the pointee (function) type.
   11581     DestType = DestType->castAs<PointerType>()->getPointeeType();
   11582 
   11583     ExprResult Result = Visit(E->getSubExpr());
   11584     if (!Result.isUsable()) return ExprError();
   11585 
   11586     E->setSubExpr(Result.take());
   11587     return S.Owned(E);
   11588   } else if (E->getCastKind() == CK_LValueToRValue) {
   11589     assert(E->getValueKind() == VK_RValue);
   11590     assert(E->getObjectKind() == OK_Ordinary);
   11591 
   11592     assert(isa<BlockPointerType>(E->getType()));
   11593 
   11594     E->setType(DestType);
   11595 
   11596     // The sub-expression has to be a lvalue reference, so rebuild it as such.
   11597     DestType = S.Context.getLValueReferenceType(DestType);
   11598 
   11599     ExprResult Result = Visit(E->getSubExpr());
   11600     if (!Result.isUsable()) return ExprError();
   11601 
   11602     E->setSubExpr(Result.take());
   11603     return S.Owned(E);
   11604   } else {
   11605     llvm_unreachable("Unhandled cast type!");
   11606   }
   11607 }
   11608 
   11609 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
   11610   ExprValueKind ValueKind = VK_LValue;
   11611   QualType Type = DestType;
   11612 
   11613   // We know how to make this work for certain kinds of decls:
   11614 
   11615   //  - functions
   11616   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
   11617     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
   11618       DestType = Ptr->getPointeeType();
   11619       ExprResult Result = resolveDecl(E, VD);
   11620       if (Result.isInvalid()) return ExprError();
   11621       return S.ImpCastExprToType(Result.take(), Type,
   11622                                  CK_FunctionToPointerDecay, VK_RValue);
   11623     }
   11624 
   11625     if (!Type->isFunctionType()) {
   11626       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
   11627         << VD << E->getSourceRange();
   11628       return ExprError();
   11629     }
   11630 
   11631     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
   11632       if (MD->isInstance()) {
   11633         ValueKind = VK_RValue;
   11634         Type = S.Context.BoundMemberTy;
   11635       }
   11636 
   11637     // Function references aren't l-values in C.
   11638     if (!S.getLangOpts().CPlusPlus)
   11639       ValueKind = VK_RValue;
   11640 
   11641   //  - variables
   11642   } else if (isa<VarDecl>(VD)) {
   11643     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
   11644       Type = RefTy->getPointeeType();
   11645     } else if (Type->isFunctionType()) {
   11646       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
   11647         << VD << E->getSourceRange();
   11648       return ExprError();
   11649     }
   11650 
   11651   //  - nothing else
   11652   } else {
   11653     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
   11654       << VD << E->getSourceRange();
   11655     return ExprError();
   11656   }
   11657 
   11658   VD->setType(DestType);
   11659   E->setType(Type);
   11660   E->setValueKind(ValueKind);
   11661   return S.Owned(E);
   11662 }
   11663 
   11664 /// Check a cast of an unknown-any type.  We intentionally only
   11665 /// trigger this for C-style casts.
   11666 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
   11667                                      Expr *CastExpr, CastKind &CastKind,
   11668                                      ExprValueKind &VK, CXXCastPath &Path) {
   11669   // Rewrite the casted expression from scratch.
   11670   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
   11671   if (!result.isUsable()) return ExprError();
   11672 
   11673   CastExpr = result.take();
   11674   VK = CastExpr->getValueKind();
   11675   CastKind = CK_NoOp;
   11676 
   11677   return CastExpr;
   11678 }
   11679 
   11680 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
   11681   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
   11682 }
   11683 
   11684 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
   11685   Expr *orig = E;
   11686   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
   11687   while (true) {
   11688     E = E->IgnoreParenImpCasts();
   11689     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
   11690       E = call->getCallee();
   11691       diagID = diag::err_uncasted_call_of_unknown_any;
   11692     } else {
   11693       break;
   11694     }
   11695   }
   11696 
   11697   SourceLocation loc;
   11698   NamedDecl *d;
   11699   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
   11700     loc = ref->getLocation();
   11701     d = ref->getDecl();
   11702   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
   11703     loc = mem->getMemberLoc();
   11704     d = mem->getMemberDecl();
   11705   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
   11706     diagID = diag::err_uncasted_call_of_unknown_any;
   11707     loc = msg->getSelectorStartLoc();
   11708     d = msg->getMethodDecl();
   11709     if (!d) {
   11710       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
   11711         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
   11712         << orig->getSourceRange();
   11713       return ExprError();
   11714     }
   11715   } else {
   11716     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
   11717       << E->getSourceRange();
   11718     return ExprError();
   11719   }
   11720 
   11721   S.Diag(loc, diagID) << d << orig->getSourceRange();
   11722 
   11723   // Never recoverable.
   11724   return ExprError();
   11725 }
   11726 
   11727 /// Check for operands with placeholder types and complain if found.
   11728 /// Returns true if there was an error and no recovery was possible.
   11729 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
   11730   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
   11731   if (!placeholderType) return Owned(E);
   11732 
   11733   switch (placeholderType->getKind()) {
   11734 
   11735   // Overloaded expressions.
   11736   case BuiltinType::Overload: {
   11737     // Try to resolve a single function template specialization.
   11738     // This is obligatory.
   11739     ExprResult result = Owned(E);
   11740     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
   11741       return result;
   11742 
   11743     // If that failed, try to recover with a call.
   11744     } else {
   11745       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
   11746                            /*complain*/ true);
   11747       return result;
   11748     }
   11749   }
   11750 
   11751   // Bound member functions.
   11752   case BuiltinType::BoundMember: {
   11753     ExprResult result = Owned(E);
   11754     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
   11755                          /*complain*/ true);
   11756     return result;
   11757   }
   11758 
   11759   // ARC unbridged casts.
   11760   case BuiltinType::ARCUnbridgedCast: {
   11761     Expr *realCast = stripARCUnbridgedCast(E);
   11762     diagnoseARCUnbridgedCast(realCast);
   11763     return Owned(realCast);
   11764   }
   11765 
   11766   // Expressions of unknown type.
   11767   case BuiltinType::UnknownAny:
   11768     return diagnoseUnknownAnyExpr(*this, E);
   11769 
   11770   // Pseudo-objects.
   11771   case BuiltinType::PseudoObject:
   11772     return checkPseudoObjectRValue(E);
   11773 
   11774   case BuiltinType::BuiltinFn:
   11775     Diag(E->getLocStart(), diag::err_builtin_fn_use);
   11776     return ExprError();
   11777 
   11778   // Everything else should be impossible.
   11779 #define BUILTIN_TYPE(Id, SingletonId) \
   11780   case BuiltinType::Id:
   11781 #define PLACEHOLDER_TYPE(Id, SingletonId)
   11782 #include "clang/AST/BuiltinTypes.def"
   11783     break;
   11784   }
   11785 
   11786   llvm_unreachable("invalid placeholder type!");
   11787 }
   11788 
   11789 bool Sema::CheckCaseExpression(Expr *E) {
   11790   if (E->isTypeDependent())
   11791     return true;
   11792   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
   11793     return E->getType()->isIntegralOrEnumerationType();
   11794   return false;
   11795 }
   11796 
   11797 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
   11798 ExprResult
   11799 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
   11800   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
   11801          "Unknown Objective-C Boolean value!");
   11802   QualType BoolT = Context.ObjCBuiltinBoolTy;
   11803   if (!Context.getBOOLDecl()) {
   11804     LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
   11805                         Sema::LookupOrdinaryName);
   11806     if (LookupName(Result, getCurScope())) {
   11807       NamedDecl *ND = Result.getFoundDecl();
   11808       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
   11809         Context.setBOOLDecl(TD);
   11810     }
   11811   }
   11812   if (Context.getBOOLDecl())
   11813     BoolT = Context.getBOOLType();
   11814   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
   11815                                         BoolT, OpLoc));
   11816 }
   11817