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 "TreeTransform.h"
     16 #include "clang/AST/ASTConsumer.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/ASTMutationListener.h"
     19 #include "clang/AST/CXXInheritance.h"
     20 #include "clang/AST/DeclObjC.h"
     21 #include "clang/AST/DeclTemplate.h"
     22 #include "clang/AST/EvaluatedExprVisitor.h"
     23 #include "clang/AST/Expr.h"
     24 #include "clang/AST/ExprCXX.h"
     25 #include "clang/AST/ExprObjC.h"
     26 #include "clang/AST/RecursiveASTVisitor.h"
     27 #include "clang/AST/TypeLoc.h"
     28 #include "clang/Basic/PartialDiagnostic.h"
     29 #include "clang/Basic/SourceManager.h"
     30 #include "clang/Basic/TargetInfo.h"
     31 #include "clang/Lex/LiteralSupport.h"
     32 #include "clang/Lex/Preprocessor.h"
     33 #include "clang/Sema/AnalysisBasedWarnings.h"
     34 #include "clang/Sema/DeclSpec.h"
     35 #include "clang/Sema/DelayedDiagnostic.h"
     36 #include "clang/Sema/Designator.h"
     37 #include "clang/Sema/Initialization.h"
     38 #include "clang/Sema/Lookup.h"
     39 #include "clang/Sema/ParsedTemplate.h"
     40 #include "clang/Sema/Scope.h"
     41 #include "clang/Sema/ScopeInfo.h"
     42 #include "clang/Sema/SemaFixItUtils.h"
     43 #include "clang/Sema/Template.h"
     44 using namespace clang;
     45 using namespace sema;
     46 
     47 /// \brief Determine whether the use of this declaration is valid, without
     48 /// emitting diagnostics.
     49 bool Sema::CanUseDecl(NamedDecl *D) {
     50   // See if this is an auto-typed variable whose initializer we are parsing.
     51   if (ParsingInitForAutoVars.count(D))
     52     return false;
     53 
     54   // See if this is a deleted function.
     55   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
     56     if (FD->isDeleted())
     57       return false;
     58   }
     59 
     60   // See if this function is unavailable.
     61   if (D->getAvailability() == AR_Unavailable &&
     62       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
     63     return false;
     64 
     65   return true;
     66 }
     67 
     68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
     69   // Warn if this is used but marked unused.
     70   if (D->hasAttr<UnusedAttr>()) {
     71     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
     72     if (!DC->hasAttr<UnusedAttr>())
     73       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
     74   }
     75 }
     76 
     77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
     78                               NamedDecl *D, SourceLocation Loc,
     79                               const ObjCInterfaceDecl *UnknownObjCClass) {
     80   // See if this declaration is unavailable or deprecated.
     81   std::string Message;
     82   AvailabilityResult Result = D->getAvailability(&Message);
     83   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
     84     if (Result == AR_Available) {
     85       const DeclContext *DC = ECD->getDeclContext();
     86       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
     87         Result = TheEnumDecl->getAvailability(&Message);
     88     }
     89 
     90   const ObjCPropertyDecl *ObjCPDecl = 0;
     91   if (Result == AR_Deprecated || Result == AR_Unavailable) {
     92     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
     93       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
     94         AvailabilityResult PDeclResult = PD->getAvailability(0);
     95         if (PDeclResult == Result)
     96           ObjCPDecl = PD;
     97       }
     98     }
     99   }
    100 
    101   switch (Result) {
    102     case AR_Available:
    103     case AR_NotYetIntroduced:
    104       break;
    105 
    106     case AR_Deprecated:
    107       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
    108       break;
    109 
    110     case AR_Unavailable:
    111       if (S.getCurContextAvailability() != AR_Unavailable) {
    112         if (Message.empty()) {
    113           if (!UnknownObjCClass) {
    114             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
    115             if (ObjCPDecl)
    116               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
    117                 << ObjCPDecl->getDeclName() << 1;
    118           }
    119           else
    120             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
    121               << D->getDeclName();
    122         }
    123         else
    124           S.Diag(Loc, diag::err_unavailable_message)
    125             << D->getDeclName() << Message;
    126         S.Diag(D->getLocation(), diag::note_unavailable_here)
    127                   << isa<FunctionDecl>(D) << false;
    128         if (ObjCPDecl)
    129           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
    130           << ObjCPDecl->getDeclName() << 1;
    131       }
    132       break;
    133     }
    134     return Result;
    135 }
    136 
    137 /// \brief Emit a note explaining that this function is deleted or unavailable.
    138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
    139   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
    140 
    141   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
    142     // If the method was explicitly defaulted, point at that declaration.
    143     if (!Method->isImplicit())
    144       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
    145 
    146     // Try to diagnose why this special member function was implicitly
    147     // deleted. This might fail, if that reason no longer applies.
    148     CXXSpecialMember CSM = getSpecialMember(Method);
    149     if (CSM != CXXInvalid)
    150       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
    151 
    152     return;
    153   }
    154 
    155   Diag(Decl->getLocation(), diag::note_unavailable_here)
    156     << 1 << Decl->isDeleted();
    157 }
    158 
    159 /// \brief Determine whether a FunctionDecl was ever declared with an
    160 /// explicit storage class.
    161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
    162   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
    163                                      E = D->redecls_end();
    164        I != E; ++I) {
    165     if (I->getStorageClassAsWritten() != SC_None)
    166       return true;
    167   }
    168   return false;
    169 }
    170 
    171 /// \brief Check whether we're in an extern inline function and referring to a
    172 /// variable or function with internal linkage (C11 6.7.4p3).
    173 ///
    174 /// This is only a warning because we used to silently accept this code, but
    175 /// in many cases it will not behave correctly. This is not enabled in C++ mode
    176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
    177 /// and so while there may still be user mistakes, most of the time we can't
    178 /// prove that there are errors.
    179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
    180                                                       const NamedDecl *D,
    181                                                       SourceLocation Loc) {
    182   // This is disabled under C++; there are too many ways for this to fire in
    183   // contexts where the warning is a false positive, or where it is technically
    184   // correct but benign.
    185   if (S.getLangOpts().CPlusPlus)
    186     return;
    187 
    188   // Check if this is an inlined function or method.
    189   FunctionDecl *Current = S.getCurFunctionDecl();
    190   if (!Current)
    191     return;
    192   if (!Current->isInlined())
    193     return;
    194   if (Current->getLinkage() != ExternalLinkage)
    195     return;
    196 
    197   // Check if the decl has internal linkage.
    198   if (D->getLinkage() != InternalLinkage)
    199     return;
    200 
    201   // Downgrade from ExtWarn to Extension if
    202   //  (1) the supposedly external inline function is in the main file,
    203   //      and probably won't be included anywhere else.
    204   //  (2) the thing we're referencing is a pure function.
    205   //  (3) the thing we're referencing is another inline function.
    206   // This last can give us false negatives, but it's better than warning on
    207   // wrappers for simple C library functions.
    208   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
    209   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
    210   if (!DowngradeWarning && UsedFn)
    211     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
    212 
    213   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
    214                                : diag::warn_internal_in_extern_inline)
    215     << /*IsVar=*/!UsedFn << D;
    216 
    217   // Suggest "static" on the inline function, if possible.
    218   if (!hasAnyExplicitStorageClass(Current)) {
    219     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
    220     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
    221     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
    222       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
    223   }
    224 
    225   S.Diag(D->getCanonicalDecl()->getLocation(),
    226          diag::note_internal_decl_declared_here)
    227     << D;
    228 }
    229 
    230 /// \brief Determine whether the use of this declaration is valid, and
    231 /// emit any corresponding diagnostics.
    232 ///
    233 /// This routine diagnoses various problems with referencing
    234 /// declarations that can occur when using a declaration. For example,
    235 /// it might warn if a deprecated or unavailable declaration is being
    236 /// used, or produce an error (and return true) if a C++0x deleted
    237 /// function is being used.
    238 ///
    239 /// \returns true if there was an error (this declaration cannot be
    240 /// referenced), false otherwise.
    241 ///
    242 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
    243                              const ObjCInterfaceDecl *UnknownObjCClass) {
    244   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
    245     // If there were any diagnostics suppressed by template argument deduction,
    246     // emit them now.
    247     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
    248       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
    249     if (Pos != SuppressedDiagnostics.end()) {
    250       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
    251       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
    252         Diag(Suppressed[I].first, Suppressed[I].second);
    253 
    254       // Clear out the list of suppressed diagnostics, so that we don't emit
    255       // them again for this specialization. However, we don't obsolete this
    256       // entry from the table, because we want to avoid ever emitting these
    257       // diagnostics again.
    258       Suppressed.clear();
    259     }
    260   }
    261 
    262   // See if this is an auto-typed variable whose initializer we are parsing.
    263   if (ParsingInitForAutoVars.count(D)) {
    264     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
    265       << D->getDeclName();
    266     return true;
    267   }
    268 
    269   // See if this is a deleted function.
    270   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    271     if (FD->isDeleted()) {
    272       Diag(Loc, diag::err_deleted_function_use);
    273       NoteDeletedFunction(FD);
    274       return true;
    275     }
    276   }
    277   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
    278 
    279   DiagnoseUnusedOfDecl(*this, D, Loc);
    280 
    281   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
    282 
    283   return false;
    284 }
    285 
    286 /// \brief Retrieve the message suffix that should be added to a
    287 /// diagnostic complaining about the given function being deleted or
    288 /// unavailable.
    289 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
    290   std::string Message;
    291   if (FD->getAvailability(&Message))
    292     return ": " + Message;
    293 
    294   return std::string();
    295 }
    296 
    297 /// DiagnoseSentinelCalls - This routine checks whether a call or
    298 /// message-send is to a declaration with the sentinel attribute, and
    299 /// if so, it checks that the requirements of the sentinel are
    300 /// satisfied.
    301 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
    302                                  Expr **args, unsigned numArgs) {
    303   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
    304   if (!attr)
    305     return;
    306 
    307   // The number of formal parameters of the declaration.
    308   unsigned numFormalParams;
    309 
    310   // The kind of declaration.  This is also an index into a %select in
    311   // the diagnostic.
    312   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
    313 
    314   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
    315     numFormalParams = MD->param_size();
    316     calleeType = CT_Method;
    317   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    318     numFormalParams = FD->param_size();
    319     calleeType = CT_Function;
    320   } else if (isa<VarDecl>(D)) {
    321     QualType type = cast<ValueDecl>(D)->getType();
    322     const FunctionType *fn = 0;
    323     if (const PointerType *ptr = type->getAs<PointerType>()) {
    324       fn = ptr->getPointeeType()->getAs<FunctionType>();
    325       if (!fn) return;
    326       calleeType = CT_Function;
    327     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
    328       fn = ptr->getPointeeType()->castAs<FunctionType>();
    329       calleeType = CT_Block;
    330     } else {
    331       return;
    332     }
    333 
    334     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
    335       numFormalParams = proto->getNumArgs();
    336     } else {
    337       numFormalParams = 0;
    338     }
    339   } else {
    340     return;
    341   }
    342 
    343   // "nullPos" is the number of formal parameters at the end which
    344   // effectively count as part of the variadic arguments.  This is
    345   // useful if you would prefer to not have *any* formal parameters,
    346   // but the language forces you to have at least one.
    347   unsigned nullPos = attr->getNullPos();
    348   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
    349   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
    350 
    351   // The number of arguments which should follow the sentinel.
    352   unsigned numArgsAfterSentinel = attr->getSentinel();
    353 
    354   // If there aren't enough arguments for all the formal parameters,
    355   // the sentinel, and the args after the sentinel, complain.
    356   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
    357     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
    358     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
    359     return;
    360   }
    361 
    362   // Otherwise, find the sentinel expression.
    363   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
    364   if (!sentinelExpr) return;
    365   if (sentinelExpr->isValueDependent()) return;
    366   if (Context.isSentinelNullExpr(sentinelExpr)) return;
    367 
    368   // Pick a reasonable string to insert.  Optimistically use 'nil' or
    369   // 'NULL' if those are actually defined in the context.  Only use
    370   // 'nil' for ObjC methods, where it's much more likely that the
    371   // variadic arguments form a list of object pointers.
    372   SourceLocation MissingNilLoc
    373     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
    374   std::string NullValue;
    375   if (calleeType == CT_Method &&
    376       PP.getIdentifierInfo("nil")->hasMacroDefinition())
    377     NullValue = "nil";
    378   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
    379     NullValue = "NULL";
    380   else
    381     NullValue = "(void*) 0";
    382 
    383   if (MissingNilLoc.isInvalid())
    384     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
    385   else
    386     Diag(MissingNilLoc, diag::warn_missing_sentinel)
    387       << calleeType
    388       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
    389   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
    390 }
    391 
    392 SourceRange Sema::getExprRange(Expr *E) const {
    393   return E ? E->getSourceRange() : SourceRange();
    394 }
    395 
    396 //===----------------------------------------------------------------------===//
    397 //  Standard Promotions and Conversions
    398 //===----------------------------------------------------------------------===//
    399 
    400 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
    401 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
    402   // Handle any placeholder expressions which made it here.
    403   if (E->getType()->isPlaceholderType()) {
    404     ExprResult result = CheckPlaceholderExpr(E);
    405     if (result.isInvalid()) return ExprError();
    406     E = result.take();
    407   }
    408 
    409   QualType Ty = E->getType();
    410   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
    411 
    412   if (Ty->isFunctionType())
    413     E = ImpCastExprToType(E, Context.getPointerType(Ty),
    414                           CK_FunctionToPointerDecay).take();
    415   else if (Ty->isArrayType()) {
    416     // In C90 mode, arrays only promote to pointers if the array expression is
    417     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
    418     // type 'array of type' is converted to an expression that has type 'pointer
    419     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
    420     // that has type 'array of type' ...".  The relevant change is "an lvalue"
    421     // (C90) to "an expression" (C99).
    422     //
    423     // C++ 4.2p1:
    424     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
    425     // T" can be converted to an rvalue of type "pointer to T".
    426     //
    427     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
    428       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
    429                             CK_ArrayToPointerDecay).take();
    430   }
    431   return Owned(E);
    432 }
    433 
    434 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
    435   // Check to see if we are dereferencing a null pointer.  If so,
    436   // and if not volatile-qualified, this is undefined behavior that the
    437   // optimizer will delete, so warn about it.  People sometimes try to use this
    438   // to get a deterministic trap and are surprised by clang's behavior.  This
    439   // only handles the pattern "*null", which is a very syntactic check.
    440   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
    441     if (UO->getOpcode() == UO_Deref &&
    442         UO->getSubExpr()->IgnoreParenCasts()->
    443           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
    444         !UO->getType().isVolatileQualified()) {
    445     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    446                           S.PDiag(diag::warn_indirection_through_null)
    447                             << UO->getSubExpr()->getSourceRange());
    448     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    449                         S.PDiag(diag::note_indirection_through_null));
    450   }
    451 }
    452 
    453 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
    454   // Handle any placeholder expressions which made it here.
    455   if (E->getType()->isPlaceholderType()) {
    456     ExprResult result = CheckPlaceholderExpr(E);
    457     if (result.isInvalid()) return ExprError();
    458     E = result.take();
    459   }
    460 
    461   // C++ [conv.lval]p1:
    462   //   A glvalue of a non-function, non-array type T can be
    463   //   converted to a prvalue.
    464   if (!E->isGLValue()) return Owned(E);
    465 
    466   QualType T = E->getType();
    467   assert(!T.isNull() && "r-value conversion on typeless expression?");
    468 
    469   // We don't want to throw lvalue-to-rvalue casts on top of
    470   // expressions of certain types in C++.
    471   if (getLangOpts().CPlusPlus &&
    472       (E->getType() == Context.OverloadTy ||
    473        T->isDependentType() ||
    474        T->isRecordType()))
    475     return Owned(E);
    476 
    477   // The C standard is actually really unclear on this point, and
    478   // DR106 tells us what the result should be but not why.  It's
    479   // generally best to say that void types just doesn't undergo
    480   // lvalue-to-rvalue at all.  Note that expressions of unqualified
    481   // 'void' type are never l-values, but qualified void can be.
    482   if (T->isVoidType())
    483     return Owned(E);
    484 
    485   // OpenCL usually rejects direct accesses to values of 'half' type.
    486   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
    487       T->isHalfType()) {
    488     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
    489       << 0 << T;
    490     return ExprError();
    491   }
    492 
    493   CheckForNullPointerDereference(*this, E);
    494 
    495   // C++ [conv.lval]p1:
    496   //   [...] If T is a non-class type, the type of the prvalue is the
    497   //   cv-unqualified version of T. Otherwise, the type of the
    498   //   rvalue is T.
    499   //
    500   // C99 6.3.2.1p2:
    501   //   If the lvalue has qualified type, the value has the unqualified
    502   //   version of the type of the lvalue; otherwise, the value has the
    503   //   type of the lvalue.
    504   if (T.hasQualifiers())
    505     T = T.getUnqualifiedType();
    506 
    507   UpdateMarkingForLValueToRValue(E);
    508 
    509   // Loading a __weak object implicitly retains the value, so we need a cleanup to
    510   // balance that.
    511   if (getLangOpts().ObjCAutoRefCount &&
    512       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
    513     ExprNeedsCleanups = true;
    514 
    515   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
    516                                                   E, 0, VK_RValue));
    517 
    518   // C11 6.3.2.1p2:
    519   //   ... if the lvalue has atomic type, the value has the non-atomic version
    520   //   of the type of the lvalue ...
    521   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
    522     T = Atomic->getValueType().getUnqualifiedType();
    523     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
    524                                          Res.get(), 0, VK_RValue));
    525   }
    526 
    527   return Res;
    528 }
    529 
    530 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
    531   ExprResult Res = DefaultFunctionArrayConversion(E);
    532   if (Res.isInvalid())
    533     return ExprError();
    534   Res = DefaultLvalueConversion(Res.take());
    535   if (Res.isInvalid())
    536     return ExprError();
    537   return Res;
    538 }
    539 
    540 
    541 /// UsualUnaryConversions - Performs various conversions that are common to most
    542 /// operators (C99 6.3). The conversions of array and function types are
    543 /// sometimes suppressed. For example, the array->pointer conversion doesn't
    544 /// apply if the array is an argument to the sizeof or address (&) operators.
    545 /// In these instances, this routine should *not* be called.
    546 ExprResult Sema::UsualUnaryConversions(Expr *E) {
    547   // First, convert to an r-value.
    548   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
    549   if (Res.isInvalid())
    550     return ExprError();
    551   E = Res.take();
    552 
    553   QualType Ty = E->getType();
    554   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
    555 
    556   // Half FP have to be promoted to float unless it is natively supported
    557   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
    558     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
    559 
    560   // Try to perform integral promotions if the object has a theoretically
    561   // promotable type.
    562   if (Ty->isIntegralOrUnscopedEnumerationType()) {
    563     // C99 6.3.1.1p2:
    564     //
    565     //   The following may be used in an expression wherever an int or
    566     //   unsigned int may be used:
    567     //     - an object or expression with an integer type whose integer
    568     //       conversion rank is less than or equal to the rank of int
    569     //       and unsigned int.
    570     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
    571     //
    572     //   If an int can represent all values of the original type, the
    573     //   value is converted to an int; otherwise, it is converted to an
    574     //   unsigned int. These are called the integer promotions. All
    575     //   other types are unchanged by the integer promotions.
    576 
    577     QualType PTy = Context.isPromotableBitField(E);
    578     if (!PTy.isNull()) {
    579       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
    580       return Owned(E);
    581     }
    582     if (Ty->isPromotableIntegerType()) {
    583       QualType PT = Context.getPromotedIntegerType(Ty);
    584       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
    585       return Owned(E);
    586     }
    587   }
    588   return Owned(E);
    589 }
    590 
    591 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
    592 /// do not have a prototype. Arguments that have type float or __fp16
    593 /// are promoted to double. All other argument types are converted by
    594 /// UsualUnaryConversions().
    595 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
    596   QualType Ty = E->getType();
    597   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
    598 
    599   ExprResult Res = UsualUnaryConversions(E);
    600   if (Res.isInvalid())
    601     return ExprError();
    602   E = Res.take();
    603 
    604   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
    605   // double.
    606   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
    607   if (BTy && (BTy->getKind() == BuiltinType::Half ||
    608               BTy->getKind() == BuiltinType::Float))
    609     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
    610 
    611   // C++ performs lvalue-to-rvalue conversion as a default argument
    612   // promotion, even on class types, but note:
    613   //   C++11 [conv.lval]p2:
    614   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
    615   //     operand or a subexpression thereof the value contained in the
    616   //     referenced object is not accessed. Otherwise, if the glvalue
    617   //     has a class type, the conversion copy-initializes a temporary
    618   //     of type T from the glvalue and the result of the conversion
    619   //     is a prvalue for the temporary.
    620   // FIXME: add some way to gate this entire thing for correctness in
    621   // potentially potentially evaluated contexts.
    622   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
    623     ExprResult Temp = PerformCopyInitialization(
    624                        InitializedEntity::InitializeTemporary(E->getType()),
    625                                                 E->getExprLoc(),
    626                                                 Owned(E));
    627     if (Temp.isInvalid())
    628       return ExprError();
    629     E = Temp.get();
    630   }
    631 
    632   return Owned(E);
    633 }
    634 
    635 /// Determine the degree of POD-ness for an expression.
    636 /// Incomplete types are considered POD, since this check can be performed
    637 /// when we're in an unevaluated context.
    638 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
    639   if (Ty->isIncompleteType()) {
    640     if (Ty->isObjCObjectType())
    641       return VAK_Invalid;
    642     return VAK_Valid;
    643   }
    644 
    645   if (Ty.isCXX98PODType(Context))
    646     return VAK_Valid;
    647 
    648   // C++11 [expr.call]p7:
    649   //   Passing a potentially-evaluated argument of class type (Clause 9)
    650   //   having a non-trivial copy constructor, a non-trivial move constructor,
    651   //   or a non-trivial destructor, with no corresponding parameter,
    652   //   is conditionally-supported with implementation-defined semantics.
    653   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
    654     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
    655       if (!Record->hasNonTrivialCopyConstructor() &&
    656           !Record->hasNonTrivialMoveConstructor() &&
    657           !Record->hasNonTrivialDestructor())
    658         return VAK_ValidInCXX11;
    659 
    660   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
    661     return VAK_Valid;
    662   return VAK_Invalid;
    663 }
    664 
    665 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
    666   // Don't allow one to pass an Objective-C interface to a vararg.
    667   const QualType & Ty = E->getType();
    668 
    669   // Complain about passing non-POD types through varargs.
    670   switch (isValidVarArgType(Ty)) {
    671   case VAK_Valid:
    672     break;
    673   case VAK_ValidInCXX11:
    674     DiagRuntimeBehavior(E->getLocStart(), 0,
    675         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
    676         << E->getType() << CT);
    677     break;
    678   case VAK_Invalid: {
    679     if (Ty->isObjCObjectType())
    680       return DiagRuntimeBehavior(E->getLocStart(), 0,
    681                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
    682                             << Ty << CT);
    683 
    684     return DiagRuntimeBehavior(E->getLocStart(), 0,
    685                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
    686                    << getLangOpts().CPlusPlus11 << Ty << CT);
    687   }
    688   }
    689   // c++ rules are enforced elsewhere.
    690   return false;
    691 }
    692 
    693 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
    694 /// will create a trap if the resulting type is not a POD type.
    695 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
    696                                                   FunctionDecl *FDecl) {
    697   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
    698     // Strip the unbridged-cast placeholder expression off, if applicable.
    699     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
    700         (CT == VariadicMethod ||
    701          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
    702       E = stripARCUnbridgedCast(E);
    703 
    704     // Otherwise, do normal placeholder checking.
    705     } else {
    706       ExprResult ExprRes = CheckPlaceholderExpr(E);
    707       if (ExprRes.isInvalid())
    708         return ExprError();
    709       E = ExprRes.take();
    710     }
    711   }
    712 
    713   ExprResult ExprRes = DefaultArgumentPromotion(E);
    714   if (ExprRes.isInvalid())
    715     return ExprError();
    716   E = ExprRes.take();
    717 
    718   // Diagnostics regarding non-POD argument types are
    719   // emitted along with format string checking in Sema::CheckFunctionCall().
    720   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
    721     // Turn this into a trap.
    722     CXXScopeSpec SS;
    723     SourceLocation TemplateKWLoc;
    724     UnqualifiedId Name;
    725     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
    726                        E->getLocStart());
    727     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
    728                                           Name, true, false);
    729     if (TrapFn.isInvalid())
    730       return ExprError();
    731 
    732     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
    733                                     E->getLocStart(), MultiExprArg(),
    734                                     E->getLocEnd());
    735     if (Call.isInvalid())
    736       return ExprError();
    737 
    738     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
    739                                   Call.get(), E);
    740     if (Comma.isInvalid())
    741       return ExprError();
    742     return Comma.get();
    743   }
    744 
    745   if (!getLangOpts().CPlusPlus &&
    746       RequireCompleteType(E->getExprLoc(), E->getType(),
    747                           diag::err_call_incomplete_argument))
    748     return ExprError();
    749 
    750   return Owned(E);
    751 }
    752 
    753 /// \brief Converts an integer to complex float type.  Helper function of
    754 /// UsualArithmeticConversions()
    755 ///
    756 /// \return false if the integer expression is an integer type and is
    757 /// successfully converted to the complex type.
    758 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
    759                                                   ExprResult &ComplexExpr,
    760                                                   QualType IntTy,
    761                                                   QualType ComplexTy,
    762                                                   bool SkipCast) {
    763   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
    764   if (SkipCast) return false;
    765   if (IntTy->isIntegerType()) {
    766     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
    767     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
    768     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
    769                                   CK_FloatingRealToComplex);
    770   } else {
    771     assert(IntTy->isComplexIntegerType());
    772     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
    773                                   CK_IntegralComplexToFloatingComplex);
    774   }
    775   return false;
    776 }
    777 
    778 /// \brief Takes two complex float types and converts them to the same type.
    779 /// Helper function of UsualArithmeticConversions()
    780 static QualType
    781 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
    782                                             ExprResult &RHS, QualType LHSType,
    783                                             QualType RHSType,
    784                                             bool IsCompAssign) {
    785   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
    786 
    787   if (order < 0) {
    788     // _Complex float -> _Complex double
    789     if (!IsCompAssign)
    790       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
    791     return RHSType;
    792   }
    793   if (order > 0)
    794     // _Complex float -> _Complex double
    795     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
    796   return LHSType;
    797 }
    798 
    799 /// \brief Converts otherExpr to complex float and promotes complexExpr if
    800 /// necessary.  Helper function of UsualArithmeticConversions()
    801 static QualType handleOtherComplexFloatConversion(Sema &S,
    802                                                   ExprResult &ComplexExpr,
    803                                                   ExprResult &OtherExpr,
    804                                                   QualType ComplexTy,
    805                                                   QualType OtherTy,
    806                                                   bool ConvertComplexExpr,
    807                                                   bool ConvertOtherExpr) {
    808   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
    809 
    810   // If just the complexExpr is complex, the otherExpr needs to be converted,
    811   // and the complexExpr might need to be promoted.
    812   if (order > 0) { // complexExpr is wider
    813     // float -> _Complex double
    814     if (ConvertOtherExpr) {
    815       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
    816       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
    817       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
    818                                       CK_FloatingRealToComplex);
    819     }
    820     return ComplexTy;
    821   }
    822 
    823   // otherTy is at least as wide.  Find its corresponding complex type.
    824   QualType result = (order == 0 ? ComplexTy :
    825                                   S.Context.getComplexType(OtherTy));
    826 
    827   // double -> _Complex double
    828   if (ConvertOtherExpr)
    829     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
    830                                     CK_FloatingRealToComplex);
    831 
    832   // _Complex float -> _Complex double
    833   if (ConvertComplexExpr && order < 0)
    834     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
    835                                       CK_FloatingComplexCast);
    836 
    837   return result;
    838 }
    839 
    840 /// \brief Handle arithmetic conversion with complex types.  Helper function of
    841 /// UsualArithmeticConversions()
    842 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
    843                                              ExprResult &RHS, QualType LHSType,
    844                                              QualType RHSType,
    845                                              bool IsCompAssign) {
    846   // if we have an integer operand, the result is the complex type.
    847   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
    848                                              /*skipCast*/false))
    849     return LHSType;
    850   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
    851                                              /*skipCast*/IsCompAssign))
    852     return RHSType;
    853 
    854   // This handles complex/complex, complex/float, or float/complex.
    855   // When both operands are complex, the shorter operand is converted to the
    856   // type of the longer, and that is the type of the result. This corresponds
    857   // to what is done when combining two real floating-point operands.
    858   // The fun begins when size promotion occur across type domains.
    859   // From H&S 6.3.4: When one operand is complex and the other is a real
    860   // floating-point type, the less precise type is converted, within it's
    861   // real or complex domain, to the precision of the other type. For example,
    862   // when combining a "long double" with a "double _Complex", the
    863   // "double _Complex" is promoted to "long double _Complex".
    864 
    865   bool LHSComplexFloat = LHSType->isComplexType();
    866   bool RHSComplexFloat = RHSType->isComplexType();
    867 
    868   // If both are complex, just cast to the more precise type.
    869   if (LHSComplexFloat && RHSComplexFloat)
    870     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
    871                                                        LHSType, RHSType,
    872                                                        IsCompAssign);
    873 
    874   // If only one operand is complex, promote it if necessary and convert the
    875   // other operand to complex.
    876   if (LHSComplexFloat)
    877     return handleOtherComplexFloatConversion(
    878         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
    879         /*convertOtherExpr*/ true);
    880 
    881   assert(RHSComplexFloat);
    882   return handleOtherComplexFloatConversion(
    883       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
    884       /*convertOtherExpr*/ !IsCompAssign);
    885 }
    886 
    887 /// \brief Hande arithmetic conversion from integer to float.  Helper function
    888 /// of UsualArithmeticConversions()
    889 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
    890                                            ExprResult &IntExpr,
    891                                            QualType FloatTy, QualType IntTy,
    892                                            bool ConvertFloat, bool ConvertInt) {
    893   if (IntTy->isIntegerType()) {
    894     if (ConvertInt)
    895       // Convert intExpr to the lhs floating point type.
    896       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
    897                                     CK_IntegralToFloating);
    898     return FloatTy;
    899   }
    900 
    901   // Convert both sides to the appropriate complex float.
    902   assert(IntTy->isComplexIntegerType());
    903   QualType result = S.Context.getComplexType(FloatTy);
    904 
    905   // _Complex int -> _Complex float
    906   if (ConvertInt)
    907     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
    908                                   CK_IntegralComplexToFloatingComplex);
    909 
    910   // float -> _Complex float
    911   if (ConvertFloat)
    912     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
    913                                     CK_FloatingRealToComplex);
    914 
    915   return result;
    916 }
    917 
    918 /// \brief Handle arithmethic conversion with floating point types.  Helper
    919 /// function of UsualArithmeticConversions()
    920 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
    921                                       ExprResult &RHS, QualType LHSType,
    922                                       QualType RHSType, bool IsCompAssign) {
    923   bool LHSFloat = LHSType->isRealFloatingType();
    924   bool RHSFloat = RHSType->isRealFloatingType();
    925 
    926   // If we have two real floating types, convert the smaller operand
    927   // to the bigger result.
    928   if (LHSFloat && RHSFloat) {
    929     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
    930     if (order > 0) {
    931       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
    932       return LHSType;
    933     }
    934 
    935     assert(order < 0 && "illegal float comparison");
    936     if (!IsCompAssign)
    937       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
    938     return RHSType;
    939   }
    940 
    941   if (LHSFloat)
    942     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
    943                                       /*convertFloat=*/!IsCompAssign,
    944                                       /*convertInt=*/ true);
    945   assert(RHSFloat);
    946   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
    947                                     /*convertInt=*/ true,
    948                                     /*convertFloat=*/!IsCompAssign);
    949 }
    950 
    951 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
    952 
    953 namespace {
    954 /// These helper callbacks are placed in an anonymous namespace to
    955 /// permit their use as function template parameters.
    956 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
    957   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
    958 }
    959 
    960 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
    961   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
    962                              CK_IntegralComplexCast);
    963 }
    964 }
    965 
    966 /// \brief Handle integer arithmetic conversions.  Helper function of
    967 /// UsualArithmeticConversions()
    968 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
    969 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
    970                                         ExprResult &RHS, QualType LHSType,
    971                                         QualType RHSType, bool IsCompAssign) {
    972   // The rules for this case are in C99 6.3.1.8
    973   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
    974   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
    975   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
    976   if (LHSSigned == RHSSigned) {
    977     // Same signedness; use the higher-ranked type
    978     if (order >= 0) {
    979       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
    980       return LHSType;
    981     } else if (!IsCompAssign)
    982       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
    983     return RHSType;
    984   } else if (order != (LHSSigned ? 1 : -1)) {
    985     // The unsigned type has greater than or equal rank to the
    986     // signed type, so use the unsigned type
    987     if (RHSSigned) {
    988       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
    989       return LHSType;
    990     } else if (!IsCompAssign)
    991       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
    992     return RHSType;
    993   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
    994     // The two types are different widths; if we are here, that
    995     // means the signed type is larger than the unsigned type, so
    996     // use the signed type.
    997     if (LHSSigned) {
    998       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
    999       return LHSType;
   1000     } else if (!IsCompAssign)
   1001       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
   1002     return RHSType;
   1003   } else {
   1004     // The signed type is higher-ranked than the unsigned type,
   1005     // but isn't actually any bigger (like unsigned int and long
   1006     // on most 32-bit systems).  Use the unsigned type corresponding
   1007     // to the signed type.
   1008     QualType result =
   1009       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
   1010     RHS = (*doRHSCast)(S, RHS.take(), result);
   1011     if (!IsCompAssign)
   1012       LHS = (*doLHSCast)(S, LHS.take(), result);
   1013     return result;
   1014   }
   1015 }
   1016 
   1017 /// \brief Handle conversions with GCC complex int extension.  Helper function
   1018 /// of UsualArithmeticConversions()
   1019 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
   1020                                            ExprResult &RHS, QualType LHSType,
   1021                                            QualType RHSType,
   1022                                            bool IsCompAssign) {
   1023   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
   1024   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
   1025 
   1026   if (LHSComplexInt && RHSComplexInt) {
   1027     QualType LHSEltType = LHSComplexInt->getElementType();
   1028     QualType RHSEltType = RHSComplexInt->getElementType();
   1029     QualType ScalarType =
   1030       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
   1031         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
   1032 
   1033     return S.Context.getComplexType(ScalarType);
   1034   }
   1035 
   1036   if (LHSComplexInt) {
   1037     QualType LHSEltType = LHSComplexInt->getElementType();
   1038     QualType ScalarType =
   1039       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
   1040         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
   1041     QualType ComplexType = S.Context.getComplexType(ScalarType);
   1042     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
   1043                               CK_IntegralRealToComplex);
   1044 
   1045     return ComplexType;
   1046   }
   1047 
   1048   assert(RHSComplexInt);
   1049 
   1050   QualType RHSEltType = RHSComplexInt->getElementType();
   1051   QualType ScalarType =
   1052     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
   1053       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
   1054   QualType ComplexType = S.Context.getComplexType(ScalarType);
   1055 
   1056   if (!IsCompAssign)
   1057     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
   1058                               CK_IntegralRealToComplex);
   1059   return ComplexType;
   1060 }
   1061 
   1062 /// UsualArithmeticConversions - Performs various conversions that are common to
   1063 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
   1064 /// routine returns the first non-arithmetic type found. The client is
   1065 /// responsible for emitting appropriate error diagnostics.
   1066 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
   1067                                           bool IsCompAssign) {
   1068   if (!IsCompAssign) {
   1069     LHS = UsualUnaryConversions(LHS.take());
   1070     if (LHS.isInvalid())
   1071       return QualType();
   1072   }
   1073 
   1074   RHS = UsualUnaryConversions(RHS.take());
   1075   if (RHS.isInvalid())
   1076     return QualType();
   1077 
   1078   // For conversion purposes, we ignore any qualifiers.
   1079   // For example, "const float" and "float" are equivalent.
   1080   QualType LHSType =
   1081     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
   1082   QualType RHSType =
   1083     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
   1084 
   1085   // For conversion purposes, we ignore any atomic qualifier on the LHS.
   1086   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
   1087     LHSType = AtomicLHS->getValueType();
   1088 
   1089   // If both types are identical, no conversion is needed.
   1090   if (LHSType == RHSType)
   1091     return LHSType;
   1092 
   1093   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
   1094   // The caller can deal with this (e.g. pointer + int).
   1095   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
   1096     return QualType();
   1097 
   1098   // Apply unary and bitfield promotions to the LHS's type.
   1099   QualType LHSUnpromotedType = LHSType;
   1100   if (LHSType->isPromotableIntegerType())
   1101     LHSType = Context.getPromotedIntegerType(LHSType);
   1102   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
   1103   if (!LHSBitfieldPromoteTy.isNull())
   1104     LHSType = LHSBitfieldPromoteTy;
   1105   if (LHSType != LHSUnpromotedType && !IsCompAssign)
   1106     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
   1107 
   1108   // If both types are identical, no conversion is needed.
   1109   if (LHSType == RHSType)
   1110     return LHSType;
   1111 
   1112   // At this point, we have two different arithmetic types.
   1113 
   1114   // Handle complex types first (C99 6.3.1.8p1).
   1115   if (LHSType->isComplexType() || RHSType->isComplexType())
   1116     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1117                                         IsCompAssign);
   1118 
   1119   // Now handle "real" floating types (i.e. float, double, long double).
   1120   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
   1121     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1122                                  IsCompAssign);
   1123 
   1124   // Handle GCC complex int extension.
   1125   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
   1126     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
   1127                                       IsCompAssign);
   1128 
   1129   // Finally, we have two differing integer types.
   1130   return handleIntegerConversion<doIntegralCast, doIntegralCast>
   1131            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
   1132 }
   1133 
   1134 
   1135 //===----------------------------------------------------------------------===//
   1136 //  Semantic Analysis for various Expression Types
   1137 //===----------------------------------------------------------------------===//
   1138 
   1139 
   1140 ExprResult
   1141 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
   1142                                 SourceLocation DefaultLoc,
   1143                                 SourceLocation RParenLoc,
   1144                                 Expr *ControllingExpr,
   1145                                 MultiTypeArg ArgTypes,
   1146                                 MultiExprArg ArgExprs) {
   1147   unsigned NumAssocs = ArgTypes.size();
   1148   assert(NumAssocs == ArgExprs.size());
   1149 
   1150   ParsedType *ParsedTypes = ArgTypes.data();
   1151   Expr **Exprs = ArgExprs.data();
   1152 
   1153   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
   1154   for (unsigned i = 0; i < NumAssocs; ++i) {
   1155     if (ParsedTypes[i])
   1156       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
   1157     else
   1158       Types[i] = 0;
   1159   }
   1160 
   1161   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1162                                              ControllingExpr, Types, Exprs,
   1163                                              NumAssocs);
   1164   delete [] Types;
   1165   return ER;
   1166 }
   1167 
   1168 ExprResult
   1169 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
   1170                                  SourceLocation DefaultLoc,
   1171                                  SourceLocation RParenLoc,
   1172                                  Expr *ControllingExpr,
   1173                                  TypeSourceInfo **Types,
   1174                                  Expr **Exprs,
   1175                                  unsigned NumAssocs) {
   1176   if (ControllingExpr->getType()->isPlaceholderType()) {
   1177     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
   1178     if (result.isInvalid()) return ExprError();
   1179     ControllingExpr = result.take();
   1180   }
   1181 
   1182   bool TypeErrorFound = false,
   1183        IsResultDependent = ControllingExpr->isTypeDependent(),
   1184        ContainsUnexpandedParameterPack
   1185          = ControllingExpr->containsUnexpandedParameterPack();
   1186 
   1187   for (unsigned i = 0; i < NumAssocs; ++i) {
   1188     if (Exprs[i]->containsUnexpandedParameterPack())
   1189       ContainsUnexpandedParameterPack = true;
   1190 
   1191     if (Types[i]) {
   1192       if (Types[i]->getType()->containsUnexpandedParameterPack())
   1193         ContainsUnexpandedParameterPack = true;
   1194 
   1195       if (Types[i]->getType()->isDependentType()) {
   1196         IsResultDependent = true;
   1197       } else {
   1198         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
   1199         // complete object type other than a variably modified type."
   1200         unsigned D = 0;
   1201         if (Types[i]->getType()->isIncompleteType())
   1202           D = diag::err_assoc_type_incomplete;
   1203         else if (!Types[i]->getType()->isObjectType())
   1204           D = diag::err_assoc_type_nonobject;
   1205         else if (Types[i]->getType()->isVariablyModifiedType())
   1206           D = diag::err_assoc_type_variably_modified;
   1207 
   1208         if (D != 0) {
   1209           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
   1210             << Types[i]->getTypeLoc().getSourceRange()
   1211             << Types[i]->getType();
   1212           TypeErrorFound = true;
   1213         }
   1214 
   1215         // C11 6.5.1.1p2 "No two generic associations in the same generic
   1216         // selection shall specify compatible types."
   1217         for (unsigned j = i+1; j < NumAssocs; ++j)
   1218           if (Types[j] && !Types[j]->getType()->isDependentType() &&
   1219               Context.typesAreCompatible(Types[i]->getType(),
   1220                                          Types[j]->getType())) {
   1221             Diag(Types[j]->getTypeLoc().getBeginLoc(),
   1222                  diag::err_assoc_compatible_types)
   1223               << Types[j]->getTypeLoc().getSourceRange()
   1224               << Types[j]->getType()
   1225               << Types[i]->getType();
   1226             Diag(Types[i]->getTypeLoc().getBeginLoc(),
   1227                  diag::note_compat_assoc)
   1228               << Types[i]->getTypeLoc().getSourceRange()
   1229               << Types[i]->getType();
   1230             TypeErrorFound = true;
   1231           }
   1232       }
   1233     }
   1234   }
   1235   if (TypeErrorFound)
   1236     return ExprError();
   1237 
   1238   // If we determined that the generic selection is result-dependent, don't
   1239   // try to compute the result expression.
   1240   if (IsResultDependent)
   1241     return Owned(new (Context) GenericSelectionExpr(
   1242                    Context, KeyLoc, ControllingExpr,
   1243                    llvm::makeArrayRef(Types, NumAssocs),
   1244                    llvm::makeArrayRef(Exprs, NumAssocs),
   1245                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
   1246 
   1247   SmallVector<unsigned, 1> CompatIndices;
   1248   unsigned DefaultIndex = -1U;
   1249   for (unsigned i = 0; i < NumAssocs; ++i) {
   1250     if (!Types[i])
   1251       DefaultIndex = i;
   1252     else if (Context.typesAreCompatible(ControllingExpr->getType(),
   1253                                         Types[i]->getType()))
   1254       CompatIndices.push_back(i);
   1255   }
   1256 
   1257   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
   1258   // type compatible with at most one of the types named in its generic
   1259   // association list."
   1260   if (CompatIndices.size() > 1) {
   1261     // We strip parens here because the controlling expression is typically
   1262     // parenthesized in macro definitions.
   1263     ControllingExpr = ControllingExpr->IgnoreParens();
   1264     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
   1265       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
   1266       << (unsigned) CompatIndices.size();
   1267     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
   1268          E = CompatIndices.end(); I != E; ++I) {
   1269       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
   1270            diag::note_compat_assoc)
   1271         << Types[*I]->getTypeLoc().getSourceRange()
   1272         << Types[*I]->getType();
   1273     }
   1274     return ExprError();
   1275   }
   1276 
   1277   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
   1278   // its controlling expression shall have type compatible with exactly one of
   1279   // the types named in its generic association list."
   1280   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
   1281     // We strip parens here because the controlling expression is typically
   1282     // parenthesized in macro definitions.
   1283     ControllingExpr = ControllingExpr->IgnoreParens();
   1284     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
   1285       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
   1286     return ExprError();
   1287   }
   1288 
   1289   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
   1290   // type name that is compatible with the type of the controlling expression,
   1291   // then the result expression of the generic selection is the expression
   1292   // in that generic association. Otherwise, the result expression of the
   1293   // generic selection is the expression in the default generic association."
   1294   unsigned ResultIndex =
   1295     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
   1296 
   1297   return Owned(new (Context) GenericSelectionExpr(
   1298                  Context, KeyLoc, ControllingExpr,
   1299                  llvm::makeArrayRef(Types, NumAssocs),
   1300                  llvm::makeArrayRef(Exprs, NumAssocs),
   1301                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
   1302                  ResultIndex));
   1303 }
   1304 
   1305 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
   1306 /// location of the token and the offset of the ud-suffix within it.
   1307 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
   1308                                      unsigned Offset) {
   1309   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
   1310                                         S.getLangOpts());
   1311 }
   1312 
   1313 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
   1314 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
   1315 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
   1316                                                  IdentifierInfo *UDSuffix,
   1317                                                  SourceLocation UDSuffixLoc,
   1318                                                  ArrayRef<Expr*> Args,
   1319                                                  SourceLocation LitEndLoc) {
   1320   assert(Args.size() <= 2 && "too many arguments for literal operator");
   1321 
   1322   QualType ArgTy[2];
   1323   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
   1324     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
   1325     if (ArgTy[ArgIdx]->isArrayType())
   1326       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
   1327   }
   1328 
   1329   DeclarationName OpName =
   1330     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   1331   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   1332   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   1333 
   1334   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
   1335   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
   1336                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
   1337     return ExprError();
   1338 
   1339   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
   1340 }
   1341 
   1342 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   1343 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
   1344 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
   1345 /// multiple tokens.  However, the common case is that StringToks points to one
   1346 /// string.
   1347 ///
   1348 ExprResult
   1349 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
   1350                          Scope *UDLScope) {
   1351   assert(NumStringToks && "Must have at least one string!");
   1352 
   1353   StringLiteralParser Literal(StringToks, NumStringToks, PP);
   1354   if (Literal.hadError)
   1355     return ExprError();
   1356 
   1357   SmallVector<SourceLocation, 4> StringTokLocs;
   1358   for (unsigned i = 0; i != NumStringToks; ++i)
   1359     StringTokLocs.push_back(StringToks[i].getLocation());
   1360 
   1361   QualType StrTy = Context.CharTy;
   1362   if (Literal.isWide())
   1363     StrTy = Context.getWCharType();
   1364   else if (Literal.isUTF16())
   1365     StrTy = Context.Char16Ty;
   1366   else if (Literal.isUTF32())
   1367     StrTy = Context.Char32Ty;
   1368   else if (Literal.isPascal())
   1369     StrTy = Context.UnsignedCharTy;
   1370 
   1371   StringLiteral::StringKind Kind = StringLiteral::Ascii;
   1372   if (Literal.isWide())
   1373     Kind = StringLiteral::Wide;
   1374   else if (Literal.isUTF8())
   1375     Kind = StringLiteral::UTF8;
   1376   else if (Literal.isUTF16())
   1377     Kind = StringLiteral::UTF16;
   1378   else if (Literal.isUTF32())
   1379     Kind = StringLiteral::UTF32;
   1380 
   1381   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
   1382   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
   1383     StrTy.addConst();
   1384 
   1385   // Get an array type for the string, according to C99 6.4.5.  This includes
   1386   // the nul terminator character as well as the string length for pascal
   1387   // strings.
   1388   StrTy = Context.getConstantArrayType(StrTy,
   1389                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
   1390                                        ArrayType::Normal, 0);
   1391 
   1392   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
   1393   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
   1394                                              Kind, Literal.Pascal, StrTy,
   1395                                              &StringTokLocs[0],
   1396                                              StringTokLocs.size());
   1397   if (Literal.getUDSuffix().empty())
   1398     return Owned(Lit);
   1399 
   1400   // We're building a user-defined literal.
   1401   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   1402   SourceLocation UDSuffixLoc =
   1403     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
   1404                    Literal.getUDSuffixOffset());
   1405 
   1406   // Make sure we're allowed user-defined literals here.
   1407   if (!UDLScope)
   1408     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
   1409 
   1410   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
   1411   //   operator "" X (str, len)
   1412   QualType SizeType = Context.getSizeType();
   1413   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
   1414   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
   1415                                                   StringTokLocs[0]);
   1416   Expr *Args[] = { Lit, LenArg };
   1417   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
   1418                                         Args, StringTokLocs.back());
   1419 }
   1420 
   1421 ExprResult
   1422 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1423                        SourceLocation Loc,
   1424                        const CXXScopeSpec *SS) {
   1425   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
   1426   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
   1427 }
   1428 
   1429 /// BuildDeclRefExpr - Build an expression that references a
   1430 /// declaration that does not require a closure capture.
   1431 ExprResult
   1432 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1433                        const DeclarationNameInfo &NameInfo,
   1434                        const CXXScopeSpec *SS) {
   1435   if (getLangOpts().CUDA)
   1436     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
   1437       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
   1438         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
   1439                            CalleeTarget = IdentifyCUDATarget(Callee);
   1440         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
   1441           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
   1442             << CalleeTarget << D->getIdentifier() << CallerTarget;
   1443           Diag(D->getLocation(), diag::note_previous_decl)
   1444             << D->getIdentifier();
   1445           return ExprError();
   1446         }
   1447       }
   1448 
   1449   bool refersToEnclosingScope =
   1450     (CurContext != D->getDeclContext() &&
   1451      D->getDeclContext()->isFunctionOrMethod());
   1452 
   1453   DeclRefExpr *E = DeclRefExpr::Create(Context,
   1454                                        SS ? SS->getWithLocInContext(Context)
   1455                                               : NestedNameSpecifierLoc(),
   1456                                        SourceLocation(),
   1457                                        D, refersToEnclosingScope,
   1458                                        NameInfo, Ty, VK);
   1459 
   1460   MarkDeclRefReferenced(E);
   1461 
   1462   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
   1463       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
   1464     DiagnosticsEngine::Level Level =
   1465       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
   1466                                E->getLocStart());
   1467     if (Level != DiagnosticsEngine::Ignored)
   1468       getCurFunction()->recordUseOfWeak(E);
   1469   }
   1470 
   1471   // Just in case we're building an illegal pointer-to-member.
   1472   FieldDecl *FD = dyn_cast<FieldDecl>(D);
   1473   if (FD && FD->isBitField())
   1474     E->setObjectKind(OK_BitField);
   1475 
   1476   return Owned(E);
   1477 }
   1478 
   1479 /// Decomposes the given name into a DeclarationNameInfo, its location, and
   1480 /// possibly a list of template arguments.
   1481 ///
   1482 /// If this produces template arguments, it is permitted to call
   1483 /// DecomposeTemplateName.
   1484 ///
   1485 /// This actually loses a lot of source location information for
   1486 /// non-standard name kinds; we should consider preserving that in
   1487 /// some way.
   1488 void
   1489 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
   1490                              TemplateArgumentListInfo &Buffer,
   1491                              DeclarationNameInfo &NameInfo,
   1492                              const TemplateArgumentListInfo *&TemplateArgs) {
   1493   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
   1494     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
   1495     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
   1496 
   1497     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
   1498                                        Id.TemplateId->NumArgs);
   1499     translateTemplateArguments(TemplateArgsPtr, Buffer);
   1500 
   1501     TemplateName TName = Id.TemplateId->Template.get();
   1502     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
   1503     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
   1504     TemplateArgs = &Buffer;
   1505   } else {
   1506     NameInfo = GetNameFromUnqualifiedId(Id);
   1507     TemplateArgs = 0;
   1508   }
   1509 }
   1510 
   1511 /// Diagnose an empty lookup.
   1512 ///
   1513 /// \return false if new lookup candidates were found
   1514 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
   1515                                CorrectionCandidateCallback &CCC,
   1516                                TemplateArgumentListInfo *ExplicitTemplateArgs,
   1517                                llvm::ArrayRef<Expr *> Args) {
   1518   DeclarationName Name = R.getLookupName();
   1519 
   1520   unsigned diagnostic = diag::err_undeclared_var_use;
   1521   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
   1522   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
   1523       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
   1524       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
   1525     diagnostic = diag::err_undeclared_use;
   1526     diagnostic_suggest = diag::err_undeclared_use_suggest;
   1527   }
   1528 
   1529   // If the original lookup was an unqualified lookup, fake an
   1530   // unqualified lookup.  This is useful when (for example) the
   1531   // original lookup would not have found something because it was a
   1532   // dependent name.
   1533   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
   1534     ? CurContext : 0;
   1535   while (DC) {
   1536     if (isa<CXXRecordDecl>(DC)) {
   1537       LookupQualifiedName(R, DC);
   1538 
   1539       if (!R.empty()) {
   1540         // Don't give errors about ambiguities in this lookup.
   1541         R.suppressDiagnostics();
   1542 
   1543         // During a default argument instantiation the CurContext points
   1544         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
   1545         // function parameter list, hence add an explicit check.
   1546         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
   1547                               ActiveTemplateInstantiations.back().Kind ==
   1548             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
   1549         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
   1550         bool isInstance = CurMethod &&
   1551                           CurMethod->isInstance() &&
   1552                           DC == CurMethod->getParent() && !isDefaultArgument;
   1553 
   1554 
   1555         // Give a code modification hint to insert 'this->'.
   1556         // TODO: fixit for inserting 'Base<T>::' in the other cases.
   1557         // Actually quite difficult!
   1558         if (getLangOpts().MicrosoftMode)
   1559           diagnostic = diag::warn_found_via_dependent_bases_lookup;
   1560         if (isInstance) {
   1561           Diag(R.getNameLoc(), diagnostic) << Name
   1562             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
   1563           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
   1564               CallsUndergoingInstantiation.back()->getCallee());
   1565 
   1566 
   1567           CXXMethodDecl *DepMethod;
   1568           if (CurMethod->getTemplatedKind() ==
   1569               FunctionDecl::TK_FunctionTemplateSpecialization)
   1570             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
   1571                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
   1572           else
   1573             DepMethod = cast<CXXMethodDecl>(
   1574                 CurMethod->getInstantiatedFromMemberFunction());
   1575           assert(DepMethod && "No template pattern found");
   1576 
   1577           QualType DepThisType = DepMethod->getThisType(Context);
   1578           CheckCXXThisCapture(R.getNameLoc());
   1579           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
   1580                                      R.getNameLoc(), DepThisType, false);
   1581           TemplateArgumentListInfo TList;
   1582           if (ULE->hasExplicitTemplateArgs())
   1583             ULE->copyTemplateArgumentsInto(TList);
   1584 
   1585           CXXScopeSpec SS;
   1586           SS.Adopt(ULE->getQualifierLoc());
   1587           CXXDependentScopeMemberExpr *DepExpr =
   1588               CXXDependentScopeMemberExpr::Create(
   1589                   Context, DepThis, DepThisType, true, SourceLocation(),
   1590                   SS.getWithLocInContext(Context),
   1591                   ULE->getTemplateKeywordLoc(), 0,
   1592                   R.getLookupNameInfo(),
   1593                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
   1594           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
   1595         } else {
   1596           Diag(R.getNameLoc(), diagnostic) << Name;
   1597         }
   1598 
   1599         // Do we really want to note all of these?
   1600         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
   1601           Diag((*I)->getLocation(), diag::note_dependent_var_use);
   1602 
   1603         // Return true if we are inside a default argument instantiation
   1604         // and the found name refers to an instance member function, otherwise
   1605         // the function calling DiagnoseEmptyLookup will try to create an
   1606         // implicit member call and this is wrong for default argument.
   1607         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
   1608           Diag(R.getNameLoc(), diag::err_member_call_without_object);
   1609           return true;
   1610         }
   1611 
   1612         // Tell the callee to try to recover.
   1613         return false;
   1614       }
   1615 
   1616       R.clear();
   1617     }
   1618 
   1619     // In Microsoft mode, if we are performing lookup from within a friend
   1620     // function definition declared at class scope then we must set
   1621     // DC to the lexical parent to be able to search into the parent
   1622     // class.
   1623     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
   1624         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
   1625         DC->getLexicalParent()->isRecord())
   1626       DC = DC->getLexicalParent();
   1627     else
   1628       DC = DC->getParent();
   1629   }
   1630 
   1631   // We didn't find anything, so try to correct for a typo.
   1632   TypoCorrection Corrected;
   1633   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
   1634                                     S, &SS, CCC))) {
   1635     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
   1636     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
   1637     R.setLookupName(Corrected.getCorrection());
   1638 
   1639     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
   1640       if (Corrected.isOverloaded()) {
   1641         OverloadCandidateSet OCS(R.getNameLoc());
   1642         OverloadCandidateSet::iterator Best;
   1643         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
   1644                                         CDEnd = Corrected.end();
   1645              CD != CDEnd; ++CD) {
   1646           if (FunctionTemplateDecl *FTD =
   1647                    dyn_cast<FunctionTemplateDecl>(*CD))
   1648             AddTemplateOverloadCandidate(
   1649                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
   1650                 Args, OCS);
   1651           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
   1652             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
   1653               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
   1654                                    Args, OCS);
   1655         }
   1656         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
   1657           case OR_Success:
   1658             ND = Best->Function;
   1659             break;
   1660           default:
   1661             break;
   1662         }
   1663       }
   1664       R.addDecl(ND);
   1665       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
   1666         if (SS.isEmpty())
   1667           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
   1668             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
   1669         else
   1670           Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1671             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1672             << SS.getRange()
   1673             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
   1674                                             CorrectedStr);
   1675 
   1676         unsigned diag = isa<ImplicitParamDecl>(ND)
   1677           ? diag::note_implicit_param_decl
   1678           : diag::note_previous_decl;
   1679 
   1680         Diag(ND->getLocation(), diag)
   1681           << CorrectedQuotedStr;
   1682 
   1683         // Tell the callee to try to recover.
   1684         return false;
   1685       }
   1686 
   1687       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
   1688         // FIXME: If we ended up with a typo for a type name or
   1689         // Objective-C class name, we're in trouble because the parser
   1690         // is in the wrong place to recover. Suggest the typo
   1691         // correction, but don't make it a fix-it since we're not going
   1692         // to recover well anyway.
   1693         if (SS.isEmpty())
   1694           Diag(R.getNameLoc(), diagnostic_suggest)
   1695             << Name << CorrectedQuotedStr;
   1696         else
   1697           Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1698             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1699             << SS.getRange();
   1700 
   1701         // Don't try to recover; it won't work.
   1702         return true;
   1703       }
   1704     } else {
   1705       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
   1706       // because we aren't able to recover.
   1707       if (SS.isEmpty())
   1708         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
   1709       else
   1710         Diag(R.getNameLoc(), diag::err_no_member_suggest)
   1711         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
   1712         << SS.getRange();
   1713       return true;
   1714     }
   1715   }
   1716   R.clear();
   1717 
   1718   // Emit a special diagnostic for failed member lookups.
   1719   // FIXME: computing the declaration context might fail here (?)
   1720   if (!SS.isEmpty()) {
   1721     Diag(R.getNameLoc(), diag::err_no_member)
   1722       << Name << computeDeclContext(SS, false)
   1723       << SS.getRange();
   1724     return true;
   1725   }
   1726 
   1727   // Give up, we can't recover.
   1728   Diag(R.getNameLoc(), diagnostic) << Name;
   1729   return true;
   1730 }
   1731 
   1732 ExprResult Sema::ActOnIdExpression(Scope *S,
   1733                                    CXXScopeSpec &SS,
   1734                                    SourceLocation TemplateKWLoc,
   1735                                    UnqualifiedId &Id,
   1736                                    bool HasTrailingLParen,
   1737                                    bool IsAddressOfOperand,
   1738                                    CorrectionCandidateCallback *CCC) {
   1739   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
   1740          "cannot be direct & operand and have a trailing lparen");
   1741 
   1742   if (SS.isInvalid())
   1743     return ExprError();
   1744 
   1745   TemplateArgumentListInfo TemplateArgsBuffer;
   1746 
   1747   // Decompose the UnqualifiedId into the following data.
   1748   DeclarationNameInfo NameInfo;
   1749   const TemplateArgumentListInfo *TemplateArgs;
   1750   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
   1751 
   1752   DeclarationName Name = NameInfo.getName();
   1753   IdentifierInfo *II = Name.getAsIdentifierInfo();
   1754   SourceLocation NameLoc = NameInfo.getLoc();
   1755 
   1756   // C++ [temp.dep.expr]p3:
   1757   //   An id-expression is type-dependent if it contains:
   1758   //     -- an identifier that was declared with a dependent type,
   1759   //        (note: handled after lookup)
   1760   //     -- a template-id that is dependent,
   1761   //        (note: handled in BuildTemplateIdExpr)
   1762   //     -- a conversion-function-id that specifies a dependent type,
   1763   //     -- a nested-name-specifier that contains a class-name that
   1764   //        names a dependent type.
   1765   // Determine whether this is a member of an unknown specialization;
   1766   // we need to handle these differently.
   1767   bool DependentID = false;
   1768   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
   1769       Name.getCXXNameType()->isDependentType()) {
   1770     DependentID = true;
   1771   } else if (SS.isSet()) {
   1772     if (DeclContext *DC = computeDeclContext(SS, false)) {
   1773       if (RequireCompleteDeclContext(SS, DC))
   1774         return ExprError();
   1775     } else {
   1776       DependentID = true;
   1777     }
   1778   }
   1779 
   1780   if (DependentID)
   1781     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1782                                       IsAddressOfOperand, TemplateArgs);
   1783 
   1784   // Perform the required lookup.
   1785   LookupResult R(*this, NameInfo,
   1786                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
   1787                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
   1788   if (TemplateArgs) {
   1789     // Lookup the template name again to correctly establish the context in
   1790     // which it was found. This is really unfortunate as we already did the
   1791     // lookup to determine that it was a template name in the first place. If
   1792     // this becomes a performance hit, we can work harder to preserve those
   1793     // results until we get here but it's likely not worth it.
   1794     bool MemberOfUnknownSpecialization;
   1795     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
   1796                        MemberOfUnknownSpecialization);
   1797 
   1798     if (MemberOfUnknownSpecialization ||
   1799         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
   1800       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1801                                         IsAddressOfOperand, TemplateArgs);
   1802   } else {
   1803     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
   1804     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
   1805 
   1806     // If the result might be in a dependent base class, this is a dependent
   1807     // id-expression.
   1808     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
   1809       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1810                                         IsAddressOfOperand, TemplateArgs);
   1811 
   1812     // If this reference is in an Objective-C method, then we need to do
   1813     // some special Objective-C lookup, too.
   1814     if (IvarLookupFollowUp) {
   1815       ExprResult E(LookupInObjCMethod(R, S, II, true));
   1816       if (E.isInvalid())
   1817         return ExprError();
   1818 
   1819       if (Expr *Ex = E.takeAs<Expr>())
   1820         return Owned(Ex);
   1821     }
   1822   }
   1823 
   1824   if (R.isAmbiguous())
   1825     return ExprError();
   1826 
   1827   // Determine whether this name might be a candidate for
   1828   // argument-dependent lookup.
   1829   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
   1830 
   1831   if (R.empty() && !ADL) {
   1832     // Otherwise, this could be an implicitly declared function reference (legal
   1833     // in C90, extension in C99, forbidden in C++).
   1834     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
   1835       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
   1836       if (D) R.addDecl(D);
   1837     }
   1838 
   1839     // If this name wasn't predeclared and if this is not a function
   1840     // call, diagnose the problem.
   1841     if (R.empty()) {
   1842 
   1843       // In Microsoft mode, if we are inside a template class member function
   1844       // and we can't resolve an identifier then assume the identifier is type
   1845       // dependent. The goal is to postpone name lookup to instantiation time
   1846       // to be able to search into type dependent base classes.
   1847       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
   1848           isa<CXXMethodDecl>(CurContext))
   1849         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   1850                                           IsAddressOfOperand, TemplateArgs);
   1851 
   1852       CorrectionCandidateCallback DefaultValidator;
   1853       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
   1854         return ExprError();
   1855 
   1856       assert(!R.empty() &&
   1857              "DiagnoseEmptyLookup returned false but added no results");
   1858 
   1859       // If we found an Objective-C instance variable, let
   1860       // LookupInObjCMethod build the appropriate expression to
   1861       // reference the ivar.
   1862       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
   1863         R.clear();
   1864         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
   1865         // In a hopelessly buggy code, Objective-C instance variable
   1866         // lookup fails and no expression will be built to reference it.
   1867         if (!E.isInvalid() && !E.get())
   1868           return ExprError();
   1869         return E;
   1870       }
   1871     }
   1872   }
   1873 
   1874   // This is guaranteed from this point on.
   1875   assert(!R.empty() || ADL);
   1876 
   1877   // Check whether this might be a C++ implicit instance member access.
   1878   // C++ [class.mfct.non-static]p3:
   1879   //   When an id-expression that is not part of a class member access
   1880   //   syntax and not used to form a pointer to member is used in the
   1881   //   body of a non-static member function of class X, if name lookup
   1882   //   resolves the name in the id-expression to a non-static non-type
   1883   //   member of some class C, the id-expression is transformed into a
   1884   //   class member access expression using (*this) as the
   1885   //   postfix-expression to the left of the . operator.
   1886   //
   1887   // But we don't actually need to do this for '&' operands if R
   1888   // resolved to a function or overloaded function set, because the
   1889   // expression is ill-formed if it actually works out to be a
   1890   // non-static member function:
   1891   //
   1892   // C++ [expr.ref]p4:
   1893   //   Otherwise, if E1.E2 refers to a non-static member function. . .
   1894   //   [t]he expression can be used only as the left-hand operand of a
   1895   //   member function call.
   1896   //
   1897   // There are other safeguards against such uses, but it's important
   1898   // to get this right here so that we don't end up making a
   1899   // spuriously dependent expression if we're inside a dependent
   1900   // instance method.
   1901   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
   1902     bool MightBeImplicitMember;
   1903     if (!IsAddressOfOperand)
   1904       MightBeImplicitMember = true;
   1905     else if (!SS.isEmpty())
   1906       MightBeImplicitMember = false;
   1907     else if (R.isOverloadedResult())
   1908       MightBeImplicitMember = false;
   1909     else if (R.isUnresolvableResult())
   1910       MightBeImplicitMember = true;
   1911     else
   1912       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
   1913                               isa<IndirectFieldDecl>(R.getFoundDecl());
   1914 
   1915     if (MightBeImplicitMember)
   1916       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
   1917                                              R, TemplateArgs);
   1918   }
   1919 
   1920   if (TemplateArgs || TemplateKWLoc.isValid())
   1921     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
   1922 
   1923   return BuildDeclarationNameExpr(SS, R, ADL);
   1924 }
   1925 
   1926 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
   1927 /// declaration name, generally during template instantiation.
   1928 /// There's a large number of things which don't need to be done along
   1929 /// this path.
   1930 ExprResult
   1931 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
   1932                                         const DeclarationNameInfo &NameInfo,
   1933                                         bool IsAddressOfOperand) {
   1934   DeclContext *DC = computeDeclContext(SS, false);
   1935   if (!DC)
   1936     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
   1937                                      NameInfo, /*TemplateArgs=*/0);
   1938 
   1939   if (RequireCompleteDeclContext(SS, DC))
   1940     return ExprError();
   1941 
   1942   LookupResult R(*this, NameInfo, LookupOrdinaryName);
   1943   LookupQualifiedName(R, DC);
   1944 
   1945   if (R.isAmbiguous())
   1946     return ExprError();
   1947 
   1948   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
   1949     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
   1950                                      NameInfo, /*TemplateArgs=*/0);
   1951 
   1952   if (R.empty()) {
   1953     Diag(NameInfo.getLoc(), diag::err_no_member)
   1954       << NameInfo.getName() << DC << SS.getRange();
   1955     return ExprError();
   1956   }
   1957 
   1958   // Defend against this resolving to an implicit member access. We usually
   1959   // won't get here if this might be a legitimate a class member (we end up in
   1960   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
   1961   // a pointer-to-member or in an unevaluated context in C++11.
   1962   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
   1963     return BuildPossibleImplicitMemberExpr(SS,
   1964                                            /*TemplateKWLoc=*/SourceLocation(),
   1965                                            R, /*TemplateArgs=*/0);
   1966 
   1967   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
   1968 }
   1969 
   1970 /// LookupInObjCMethod - The parser has read a name in, and Sema has
   1971 /// detected that we're currently inside an ObjC method.  Perform some
   1972 /// additional lookup.
   1973 ///
   1974 /// Ideally, most of this would be done by lookup, but there's
   1975 /// actually quite a lot of extra work involved.
   1976 ///
   1977 /// Returns a null sentinel to indicate trivial success.
   1978 ExprResult
   1979 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
   1980                          IdentifierInfo *II, bool AllowBuiltinCreation) {
   1981   SourceLocation Loc = Lookup.getNameLoc();
   1982   ObjCMethodDecl *CurMethod = getCurMethodDecl();
   1983 
   1984   // Check for error condition which is already reported.
   1985   if (!CurMethod)
   1986     return ExprError();
   1987 
   1988   // There are two cases to handle here.  1) scoped lookup could have failed,
   1989   // in which case we should look for an ivar.  2) scoped lookup could have
   1990   // found a decl, but that decl is outside the current instance method (i.e.
   1991   // a global variable).  In these two cases, we do a lookup for an ivar with
   1992   // this name, if the lookup sucedes, we replace it our current decl.
   1993 
   1994   // If we're in a class method, we don't normally want to look for
   1995   // ivars.  But if we don't find anything else, and there's an
   1996   // ivar, that's an error.
   1997   bool IsClassMethod = CurMethod->isClassMethod();
   1998 
   1999   bool LookForIvars;
   2000   if (Lookup.empty())
   2001     LookForIvars = true;
   2002   else if (IsClassMethod)
   2003     LookForIvars = false;
   2004   else
   2005     LookForIvars = (Lookup.isSingleResult() &&
   2006                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
   2007   ObjCInterfaceDecl *IFace = 0;
   2008   if (LookForIvars) {
   2009     IFace = CurMethod->getClassInterface();
   2010     ObjCInterfaceDecl *ClassDeclared;
   2011     ObjCIvarDecl *IV = 0;
   2012     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
   2013       // Diagnose using an ivar in a class method.
   2014       if (IsClassMethod)
   2015         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   2016                          << IV->getDeclName());
   2017 
   2018       // If we're referencing an invalid decl, just return this as a silent
   2019       // error node.  The error diagnostic was already emitted on the decl.
   2020       if (IV->isInvalidDecl())
   2021         return ExprError();
   2022 
   2023       // Check if referencing a field with __attribute__((deprecated)).
   2024       if (DiagnoseUseOfDecl(IV, Loc))
   2025         return ExprError();
   2026 
   2027       // Diagnose the use of an ivar outside of the declaring class.
   2028       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
   2029           !declaresSameEntity(ClassDeclared, IFace) &&
   2030           !getLangOpts().DebuggerSupport)
   2031         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
   2032 
   2033       // FIXME: This should use a new expr for a direct reference, don't
   2034       // turn this into Self->ivar, just return a BareIVarExpr or something.
   2035       IdentifierInfo &II = Context.Idents.get("self");
   2036       UnqualifiedId SelfName;
   2037       SelfName.setIdentifier(&II, SourceLocation());
   2038       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
   2039       CXXScopeSpec SelfScopeSpec;
   2040       SourceLocation TemplateKWLoc;
   2041       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
   2042                                               SelfName, false, false);
   2043       if (SelfExpr.isInvalid())
   2044         return ExprError();
   2045 
   2046       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
   2047       if (SelfExpr.isInvalid())
   2048         return ExprError();
   2049 
   2050       MarkAnyDeclReferenced(Loc, IV, true);
   2051 
   2052       ObjCMethodFamily MF = CurMethod->getMethodFamily();
   2053       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
   2054           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
   2055         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
   2056 
   2057       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
   2058                                                               Loc,
   2059                                                               SelfExpr.take(),
   2060                                                               true, true);
   2061 
   2062       if (getLangOpts().ObjCAutoRefCount) {
   2063         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
   2064           DiagnosticsEngine::Level Level =
   2065             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
   2066           if (Level != DiagnosticsEngine::Ignored)
   2067             getCurFunction()->recordUseOfWeak(Result);
   2068         }
   2069         if (CurContext->isClosure())
   2070           Diag(Loc, diag::warn_implicitly_retains_self)
   2071             << FixItHint::CreateInsertion(Loc, "self->");
   2072       }
   2073 
   2074       return Owned(Result);
   2075     }
   2076   } else if (CurMethod->isInstanceMethod()) {
   2077     // We should warn if a local variable hides an ivar.
   2078     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
   2079       ObjCInterfaceDecl *ClassDeclared;
   2080       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
   2081         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
   2082             declaresSameEntity(IFace, ClassDeclared))
   2083           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
   2084       }
   2085     }
   2086   } else if (Lookup.isSingleResult() &&
   2087              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
   2088     // If accessing a stand-alone ivar in a class method, this is an error.
   2089     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
   2090       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   2091                        << IV->getDeclName());
   2092   }
   2093 
   2094   if (Lookup.empty() && II && AllowBuiltinCreation) {
   2095     // FIXME. Consolidate this with similar code in LookupName.
   2096     if (unsigned BuiltinID = II->getBuiltinID()) {
   2097       if (!(getLangOpts().CPlusPlus &&
   2098             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
   2099         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
   2100                                            S, Lookup.isForRedeclaration(),
   2101                                            Lookup.getNameLoc());
   2102         if (D) Lookup.addDecl(D);
   2103       }
   2104     }
   2105   }
   2106   // Sentinel value saying that we didn't do anything special.
   2107   return Owned((Expr*) 0);
   2108 }
   2109 
   2110 /// \brief Cast a base object to a member's actual type.
   2111 ///
   2112 /// Logically this happens in three phases:
   2113 ///
   2114 /// * First we cast from the base type to the naming class.
   2115 ///   The naming class is the class into which we were looking
   2116 ///   when we found the member;  it's the qualifier type if a
   2117 ///   qualifier was provided, and otherwise it's the base type.
   2118 ///
   2119 /// * Next we cast from the naming class to the declaring class.
   2120 ///   If the member we found was brought into a class's scope by
   2121 ///   a using declaration, this is that class;  otherwise it's
   2122 ///   the class declaring the member.
   2123 ///
   2124 /// * Finally we cast from the declaring class to the "true"
   2125 ///   declaring class of the member.  This conversion does not
   2126 ///   obey access control.
   2127 ExprResult
   2128 Sema::PerformObjectMemberConversion(Expr *From,
   2129                                     NestedNameSpecifier *Qualifier,
   2130                                     NamedDecl *FoundDecl,
   2131                                     NamedDecl *Member) {
   2132   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
   2133   if (!RD)
   2134     return Owned(From);
   2135 
   2136   QualType DestRecordType;
   2137   QualType DestType;
   2138   QualType FromRecordType;
   2139   QualType FromType = From->getType();
   2140   bool PointerConversions = false;
   2141   if (isa<FieldDecl>(Member)) {
   2142     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
   2143 
   2144     if (FromType->getAs<PointerType>()) {
   2145       DestType = Context.getPointerType(DestRecordType);
   2146       FromRecordType = FromType->getPointeeType();
   2147       PointerConversions = true;
   2148     } else {
   2149       DestType = DestRecordType;
   2150       FromRecordType = FromType;
   2151     }
   2152   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
   2153     if (Method->isStatic())
   2154       return Owned(From);
   2155 
   2156     DestType = Method->getThisType(Context);
   2157     DestRecordType = DestType->getPointeeType();
   2158 
   2159     if (FromType->getAs<PointerType>()) {
   2160       FromRecordType = FromType->getPointeeType();
   2161       PointerConversions = true;
   2162     } else {
   2163       FromRecordType = FromType;
   2164       DestType = DestRecordType;
   2165     }
   2166   } else {
   2167     // No conversion necessary.
   2168     return Owned(From);
   2169   }
   2170 
   2171   if (DestType->isDependentType() || FromType->isDependentType())
   2172     return Owned(From);
   2173 
   2174   // If the unqualified types are the same, no conversion is necessary.
   2175   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2176     return Owned(From);
   2177 
   2178   SourceRange FromRange = From->getSourceRange();
   2179   SourceLocation FromLoc = FromRange.getBegin();
   2180 
   2181   ExprValueKind VK = From->getValueKind();
   2182 
   2183   // C++ [class.member.lookup]p8:
   2184   //   [...] Ambiguities can often be resolved by qualifying a name with its
   2185   //   class name.
   2186   //
   2187   // If the member was a qualified name and the qualified referred to a
   2188   // specific base subobject type, we'll cast to that intermediate type
   2189   // first and then to the object in which the member is declared. That allows
   2190   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
   2191   //
   2192   //   class Base { public: int x; };
   2193   //   class Derived1 : public Base { };
   2194   //   class Derived2 : public Base { };
   2195   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
   2196   //
   2197   //   void VeryDerived::f() {
   2198   //     x = 17; // error: ambiguous base subobjects
   2199   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
   2200   //   }
   2201   if (Qualifier) {
   2202     QualType QType = QualType(Qualifier->getAsType(), 0);
   2203     assert(!QType.isNull() && "lookup done with dependent qualifier?");
   2204     assert(QType->isRecordType() && "lookup done with non-record type");
   2205 
   2206     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
   2207 
   2208     // In C++98, the qualifier type doesn't actually have to be a base
   2209     // type of the object type, in which case we just ignore it.
   2210     // Otherwise build the appropriate casts.
   2211     if (IsDerivedFrom(FromRecordType, QRecordType)) {
   2212       CXXCastPath BasePath;
   2213       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
   2214                                        FromLoc, FromRange, &BasePath))
   2215         return ExprError();
   2216 
   2217       if (PointerConversions)
   2218         QType = Context.getPointerType(QType);
   2219       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
   2220                                VK, &BasePath).take();
   2221 
   2222       FromType = QType;
   2223       FromRecordType = QRecordType;
   2224 
   2225       // If the qualifier type was the same as the destination type,
   2226       // we're done.
   2227       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2228         return Owned(From);
   2229     }
   2230   }
   2231 
   2232   bool IgnoreAccess = false;
   2233 
   2234   // If we actually found the member through a using declaration, cast
   2235   // down to the using declaration's type.
   2236   //
   2237   // Pointer equality is fine here because only one declaration of a
   2238   // class ever has member declarations.
   2239   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
   2240     assert(isa<UsingShadowDecl>(FoundDecl));
   2241     QualType URecordType = Context.getTypeDeclType(
   2242                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
   2243 
   2244     // We only need to do this if the naming-class to declaring-class
   2245     // conversion is non-trivial.
   2246     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
   2247       assert(IsDerivedFrom(FromRecordType, URecordType));
   2248       CXXCastPath BasePath;
   2249       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
   2250                                        FromLoc, FromRange, &BasePath))
   2251         return ExprError();
   2252 
   2253       QualType UType = URecordType;
   2254       if (PointerConversions)
   2255         UType = Context.getPointerType(UType);
   2256       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
   2257                                VK, &BasePath).take();
   2258       FromType = UType;
   2259       FromRecordType = URecordType;
   2260     }
   2261 
   2262     // We don't do access control for the conversion from the
   2263     // declaring class to the true declaring class.
   2264     IgnoreAccess = true;
   2265   }
   2266 
   2267   CXXCastPath BasePath;
   2268   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
   2269                                    FromLoc, FromRange, &BasePath,
   2270                                    IgnoreAccess))
   2271     return ExprError();
   2272 
   2273   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
   2274                            VK, &BasePath);
   2275 }
   2276 
   2277 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
   2278                                       const LookupResult &R,
   2279                                       bool HasTrailingLParen) {
   2280   // Only when used directly as the postfix-expression of a call.
   2281   if (!HasTrailingLParen)
   2282     return false;
   2283 
   2284   // Never if a scope specifier was provided.
   2285   if (SS.isSet())
   2286     return false;
   2287 
   2288   // Only in C++ or ObjC++.
   2289   if (!getLangOpts().CPlusPlus)
   2290     return false;
   2291 
   2292   // Turn off ADL when we find certain kinds of declarations during
   2293   // normal lookup:
   2294   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   2295     NamedDecl *D = *I;
   2296 
   2297     // C++0x [basic.lookup.argdep]p3:
   2298     //     -- a declaration of a class member
   2299     // Since using decls preserve this property, we check this on the
   2300     // original decl.
   2301     if (D->isCXXClassMember())
   2302       return false;
   2303 
   2304     // C++0x [basic.lookup.argdep]p3:
   2305     //     -- a block-scope function declaration that is not a
   2306     //        using-declaration
   2307     // NOTE: we also trigger this for function templates (in fact, we
   2308     // don't check the decl type at all, since all other decl types
   2309     // turn off ADL anyway).
   2310     if (isa<UsingShadowDecl>(D))
   2311       D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2312     else if (D->getDeclContext()->isFunctionOrMethod())
   2313       return false;
   2314 
   2315     // C++0x [basic.lookup.argdep]p3:
   2316     //     -- a declaration that is neither a function or a function
   2317     //        template
   2318     // And also for builtin functions.
   2319     if (isa<FunctionDecl>(D)) {
   2320       FunctionDecl *FDecl = cast<FunctionDecl>(D);
   2321 
   2322       // But also builtin functions.
   2323       if (FDecl->getBuiltinID() && FDecl->isImplicit())
   2324         return false;
   2325     } else if (!isa<FunctionTemplateDecl>(D))
   2326       return false;
   2327   }
   2328 
   2329   return true;
   2330 }
   2331 
   2332 
   2333 /// Diagnoses obvious problems with the use of the given declaration
   2334 /// as an expression.  This is only actually called for lookups that
   2335 /// were not overloaded, and it doesn't promise that the declaration
   2336 /// will in fact be used.
   2337 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
   2338   if (isa<TypedefNameDecl>(D)) {
   2339     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
   2340     return true;
   2341   }
   2342 
   2343   if (isa<ObjCInterfaceDecl>(D)) {
   2344     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
   2345     return true;
   2346   }
   2347 
   2348   if (isa<NamespaceDecl>(D)) {
   2349     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
   2350     return true;
   2351   }
   2352 
   2353   return false;
   2354 }
   2355 
   2356 ExprResult
   2357 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2358                                LookupResult &R,
   2359                                bool NeedsADL) {
   2360   // If this is a single, fully-resolved result and we don't need ADL,
   2361   // just build an ordinary singleton decl ref.
   2362   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
   2363     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
   2364                                     R.getFoundDecl());
   2365 
   2366   // We only need to check the declaration if there's exactly one
   2367   // result, because in the overloaded case the results can only be
   2368   // functions and function templates.
   2369   if (R.isSingleResult() &&
   2370       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
   2371     return ExprError();
   2372 
   2373   // Otherwise, just build an unresolved lookup expression.  Suppress
   2374   // any lookup-related diagnostics; we'll hash these out later, when
   2375   // we've picked a target.
   2376   R.suppressDiagnostics();
   2377 
   2378   UnresolvedLookupExpr *ULE
   2379     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
   2380                                    SS.getWithLocInContext(Context),
   2381                                    R.getLookupNameInfo(),
   2382                                    NeedsADL, R.isOverloadedResult(),
   2383                                    R.begin(), R.end());
   2384 
   2385   return Owned(ULE);
   2386 }
   2387 
   2388 /// \brief Complete semantic analysis for a reference to the given declaration.
   2389 ExprResult
   2390 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2391                                const DeclarationNameInfo &NameInfo,
   2392                                NamedDecl *D) {
   2393   assert(D && "Cannot refer to a NULL declaration");
   2394   assert(!isa<FunctionTemplateDecl>(D) &&
   2395          "Cannot refer unambiguously to a function template");
   2396 
   2397   SourceLocation Loc = NameInfo.getLoc();
   2398   if (CheckDeclInExpr(*this, Loc, D))
   2399     return ExprError();
   2400 
   2401   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
   2402     // Specifically diagnose references to class templates that are missing
   2403     // a template argument list.
   2404     Diag(Loc, diag::err_template_decl_ref)
   2405       << Template << SS.getRange();
   2406     Diag(Template->getLocation(), diag::note_template_decl_here);
   2407     return ExprError();
   2408   }
   2409 
   2410   // Make sure that we're referring to a value.
   2411   ValueDecl *VD = dyn_cast<ValueDecl>(D);
   2412   if (!VD) {
   2413     Diag(Loc, diag::err_ref_non_value)
   2414       << D << SS.getRange();
   2415     Diag(D->getLocation(), diag::note_declared_at);
   2416     return ExprError();
   2417   }
   2418 
   2419   // Check whether this declaration can be used. Note that we suppress
   2420   // this check when we're going to perform argument-dependent lookup
   2421   // on this function name, because this might not be the function
   2422   // that overload resolution actually selects.
   2423   if (DiagnoseUseOfDecl(VD, Loc))
   2424     return ExprError();
   2425 
   2426   // Only create DeclRefExpr's for valid Decl's.
   2427   if (VD->isInvalidDecl())
   2428     return ExprError();
   2429 
   2430   // Handle members of anonymous structs and unions.  If we got here,
   2431   // and the reference is to a class member indirect field, then this
   2432   // must be the subject of a pointer-to-member expression.
   2433   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
   2434     if (!indirectField->isCXXClassMember())
   2435       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
   2436                                                       indirectField);
   2437 
   2438   {
   2439     QualType type = VD->getType();
   2440     ExprValueKind valueKind = VK_RValue;
   2441 
   2442     switch (D->getKind()) {
   2443     // Ignore all the non-ValueDecl kinds.
   2444 #define ABSTRACT_DECL(kind)
   2445 #define VALUE(type, base)
   2446 #define DECL(type, base) \
   2447     case Decl::type:
   2448 #include "clang/AST/DeclNodes.inc"
   2449       llvm_unreachable("invalid value decl kind");
   2450 
   2451     // These shouldn't make it here.
   2452     case Decl::ObjCAtDefsField:
   2453     case Decl::ObjCIvar:
   2454       llvm_unreachable("forming non-member reference to ivar?");
   2455 
   2456     // Enum constants are always r-values and never references.
   2457     // Unresolved using declarations are dependent.
   2458     case Decl::EnumConstant:
   2459     case Decl::UnresolvedUsingValue:
   2460       valueKind = VK_RValue;
   2461       break;
   2462 
   2463     // Fields and indirect fields that got here must be for
   2464     // pointer-to-member expressions; we just call them l-values for
   2465     // internal consistency, because this subexpression doesn't really
   2466     // exist in the high-level semantics.
   2467     case Decl::Field:
   2468     case Decl::IndirectField:
   2469       assert(getLangOpts().CPlusPlus &&
   2470              "building reference to field in C?");
   2471 
   2472       // These can't have reference type in well-formed programs, but
   2473       // for internal consistency we do this anyway.
   2474       type = type.getNonReferenceType();
   2475       valueKind = VK_LValue;
   2476       break;
   2477 
   2478     // Non-type template parameters are either l-values or r-values
   2479     // depending on the type.
   2480     case Decl::NonTypeTemplateParm: {
   2481       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
   2482         type = reftype->getPointeeType();
   2483         valueKind = VK_LValue; // even if the parameter is an r-value reference
   2484         break;
   2485       }
   2486 
   2487       // For non-references, we need to strip qualifiers just in case
   2488       // the template parameter was declared as 'const int' or whatever.
   2489       valueKind = VK_RValue;
   2490       type = type.getUnqualifiedType();
   2491       break;
   2492     }
   2493 
   2494     case Decl::Var:
   2495       // In C, "extern void blah;" is valid and is an r-value.
   2496       if (!getLangOpts().CPlusPlus &&
   2497           !type.hasQualifiers() &&
   2498           type->isVoidType()) {
   2499         valueKind = VK_RValue;
   2500         break;
   2501       }
   2502       // fallthrough
   2503 
   2504     case Decl::ImplicitParam:
   2505     case Decl::ParmVar: {
   2506       // These are always l-values.
   2507       valueKind = VK_LValue;
   2508       type = type.getNonReferenceType();
   2509 
   2510       // FIXME: Does the addition of const really only apply in
   2511       // potentially-evaluated contexts? Since the variable isn't actually
   2512       // captured in an unevaluated context, it seems that the answer is no.
   2513       if (!isUnevaluatedContext()) {
   2514         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
   2515         if (!CapturedType.isNull())
   2516           type = CapturedType;
   2517       }
   2518 
   2519       break;
   2520     }
   2521 
   2522     case Decl::Function: {
   2523       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
   2524         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
   2525           type = Context.BuiltinFnTy;
   2526           valueKind = VK_RValue;
   2527           break;
   2528         }
   2529       }
   2530 
   2531       const FunctionType *fty = type->castAs<FunctionType>();
   2532 
   2533       // If we're referring to a function with an __unknown_anytype
   2534       // result type, make the entire expression __unknown_anytype.
   2535       if (fty->getResultType() == Context.UnknownAnyTy) {
   2536         type = Context.UnknownAnyTy;
   2537         valueKind = VK_RValue;
   2538         break;
   2539       }
   2540 
   2541       // Functions are l-values in C++.
   2542       if (getLangOpts().CPlusPlus) {
   2543         valueKind = VK_LValue;
   2544         break;
   2545       }
   2546 
   2547       // C99 DR 316 says that, if a function type comes from a
   2548       // function definition (without a prototype), that type is only
   2549       // used for checking compatibility. Therefore, when referencing
   2550       // the function, we pretend that we don't have the full function
   2551       // type.
   2552       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
   2553           isa<FunctionProtoType>(fty))
   2554         type = Context.getFunctionNoProtoType(fty->getResultType(),
   2555                                               fty->getExtInfo());
   2556 
   2557       // Functions are r-values in C.
   2558       valueKind = VK_RValue;
   2559       break;
   2560     }
   2561 
   2562     case Decl::CXXMethod:
   2563       // If we're referring to a method with an __unknown_anytype
   2564       // result type, make the entire expression __unknown_anytype.
   2565       // This should only be possible with a type written directly.
   2566       if (const FunctionProtoType *proto
   2567             = dyn_cast<FunctionProtoType>(VD->getType()))
   2568         if (proto->getResultType() == Context.UnknownAnyTy) {
   2569           type = Context.UnknownAnyTy;
   2570           valueKind = VK_RValue;
   2571           break;
   2572         }
   2573 
   2574       // C++ methods are l-values if static, r-values if non-static.
   2575       if (cast<CXXMethodDecl>(VD)->isStatic()) {
   2576         valueKind = VK_LValue;
   2577         break;
   2578       }
   2579       // fallthrough
   2580 
   2581     case Decl::CXXConversion:
   2582     case Decl::CXXDestructor:
   2583     case Decl::CXXConstructor:
   2584       valueKind = VK_RValue;
   2585       break;
   2586     }
   2587 
   2588     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
   2589   }
   2590 }
   2591 
   2592 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
   2593   PredefinedExpr::IdentType IT;
   2594 
   2595   switch (Kind) {
   2596   default: llvm_unreachable("Unknown simple primary expr!");
   2597   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
   2598   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
   2599   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
   2600   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
   2601   }
   2602 
   2603   // Pre-defined identifiers are of type char[x], where x is the length of the
   2604   // string.
   2605 
   2606   Decl *currentDecl = getCurFunctionOrMethodDecl();
   2607   // Blocks and lambdas can occur at global scope. Don't emit a warning.
   2608   if (!currentDecl) {
   2609     if (const BlockScopeInfo *BSI = getCurBlock())
   2610       currentDecl = BSI->TheDecl;
   2611     else if (const LambdaScopeInfo *LSI = getCurLambda())
   2612       currentDecl = LSI->CallOperator;
   2613   }
   2614 
   2615   if (!currentDecl) {
   2616     Diag(Loc, diag::ext_predef_outside_function);
   2617     currentDecl = Context.getTranslationUnitDecl();
   2618   }
   2619 
   2620   QualType ResTy;
   2621   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
   2622     ResTy = Context.DependentTy;
   2623   } else {
   2624     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
   2625 
   2626     llvm::APInt LengthI(32, Length + 1);
   2627     if (IT == PredefinedExpr::LFunction)
   2628       ResTy = Context.WCharTy.withConst();
   2629     else
   2630       ResTy = Context.CharTy.withConst();
   2631     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
   2632   }
   2633   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
   2634 }
   2635 
   2636 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
   2637   SmallString<16> CharBuffer;
   2638   bool Invalid = false;
   2639   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
   2640   if (Invalid)
   2641     return ExprError();
   2642 
   2643   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
   2644                             PP, Tok.getKind());
   2645   if (Literal.hadError())
   2646     return ExprError();
   2647 
   2648   QualType Ty;
   2649   if (Literal.isWide())
   2650     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
   2651   else if (Literal.isUTF16())
   2652     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
   2653   else if (Literal.isUTF32())
   2654     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
   2655   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
   2656     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
   2657   else
   2658     Ty = Context.CharTy;  // 'x' -> char in C++
   2659 
   2660   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
   2661   if (Literal.isWide())
   2662     Kind = CharacterLiteral::Wide;
   2663   else if (Literal.isUTF16())
   2664     Kind = CharacterLiteral::UTF16;
   2665   else if (Literal.isUTF32())
   2666     Kind = CharacterLiteral::UTF32;
   2667 
   2668   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
   2669                                              Tok.getLocation());
   2670 
   2671   if (Literal.getUDSuffix().empty())
   2672     return Owned(Lit);
   2673 
   2674   // We're building a user-defined literal.
   2675   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   2676   SourceLocation UDSuffixLoc =
   2677     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   2678 
   2679   // Make sure we're allowed user-defined literals here.
   2680   if (!UDLScope)
   2681     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
   2682 
   2683   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
   2684   //   operator "" X (ch)
   2685   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
   2686                                         llvm::makeArrayRef(&Lit, 1),
   2687                                         Tok.getLocation());
   2688 }
   2689 
   2690 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
   2691   unsigned IntSize = Context.getTargetInfo().getIntWidth();
   2692   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
   2693                                       Context.IntTy, Loc));
   2694 }
   2695 
   2696 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
   2697                                   QualType Ty, SourceLocation Loc) {
   2698   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
   2699 
   2700   using llvm::APFloat;
   2701   APFloat Val(Format);
   2702 
   2703   APFloat::opStatus result = Literal.GetFloatValue(Val);
   2704 
   2705   // Overflow is always an error, but underflow is only an error if
   2706   // we underflowed to zero (APFloat reports denormals as underflow).
   2707   if ((result & APFloat::opOverflow) ||
   2708       ((result & APFloat::opUnderflow) && Val.isZero())) {
   2709     unsigned diagnostic;
   2710     SmallString<20> buffer;
   2711     if (result & APFloat::opOverflow) {
   2712       diagnostic = diag::warn_float_overflow;
   2713       APFloat::getLargest(Format).toString(buffer);
   2714     } else {
   2715       diagnostic = diag::warn_float_underflow;
   2716       APFloat::getSmallest(Format).toString(buffer);
   2717     }
   2718 
   2719     S.Diag(Loc, diagnostic)
   2720       << Ty
   2721       << StringRef(buffer.data(), buffer.size());
   2722   }
   2723 
   2724   bool isExact = (result == APFloat::opOK);
   2725   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
   2726 }
   2727 
   2728 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
   2729   // Fast path for a single digit (which is quite common).  A single digit
   2730   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
   2731   if (Tok.getLength() == 1) {
   2732     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
   2733     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
   2734   }
   2735 
   2736   SmallString<128> SpellingBuffer;
   2737   // NumericLiteralParser wants to overread by one character.  Add padding to
   2738   // the buffer in case the token is copied to the buffer.  If getSpelling()
   2739   // returns a StringRef to the memory buffer, it should have a null char at
   2740   // the EOF, so it is also safe.
   2741   SpellingBuffer.resize(Tok.getLength() + 1);
   2742 
   2743   // Get the spelling of the token, which eliminates trigraphs, etc.
   2744   bool Invalid = false;
   2745   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
   2746   if (Invalid)
   2747     return ExprError();
   2748 
   2749   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
   2750   if (Literal.hadError)
   2751     return ExprError();
   2752 
   2753   if (Literal.hasUDSuffix()) {
   2754     // We're building a user-defined literal.
   2755     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   2756     SourceLocation UDSuffixLoc =
   2757       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   2758 
   2759     // Make sure we're allowed user-defined literals here.
   2760     if (!UDLScope)
   2761       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
   2762 
   2763     QualType CookedTy;
   2764     if (Literal.isFloatingLiteral()) {
   2765       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
   2766       // long double, the literal is treated as a call of the form
   2767       //   operator "" X (f L)
   2768       CookedTy = Context.LongDoubleTy;
   2769     } else {
   2770       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
   2771       // unsigned long long, the literal is treated as a call of the form
   2772       //   operator "" X (n ULL)
   2773       CookedTy = Context.UnsignedLongLongTy;
   2774     }
   2775 
   2776     DeclarationName OpName =
   2777       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   2778     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   2779     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   2780 
   2781     // Perform literal operator lookup to determine if we're building a raw
   2782     // literal or a cooked one.
   2783     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
   2784     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
   2785                                   /*AllowRawAndTemplate*/true)) {
   2786     case LOLR_Error:
   2787       return ExprError();
   2788 
   2789     case LOLR_Cooked: {
   2790       Expr *Lit;
   2791       if (Literal.isFloatingLiteral()) {
   2792         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
   2793       } else {
   2794         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
   2795         if (Literal.GetIntegerValue(ResultVal))
   2796           Diag(Tok.getLocation(), diag::warn_integer_too_large);
   2797         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
   2798                                      Tok.getLocation());
   2799       }
   2800       return BuildLiteralOperatorCall(R, OpNameInfo,
   2801                                       llvm::makeArrayRef(&Lit, 1),
   2802                                       Tok.getLocation());
   2803     }
   2804 
   2805     case LOLR_Raw: {
   2806       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
   2807       // literal is treated as a call of the form
   2808       //   operator "" X ("n")
   2809       SourceLocation TokLoc = Tok.getLocation();
   2810       unsigned Length = Literal.getUDSuffixOffset();
   2811       QualType StrTy = Context.getConstantArrayType(
   2812           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
   2813           ArrayType::Normal, 0);
   2814       Expr *Lit = StringLiteral::Create(
   2815           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
   2816           /*Pascal*/false, StrTy, &TokLoc, 1);
   2817       return BuildLiteralOperatorCall(R, OpNameInfo,
   2818                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
   2819     }
   2820 
   2821     case LOLR_Template:
   2822       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
   2823       // template), L is treated as a call fo the form
   2824       //   operator "" X <'c1', 'c2', ... 'ck'>()
   2825       // where n is the source character sequence c1 c2 ... ck.
   2826       TemplateArgumentListInfo ExplicitArgs;
   2827       unsigned CharBits = Context.getIntWidth(Context.CharTy);
   2828       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
   2829       llvm::APSInt Value(CharBits, CharIsUnsigned);
   2830       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
   2831         Value = TokSpelling[I];
   2832         TemplateArgument Arg(Context, Value, Context.CharTy);
   2833         TemplateArgumentLocInfo ArgInfo;
   2834         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
   2835       }
   2836       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
   2837                                       Tok.getLocation(), &ExplicitArgs);
   2838     }
   2839 
   2840     llvm_unreachable("unexpected literal operator lookup result");
   2841   }
   2842 
   2843   Expr *Res;
   2844 
   2845   if (Literal.isFloatingLiteral()) {
   2846     QualType Ty;
   2847     if (Literal.isFloat)
   2848       Ty = Context.FloatTy;
   2849     else if (!Literal.isLong)
   2850       Ty = Context.DoubleTy;
   2851     else
   2852       Ty = Context.LongDoubleTy;
   2853 
   2854     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
   2855 
   2856     if (Ty == Context.DoubleTy) {
   2857       if (getLangOpts().SinglePrecisionConstants) {
   2858         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
   2859       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
   2860         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
   2861         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
   2862       }
   2863     }
   2864   } else if (!Literal.isIntegerLiteral()) {
   2865     return ExprError();
   2866   } else {
   2867     QualType Ty;
   2868 
   2869     // 'long long' is a C99 or C++11 feature.
   2870     if (!getLangOpts().C99 && Literal.isLongLong) {
   2871       if (getLangOpts().CPlusPlus)
   2872         Diag(Tok.getLocation(),
   2873              getLangOpts().CPlusPlus11 ?
   2874              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
   2875       else
   2876         Diag(Tok.getLocation(), diag::ext_c99_longlong);
   2877     }
   2878 
   2879     // Get the value in the widest-possible width.
   2880     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
   2881     // The microsoft literal suffix extensions support 128-bit literals, which
   2882     // may be wider than [u]intmax_t.
   2883     // FIXME: Actually, they don't. We seem to have accidentally invented the
   2884     //        i128 suffix.
   2885     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
   2886         PP.getTargetInfo().hasInt128Type())
   2887       MaxWidth = 128;
   2888     llvm::APInt ResultVal(MaxWidth, 0);
   2889 
   2890     if (Literal.GetIntegerValue(ResultVal)) {
   2891       // If this value didn't fit into uintmax_t, warn and force to ull.
   2892       Diag(Tok.getLocation(), diag::warn_integer_too_large);
   2893       Ty = Context.UnsignedLongLongTy;
   2894       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
   2895              "long long is not intmax_t?");
   2896     } else {
   2897       // If this value fits into a ULL, try to figure out what else it fits into
   2898       // according to the rules of C99 6.4.4.1p5.
   2899 
   2900       // Octal, Hexadecimal, and integers with a U suffix are allowed to
   2901       // be an unsigned int.
   2902       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
   2903 
   2904       // Check from smallest to largest, picking the smallest type we can.
   2905       unsigned Width = 0;
   2906       if (!Literal.isLong && !Literal.isLongLong) {
   2907         // Are int/unsigned possibilities?
   2908         unsigned IntSize = Context.getTargetInfo().getIntWidth();
   2909 
   2910         // Does it fit in a unsigned int?
   2911         if (ResultVal.isIntN(IntSize)) {
   2912           // Does it fit in a signed int?
   2913           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
   2914             Ty = Context.IntTy;
   2915           else if (AllowUnsigned)
   2916             Ty = Context.UnsignedIntTy;
   2917           Width = IntSize;
   2918         }
   2919       }
   2920 
   2921       // Are long/unsigned long possibilities?
   2922       if (Ty.isNull() && !Literal.isLongLong) {
   2923         unsigned LongSize = Context.getTargetInfo().getLongWidth();
   2924 
   2925         // Does it fit in a unsigned long?
   2926         if (ResultVal.isIntN(LongSize)) {
   2927           // Does it fit in a signed long?
   2928           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
   2929             Ty = Context.LongTy;
   2930           else if (AllowUnsigned)
   2931             Ty = Context.UnsignedLongTy;
   2932           Width = LongSize;
   2933         }
   2934       }
   2935 
   2936       // Check long long if needed.
   2937       if (Ty.isNull()) {
   2938         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
   2939 
   2940         // Does it fit in a unsigned long long?
   2941         if (ResultVal.isIntN(LongLongSize)) {
   2942           // Does it fit in a signed long long?
   2943           // To be compatible with MSVC, hex integer literals ending with the
   2944           // LL or i64 suffix are always signed in Microsoft mode.
   2945           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
   2946               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
   2947             Ty = Context.LongLongTy;
   2948           else if (AllowUnsigned)
   2949             Ty = Context.UnsignedLongLongTy;
   2950           Width = LongLongSize;
   2951         }
   2952       }
   2953 
   2954       // If it doesn't fit in unsigned long long, and we're using Microsoft
   2955       // extensions, then its a 128-bit integer literal.
   2956       if (Ty.isNull() && Literal.isMicrosoftInteger &&
   2957           PP.getTargetInfo().hasInt128Type()) {
   2958         if (Literal.isUnsigned)
   2959           Ty = Context.UnsignedInt128Ty;
   2960         else
   2961           Ty = Context.Int128Ty;
   2962         Width = 128;
   2963       }
   2964 
   2965       // If we still couldn't decide a type, we probably have something that
   2966       // does not fit in a signed long long, but has no U suffix.
   2967       if (Ty.isNull()) {
   2968         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
   2969         Ty = Context.UnsignedLongLongTy;
   2970         Width = Context.getTargetInfo().getLongLongWidth();
   2971       }
   2972 
   2973       if (ResultVal.getBitWidth() != Width)
   2974         ResultVal = ResultVal.trunc(Width);
   2975     }
   2976     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
   2977   }
   2978 
   2979   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
   2980   if (Literal.isImaginary)
   2981     Res = new (Context) ImaginaryLiteral(Res,
   2982                                         Context.getComplexType(Res->getType()));
   2983 
   2984   return Owned(Res);
   2985 }
   2986 
   2987 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
   2988   assert((E != 0) && "ActOnParenExpr() missing expr");
   2989   return Owned(new (Context) ParenExpr(L, R, E));
   2990 }
   2991 
   2992 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
   2993                                          SourceLocation Loc,
   2994                                          SourceRange ArgRange) {
   2995   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
   2996   // scalar or vector data type argument..."
   2997   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
   2998   // type (C99 6.2.5p18) or void.
   2999   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
   3000     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
   3001       << T << ArgRange;
   3002     return true;
   3003   }
   3004 
   3005   assert((T->isVoidType() || !T->isIncompleteType()) &&
   3006          "Scalar types should always be complete");
   3007   return false;
   3008 }
   3009 
   3010 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
   3011                                            SourceLocation Loc,
   3012                                            SourceRange ArgRange,
   3013                                            UnaryExprOrTypeTrait TraitKind) {
   3014   // C99 6.5.3.4p1:
   3015   if (T->isFunctionType()) {
   3016     // alignof(function) is allowed as an extension.
   3017     if (TraitKind == UETT_SizeOf)
   3018       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
   3019     return false;
   3020   }
   3021 
   3022   // Allow sizeof(void)/alignof(void) as an extension.
   3023   if (T->isVoidType()) {
   3024     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
   3025     return false;
   3026   }
   3027 
   3028   return true;
   3029 }
   3030 
   3031 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
   3032                                              SourceLocation Loc,
   3033                                              SourceRange ArgRange,
   3034                                              UnaryExprOrTypeTrait TraitKind) {
   3035   // Reject sizeof(interface) and sizeof(interface<proto>) if the
   3036   // runtime doesn't allow it.
   3037   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
   3038     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
   3039       << T << (TraitKind == UETT_SizeOf)
   3040       << ArgRange;
   3041     return true;
   3042   }
   3043 
   3044   return false;
   3045 }
   3046 
   3047 /// \brief Check the constrains on expression operands to unary type expression
   3048 /// and type traits.
   3049 ///
   3050 /// Completes any types necessary and validates the constraints on the operand
   3051 /// expression. The logic mostly mirrors the type-based overload, but may modify
   3052 /// the expression as it completes the type for that expression through template
   3053 /// instantiation, etc.
   3054 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
   3055                                             UnaryExprOrTypeTrait ExprKind) {
   3056   QualType ExprTy = E->getType();
   3057 
   3058   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   3059   //   the result is the size of the referenced type."
   3060   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   3061   //   result shall be the alignment of the referenced type."
   3062   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
   3063     ExprTy = Ref->getPointeeType();
   3064 
   3065   if (ExprKind == UETT_VecStep)
   3066     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
   3067                                         E->getSourceRange());
   3068 
   3069   // Whitelist some types as extensions
   3070   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
   3071                                       E->getSourceRange(), ExprKind))
   3072     return false;
   3073 
   3074   if (RequireCompleteExprType(E,
   3075                               diag::err_sizeof_alignof_incomplete_type,
   3076                               ExprKind, E->getSourceRange()))
   3077     return true;
   3078 
   3079   // Completeing the expression's type may have changed it.
   3080   ExprTy = E->getType();
   3081   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
   3082     ExprTy = Ref->getPointeeType();
   3083 
   3084   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
   3085                                        E->getSourceRange(), ExprKind))
   3086     return true;
   3087 
   3088   if (ExprKind == UETT_SizeOf) {
   3089     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
   3090       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
   3091         QualType OType = PVD->getOriginalType();
   3092         QualType Type = PVD->getType();
   3093         if (Type->isPointerType() && OType->isArrayType()) {
   3094           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
   3095             << Type << OType;
   3096           Diag(PVD->getLocation(), diag::note_declared_at);
   3097         }
   3098       }
   3099     }
   3100   }
   3101 
   3102   return false;
   3103 }
   3104 
   3105 /// \brief Check the constraints on operands to unary expression and type
   3106 /// traits.
   3107 ///
   3108 /// This will complete any types necessary, and validate the various constraints
   3109 /// on those operands.
   3110 ///
   3111 /// The UsualUnaryConversions() function is *not* called by this routine.
   3112 /// C99 6.3.2.1p[2-4] all state:
   3113 ///   Except when it is the operand of the sizeof operator ...
   3114 ///
   3115 /// C++ [expr.sizeof]p4
   3116 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
   3117 ///   standard conversions are not applied to the operand of sizeof.
   3118 ///
   3119 /// This policy is followed for all of the unary trait expressions.
   3120 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
   3121                                             SourceLocation OpLoc,
   3122                                             SourceRange ExprRange,
   3123                                             UnaryExprOrTypeTrait ExprKind) {
   3124   if (ExprType->isDependentType())
   3125     return false;
   3126 
   3127   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   3128   //   the result is the size of the referenced type."
   3129   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   3130   //   result shall be the alignment of the referenced type."
   3131   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
   3132     ExprType = Ref->getPointeeType();
   3133 
   3134   if (ExprKind == UETT_VecStep)
   3135     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
   3136 
   3137   // Whitelist some types as extensions
   3138   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
   3139                                       ExprKind))
   3140     return false;
   3141 
   3142   if (RequireCompleteType(OpLoc, ExprType,
   3143                           diag::err_sizeof_alignof_incomplete_type,
   3144                           ExprKind, ExprRange))
   3145     return true;
   3146 
   3147   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
   3148                                        ExprKind))
   3149     return true;
   3150 
   3151   return false;
   3152 }
   3153 
   3154 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
   3155   E = E->IgnoreParens();
   3156 
   3157   // alignof decl is always ok.
   3158   if (isa<DeclRefExpr>(E))
   3159     return false;
   3160 
   3161   // Cannot know anything else if the expression is dependent.
   3162   if (E->isTypeDependent())
   3163     return false;
   3164 
   3165   if (E->getBitField()) {
   3166     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
   3167        << 1 << E->getSourceRange();
   3168     return true;
   3169   }
   3170 
   3171   // Alignment of a field access is always okay, so long as it isn't a
   3172   // bit-field.
   3173   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
   3174     if (isa<FieldDecl>(ME->getMemberDecl()))
   3175       return false;
   3176 
   3177   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
   3178 }
   3179 
   3180 bool Sema::CheckVecStepExpr(Expr *E) {
   3181   E = E->IgnoreParens();
   3182 
   3183   // Cannot know anything else if the expression is dependent.
   3184   if (E->isTypeDependent())
   3185     return false;
   3186 
   3187   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
   3188 }
   3189 
   3190 /// \brief Build a sizeof or alignof expression given a type operand.
   3191 ExprResult
   3192 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
   3193                                      SourceLocation OpLoc,
   3194                                      UnaryExprOrTypeTrait ExprKind,
   3195                                      SourceRange R) {
   3196   if (!TInfo)
   3197     return ExprError();
   3198 
   3199   QualType T = TInfo->getType();
   3200 
   3201   if (!T->isDependentType() &&
   3202       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
   3203     return ExprError();
   3204 
   3205   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3206   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
   3207                                                       Context.getSizeType(),
   3208                                                       OpLoc, R.getEnd()));
   3209 }
   3210 
   3211 /// \brief Build a sizeof or alignof expression given an expression
   3212 /// operand.
   3213 ExprResult
   3214 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
   3215                                      UnaryExprOrTypeTrait ExprKind) {
   3216   ExprResult PE = CheckPlaceholderExpr(E);
   3217   if (PE.isInvalid())
   3218     return ExprError();
   3219 
   3220   E = PE.get();
   3221 
   3222   // Verify that the operand is valid.
   3223   bool isInvalid = false;
   3224   if (E->isTypeDependent()) {
   3225     // Delay type-checking for type-dependent expressions.
   3226   } else if (ExprKind == UETT_AlignOf) {
   3227     isInvalid = CheckAlignOfExpr(*this, E);
   3228   } else if (ExprKind == UETT_VecStep) {
   3229     isInvalid = CheckVecStepExpr(E);
   3230   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
   3231     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
   3232     isInvalid = true;
   3233   } else {
   3234     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
   3235   }
   3236 
   3237   if (isInvalid)
   3238     return ExprError();
   3239 
   3240   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
   3241     PE = TransformToPotentiallyEvaluated(E);
   3242     if (PE.isInvalid()) return ExprError();
   3243     E = PE.take();
   3244   }
   3245 
   3246   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3247   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
   3248       ExprKind, E, Context.getSizeType(), OpLoc,
   3249       E->getSourceRange().getEnd()));
   3250 }
   3251 
   3252 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
   3253 /// expr and the same for @c alignof and @c __alignof
   3254 /// Note that the ArgRange is invalid if isType is false.
   3255 ExprResult
   3256 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
   3257                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
   3258                                     void *TyOrEx, const SourceRange &ArgRange) {
   3259   // If error parsing type, ignore.
   3260   if (TyOrEx == 0) return ExprError();
   3261 
   3262   if (IsType) {
   3263     TypeSourceInfo *TInfo;
   3264     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
   3265     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
   3266   }
   3267 
   3268   Expr *ArgEx = (Expr *)TyOrEx;
   3269   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
   3270   return Result;
   3271 }
   3272 
   3273 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
   3274                                      bool IsReal) {
   3275   if (V.get()->isTypeDependent())
   3276     return S.Context.DependentTy;
   3277 
   3278   // _Real and _Imag are only l-values for normal l-values.
   3279   if (V.get()->getObjectKind() != OK_Ordinary) {
   3280     V = S.DefaultLvalueConversion(V.take());
   3281     if (V.isInvalid())
   3282       return QualType();
   3283   }
   3284 
   3285   // These operators return the element type of a complex type.
   3286   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
   3287     return CT->getElementType();
   3288 
   3289   // Otherwise they pass through real integer and floating point types here.
   3290   if (V.get()->getType()->isArithmeticType())
   3291     return V.get()->getType();
   3292 
   3293   // Test for placeholders.
   3294   ExprResult PR = S.CheckPlaceholderExpr(V.get());
   3295   if (PR.isInvalid()) return QualType();
   3296   if (PR.get() != V.get()) {
   3297     V = PR;
   3298     return CheckRealImagOperand(S, V, Loc, IsReal);
   3299   }
   3300 
   3301   // Reject anything else.
   3302   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
   3303     << (IsReal ? "__real" : "__imag");
   3304   return QualType();
   3305 }
   3306 
   3307 
   3308 
   3309 ExprResult
   3310 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
   3311                           tok::TokenKind Kind, Expr *Input) {
   3312   UnaryOperatorKind Opc;
   3313   switch (Kind) {
   3314   default: llvm_unreachable("Unknown unary op!");
   3315   case tok::plusplus:   Opc = UO_PostInc; break;
   3316   case tok::minusminus: Opc = UO_PostDec; break;
   3317   }
   3318 
   3319   // Since this might is a postfix expression, get rid of ParenListExprs.
   3320   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
   3321   if (Result.isInvalid()) return ExprError();
   3322   Input = Result.take();
   3323 
   3324   return BuildUnaryOp(S, OpLoc, Opc, Input);
   3325 }
   3326 
   3327 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
   3328 ///
   3329 /// \return true on error
   3330 static bool checkArithmeticOnObjCPointer(Sema &S,
   3331                                          SourceLocation opLoc,
   3332                                          Expr *op) {
   3333   assert(op->getType()->isObjCObjectPointerType());
   3334   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
   3335     return false;
   3336 
   3337   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
   3338     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
   3339     << op->getSourceRange();
   3340   return true;
   3341 }
   3342 
   3343 ExprResult
   3344 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
   3345                               Expr *idx, SourceLocation rbLoc) {
   3346   // Since this might be a postfix expression, get rid of ParenListExprs.
   3347   if (isa<ParenListExpr>(base)) {
   3348     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
   3349     if (result.isInvalid()) return ExprError();
   3350     base = result.take();
   3351   }
   3352 
   3353   // Handle any non-overload placeholder types in the base and index
   3354   // expressions.  We can't handle overloads here because the other
   3355   // operand might be an overloadable type, in which case the overload
   3356   // resolution for the operator overload should get the first crack
   3357   // at the overload.
   3358   if (base->getType()->isNonOverloadPlaceholderType()) {
   3359     ExprResult result = CheckPlaceholderExpr(base);
   3360     if (result.isInvalid()) return ExprError();
   3361     base = result.take();
   3362   }
   3363   if (idx->getType()->isNonOverloadPlaceholderType()) {
   3364     ExprResult result = CheckPlaceholderExpr(idx);
   3365     if (result.isInvalid()) return ExprError();
   3366     idx = result.take();
   3367   }
   3368 
   3369   // Build an unanalyzed expression if either operand is type-dependent.
   3370   if (getLangOpts().CPlusPlus &&
   3371       (base->isTypeDependent() || idx->isTypeDependent())) {
   3372     return Owned(new (Context) ArraySubscriptExpr(base, idx,
   3373                                                   Context.DependentTy,
   3374                                                   VK_LValue, OK_Ordinary,
   3375                                                   rbLoc));
   3376   }
   3377 
   3378   // Use C++ overloaded-operator rules if either operand has record
   3379   // type.  The spec says to do this if either type is *overloadable*,
   3380   // but enum types can't declare subscript operators or conversion
   3381   // operators, so there's nothing interesting for overload resolution
   3382   // to do if there aren't any record types involved.
   3383   //
   3384   // ObjC pointers have their own subscripting logic that is not tied
   3385   // to overload resolution and so should not take this path.
   3386   if (getLangOpts().CPlusPlus &&
   3387       (base->getType()->isRecordType() ||
   3388        (!base->getType()->isObjCObjectPointerType() &&
   3389         idx->getType()->isRecordType()))) {
   3390     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
   3391   }
   3392 
   3393   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
   3394 }
   3395 
   3396 ExprResult
   3397 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   3398                                       Expr *Idx, SourceLocation RLoc) {
   3399   Expr *LHSExp = Base;
   3400   Expr *RHSExp = Idx;
   3401 
   3402   // Perform default conversions.
   3403   if (!LHSExp->getType()->getAs<VectorType>()) {
   3404     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
   3405     if (Result.isInvalid())
   3406       return ExprError();
   3407     LHSExp = Result.take();
   3408   }
   3409   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
   3410   if (Result.isInvalid())
   3411     return ExprError();
   3412   RHSExp = Result.take();
   3413 
   3414   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
   3415   ExprValueKind VK = VK_LValue;
   3416   ExprObjectKind OK = OK_Ordinary;
   3417 
   3418   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
   3419   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
   3420   // in the subscript position. As a result, we need to derive the array base
   3421   // and index from the expression types.
   3422   Expr *BaseExpr, *IndexExpr;
   3423   QualType ResultType;
   3424   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
   3425     BaseExpr = LHSExp;
   3426     IndexExpr = RHSExp;
   3427     ResultType = Context.DependentTy;
   3428   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
   3429     BaseExpr = LHSExp;
   3430     IndexExpr = RHSExp;
   3431     ResultType = PTy->getPointeeType();
   3432   } else if (const ObjCObjectPointerType *PTy =
   3433                LHSTy->getAs<ObjCObjectPointerType>()) {
   3434     BaseExpr = LHSExp;
   3435     IndexExpr = RHSExp;
   3436 
   3437     // Use custom logic if this should be the pseudo-object subscript
   3438     // expression.
   3439     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
   3440       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
   3441 
   3442     ResultType = PTy->getPointeeType();
   3443     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
   3444       Diag(LLoc, diag::err_subscript_nonfragile_interface)
   3445         << ResultType << BaseExpr->getSourceRange();
   3446       return ExprError();
   3447     }
   3448   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
   3449      // Handle the uncommon case of "123[Ptr]".
   3450     BaseExpr = RHSExp;
   3451     IndexExpr = LHSExp;
   3452     ResultType = PTy->getPointeeType();
   3453   } else if (const ObjCObjectPointerType *PTy =
   3454                RHSTy->getAs<ObjCObjectPointerType>()) {
   3455      // Handle the uncommon case of "123[Ptr]".
   3456     BaseExpr = RHSExp;
   3457     IndexExpr = LHSExp;
   3458     ResultType = PTy->getPointeeType();
   3459     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
   3460       Diag(LLoc, diag::err_subscript_nonfragile_interface)
   3461         << ResultType << BaseExpr->getSourceRange();
   3462       return ExprError();
   3463     }
   3464   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
   3465     BaseExpr = LHSExp;    // vectors: V[123]
   3466     IndexExpr = RHSExp;
   3467     VK = LHSExp->getValueKind();
   3468     if (VK != VK_RValue)
   3469       OK = OK_VectorComponent;
   3470 
   3471     // FIXME: need to deal with const...
   3472     ResultType = VTy->getElementType();
   3473   } else if (LHSTy->isArrayType()) {
   3474     // If we see an array that wasn't promoted by
   3475     // DefaultFunctionArrayLvalueConversion, it must be an array that
   3476     // wasn't promoted because of the C90 rule that doesn't
   3477     // allow promoting non-lvalue arrays.  Warn, then
   3478     // force the promotion here.
   3479     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   3480         LHSExp->getSourceRange();
   3481     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
   3482                                CK_ArrayToPointerDecay).take();
   3483     LHSTy = LHSExp->getType();
   3484 
   3485     BaseExpr = LHSExp;
   3486     IndexExpr = RHSExp;
   3487     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
   3488   } else if (RHSTy->isArrayType()) {
   3489     // Same as previous, except for 123[f().a] case
   3490     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   3491         RHSExp->getSourceRange();
   3492     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
   3493                                CK_ArrayToPointerDecay).take();
   3494     RHSTy = RHSExp->getType();
   3495 
   3496     BaseExpr = RHSExp;
   3497     IndexExpr = LHSExp;
   3498     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
   3499   } else {
   3500     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
   3501        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
   3502   }
   3503   // C99 6.5.2.1p1
   3504   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
   3505     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
   3506                      << IndexExpr->getSourceRange());
   3507 
   3508   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
   3509        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
   3510          && !IndexExpr->isTypeDependent())
   3511     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
   3512 
   3513   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   3514   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
   3515   // type. Note that Functions are not objects, and that (in C99 parlance)
   3516   // incomplete types are not object types.
   3517   if (ResultType->isFunctionType()) {
   3518     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
   3519       << ResultType << BaseExpr->getSourceRange();
   3520     return ExprError();
   3521   }
   3522 
   3523   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
   3524     // GNU extension: subscripting on pointer to void
   3525     Diag(LLoc, diag::ext_gnu_subscript_void_type)
   3526       << BaseExpr->getSourceRange();
   3527 
   3528     // C forbids expressions of unqualified void type from being l-values.
   3529     // See IsCForbiddenLValueType.
   3530     if (!ResultType.hasQualifiers()) VK = VK_RValue;
   3531   } else if (!ResultType->isDependentType() &&
   3532       RequireCompleteType(LLoc, ResultType,
   3533                           diag::err_subscript_incomplete_type, BaseExpr))
   3534     return ExprError();
   3535 
   3536   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
   3537          !ResultType.isCForbiddenLValueType());
   3538 
   3539   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
   3540                                                 ResultType, VK, OK, RLoc));
   3541 }
   3542 
   3543 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
   3544                                         FunctionDecl *FD,
   3545                                         ParmVarDecl *Param) {
   3546   if (Param->hasUnparsedDefaultArg()) {
   3547     Diag(CallLoc,
   3548          diag::err_use_of_default_argument_to_function_declared_later) <<
   3549       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
   3550     Diag(UnparsedDefaultArgLocs[Param],
   3551          diag::note_default_argument_declared_here);
   3552     return ExprError();
   3553   }
   3554 
   3555   if (Param->hasUninstantiatedDefaultArg()) {
   3556     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
   3557 
   3558     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
   3559                                                  Param);
   3560 
   3561     // Instantiate the expression.
   3562     MultiLevelTemplateArgumentList ArgList
   3563       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
   3564 
   3565     std::pair<const TemplateArgument *, unsigned> Innermost
   3566       = ArgList.getInnermost();
   3567     InstantiatingTemplate Inst(*this, CallLoc, Param,
   3568                                ArrayRef<TemplateArgument>(Innermost.first,
   3569                                                           Innermost.second));
   3570     if (Inst)
   3571       return ExprError();
   3572 
   3573     ExprResult Result;
   3574     {
   3575       // C++ [dcl.fct.default]p5:
   3576       //   The names in the [default argument] expression are bound, and
   3577       //   the semantic constraints are checked, at the point where the
   3578       //   default argument expression appears.
   3579       ContextRAII SavedContext(*this, FD);
   3580       LocalInstantiationScope Local(*this);
   3581       Result = SubstExpr(UninstExpr, ArgList);
   3582     }
   3583     if (Result.isInvalid())
   3584       return ExprError();
   3585 
   3586     // Check the expression as an initializer for the parameter.
   3587     InitializedEntity Entity
   3588       = InitializedEntity::InitializeParameter(Context, Param);
   3589     InitializationKind Kind
   3590       = InitializationKind::CreateCopy(Param->getLocation(),
   3591              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
   3592     Expr *ResultE = Result.takeAs<Expr>();
   3593 
   3594     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
   3595     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
   3596     if (Result.isInvalid())
   3597       return ExprError();
   3598 
   3599     Expr *Arg = Result.takeAs<Expr>();
   3600     CheckCompletedExpr(Arg, Param->getOuterLocStart());
   3601     // Build the default argument expression.
   3602     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
   3603   }
   3604 
   3605   // If the default expression creates temporaries, we need to
   3606   // push them to the current stack of expression temporaries so they'll
   3607   // be properly destroyed.
   3608   // FIXME: We should really be rebuilding the default argument with new
   3609   // bound temporaries; see the comment in PR5810.
   3610   // We don't need to do that with block decls, though, because
   3611   // blocks in default argument expression can never capture anything.
   3612   if (isa<ExprWithCleanups>(Param->getInit())) {
   3613     // Set the "needs cleanups" bit regardless of whether there are
   3614     // any explicit objects.
   3615     ExprNeedsCleanups = true;
   3616 
   3617     // Append all the objects to the cleanup list.  Right now, this
   3618     // should always be a no-op, because blocks in default argument
   3619     // expressions should never be able to capture anything.
   3620     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
   3621            "default argument expression has capturing blocks?");
   3622   }
   3623 
   3624   // We already type-checked the argument, so we know it works.
   3625   // Just mark all of the declarations in this potentially-evaluated expression
   3626   // as being "referenced".
   3627   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
   3628                                    /*SkipLocalVariables=*/true);
   3629   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
   3630 }
   3631 
   3632 
   3633 Sema::VariadicCallType
   3634 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
   3635                           Expr *Fn) {
   3636   if (Proto && Proto->isVariadic()) {
   3637     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
   3638       return VariadicConstructor;
   3639     else if (Fn && Fn->getType()->isBlockPointerType())
   3640       return VariadicBlock;
   3641     else if (FDecl) {
   3642       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
   3643         if (Method->isInstance())
   3644           return VariadicMethod;
   3645     }
   3646     return VariadicFunction;
   3647   }
   3648   return VariadicDoesNotApply;
   3649 }
   3650 
   3651 /// ConvertArgumentsForCall - Converts the arguments specified in
   3652 /// Args/NumArgs to the parameter types of the function FDecl with
   3653 /// function prototype Proto. Call is the call expression itself, and
   3654 /// Fn is the function expression. For a C++ member function, this
   3655 /// routine does not attempt to convert the object argument. Returns
   3656 /// true if the call is ill-formed.
   3657 bool
   3658 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
   3659                               FunctionDecl *FDecl,
   3660                               const FunctionProtoType *Proto,
   3661                               Expr **Args, unsigned NumArgs,
   3662                               SourceLocation RParenLoc,
   3663                               bool IsExecConfig) {
   3664   // Bail out early if calling a builtin with custom typechecking.
   3665   // We don't need to do this in the
   3666   if (FDecl)
   3667     if (unsigned ID = FDecl->getBuiltinID())
   3668       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
   3669         return false;
   3670 
   3671   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
   3672   // assignment, to the types of the corresponding parameter, ...
   3673   unsigned NumArgsInProto = Proto->getNumArgs();
   3674   bool Invalid = false;
   3675   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
   3676   unsigned FnKind = Fn->getType()->isBlockPointerType()
   3677                        ? 1 /* block */
   3678                        : (IsExecConfig ? 3 /* kernel function (exec config) */
   3679                                        : 0 /* function */);
   3680 
   3681   // If too few arguments are available (and we don't have default
   3682   // arguments for the remaining parameters), don't make the call.
   3683   if (NumArgs < NumArgsInProto) {
   3684     if (NumArgs < MinArgs) {
   3685       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
   3686         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
   3687                           ? diag::err_typecheck_call_too_few_args_one
   3688                           : diag::err_typecheck_call_too_few_args_at_least_one)
   3689           << FnKind
   3690           << FDecl->getParamDecl(0) << Fn->getSourceRange();
   3691       else
   3692         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
   3693                           ? diag::err_typecheck_call_too_few_args
   3694                           : diag::err_typecheck_call_too_few_args_at_least)
   3695           << FnKind
   3696           << MinArgs << NumArgs << Fn->getSourceRange();
   3697 
   3698       // Emit the location of the prototype.
   3699       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   3700         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   3701           << FDecl;
   3702 
   3703       return true;
   3704     }
   3705     Call->setNumArgs(Context, NumArgsInProto);
   3706   }
   3707 
   3708   // If too many are passed and not variadic, error on the extras and drop
   3709   // them.
   3710   if (NumArgs > NumArgsInProto) {
   3711     if (!Proto->isVariadic()) {
   3712       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
   3713         Diag(Args[NumArgsInProto]->getLocStart(),
   3714              MinArgs == NumArgsInProto
   3715                ? diag::err_typecheck_call_too_many_args_one
   3716                : diag::err_typecheck_call_too_many_args_at_most_one)
   3717           << FnKind
   3718           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
   3719           << SourceRange(Args[NumArgsInProto]->getLocStart(),
   3720                          Args[NumArgs-1]->getLocEnd());
   3721       else
   3722         Diag(Args[NumArgsInProto]->getLocStart(),
   3723              MinArgs == NumArgsInProto
   3724                ? diag::err_typecheck_call_too_many_args
   3725                : diag::err_typecheck_call_too_many_args_at_most)
   3726           << FnKind
   3727           << NumArgsInProto << NumArgs << Fn->getSourceRange()
   3728           << SourceRange(Args[NumArgsInProto]->getLocStart(),
   3729                          Args[NumArgs-1]->getLocEnd());
   3730 
   3731       // Emit the location of the prototype.
   3732       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   3733         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   3734           << FDecl;
   3735 
   3736       // This deletes the extra arguments.
   3737       Call->setNumArgs(Context, NumArgsInProto);
   3738       return true;
   3739     }
   3740   }
   3741   SmallVector<Expr *, 8> AllArgs;
   3742   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
   3743 
   3744   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
   3745                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
   3746   if (Invalid)
   3747     return true;
   3748   unsigned TotalNumArgs = AllArgs.size();
   3749   for (unsigned i = 0; i < TotalNumArgs; ++i)
   3750     Call->setArg(i, AllArgs[i]);
   3751 
   3752   return false;
   3753 }
   3754 
   3755 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
   3756                                   FunctionDecl *FDecl,
   3757                                   const FunctionProtoType *Proto,
   3758                                   unsigned FirstProtoArg,
   3759                                   Expr **Args, unsigned NumArgs,
   3760                                   SmallVector<Expr *, 8> &AllArgs,
   3761                                   VariadicCallType CallType,
   3762                                   bool AllowExplicit,
   3763                                   bool IsListInitialization) {
   3764   unsigned NumArgsInProto = Proto->getNumArgs();
   3765   unsigned NumArgsToCheck = NumArgs;
   3766   bool Invalid = false;
   3767   if (NumArgs != NumArgsInProto)
   3768     // Use default arguments for missing arguments
   3769     NumArgsToCheck = NumArgsInProto;
   3770   unsigned ArgIx = 0;
   3771   // Continue to check argument types (even if we have too few/many args).
   3772   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
   3773     QualType ProtoArgType = Proto->getArgType(i);
   3774 
   3775     Expr *Arg;
   3776     ParmVarDecl *Param;
   3777     if (ArgIx < NumArgs) {
   3778       Arg = Args[ArgIx++];
   3779 
   3780       if (RequireCompleteType(Arg->getLocStart(),
   3781                               ProtoArgType,
   3782                               diag::err_call_incomplete_argument, Arg))
   3783         return true;
   3784 
   3785       // Pass the argument
   3786       Param = 0;
   3787       if (FDecl && i < FDecl->getNumParams())
   3788         Param = FDecl->getParamDecl(i);
   3789 
   3790       // Strip the unbridged-cast placeholder expression off, if applicable.
   3791       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
   3792           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
   3793           (!Param || !Param->hasAttr<CFConsumedAttr>()))
   3794         Arg = stripARCUnbridgedCast(Arg);
   3795 
   3796       InitializedEntity Entity = Param ?
   3797           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
   3798         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
   3799                                                  Proto->isArgConsumed(i));
   3800       ExprResult ArgE = PerformCopyInitialization(Entity,
   3801                                                   SourceLocation(),
   3802                                                   Owned(Arg),
   3803                                                   IsListInitialization,
   3804                                                   AllowExplicit);
   3805       if (ArgE.isInvalid())
   3806         return true;
   3807 
   3808       Arg = ArgE.takeAs<Expr>();
   3809     } else {
   3810       assert(FDecl && "can't use default arguments without a known callee");
   3811       Param = FDecl->getParamDecl(i);
   3812 
   3813       ExprResult ArgExpr =
   3814         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
   3815       if (ArgExpr.isInvalid())
   3816         return true;
   3817 
   3818       Arg = ArgExpr.takeAs<Expr>();
   3819     }
   3820 
   3821     // Check for array bounds violations for each argument to the call. This
   3822     // check only triggers warnings when the argument isn't a more complex Expr
   3823     // with its own checking, such as a BinaryOperator.
   3824     CheckArrayAccess(Arg);
   3825 
   3826     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
   3827     CheckStaticArrayArgument(CallLoc, Param, Arg);
   3828 
   3829     AllArgs.push_back(Arg);
   3830   }
   3831 
   3832   // If this is a variadic call, handle args passed through "...".
   3833   if (CallType != VariadicDoesNotApply) {
   3834     // Assume that extern "C" functions with variadic arguments that
   3835     // return __unknown_anytype aren't *really* variadic.
   3836     if (Proto->getResultType() == Context.UnknownAnyTy &&
   3837         FDecl && FDecl->isExternC()) {
   3838       for (unsigned i = ArgIx; i != NumArgs; ++i) {
   3839         QualType paramType; // ignored
   3840         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
   3841         Invalid |= arg.isInvalid();
   3842         AllArgs.push_back(arg.take());
   3843       }
   3844 
   3845     // Otherwise do argument promotion, (C99 6.5.2.2p7).
   3846     } else {
   3847       for (unsigned i = ArgIx; i != NumArgs; ++i) {
   3848         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
   3849                                                           FDecl);
   3850         Invalid |= Arg.isInvalid();
   3851         AllArgs.push_back(Arg.take());
   3852       }
   3853     }
   3854 
   3855     // Check for array bounds violations.
   3856     for (unsigned i = ArgIx; i != NumArgs; ++i)
   3857       CheckArrayAccess(Args[i]);
   3858   }
   3859   return Invalid;
   3860 }
   3861 
   3862 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
   3863   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
   3864   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
   3865     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
   3866       << ATL.getLocalSourceRange();
   3867 }
   3868 
   3869 /// CheckStaticArrayArgument - If the given argument corresponds to a static
   3870 /// array parameter, check that it is non-null, and that if it is formed by
   3871 /// array-to-pointer decay, the underlying array is sufficiently large.
   3872 ///
   3873 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
   3874 /// array type derivation, then for each call to the function, the value of the
   3875 /// corresponding actual argument shall provide access to the first element of
   3876 /// an array with at least as many elements as specified by the size expression.
   3877 void
   3878 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
   3879                                ParmVarDecl *Param,
   3880                                const Expr *ArgExpr) {
   3881   // Static array parameters are not supported in C++.
   3882   if (!Param || getLangOpts().CPlusPlus)
   3883     return;
   3884 
   3885   QualType OrigTy = Param->getOriginalType();
   3886 
   3887   const ArrayType *AT = Context.getAsArrayType(OrigTy);
   3888   if (!AT || AT->getSizeModifier() != ArrayType::Static)
   3889     return;
   3890 
   3891