clang API Documentation

SemaExpr.cpp
Go to the documentation of this file.
00001 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "TreeTransform.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/ASTLambda.h"
00019 #include "clang/AST/ASTMutationListener.h"
00020 #include "clang/AST/CXXInheritance.h"
00021 #include "clang/AST/DeclObjC.h"
00022 #include "clang/AST/DeclTemplate.h"
00023 #include "clang/AST/EvaluatedExprVisitor.h"
00024 #include "clang/AST/Expr.h"
00025 #include "clang/AST/ExprCXX.h"
00026 #include "clang/AST/ExprObjC.h"
00027 #include "clang/AST/RecursiveASTVisitor.h"
00028 #include "clang/AST/TypeLoc.h"
00029 #include "clang/Basic/PartialDiagnostic.h"
00030 #include "clang/Basic/SourceManager.h"
00031 #include "clang/Basic/TargetInfo.h"
00032 #include "clang/Lex/LiteralSupport.h"
00033 #include "clang/Lex/Preprocessor.h"
00034 #include "clang/Sema/AnalysisBasedWarnings.h"
00035 #include "clang/Sema/DeclSpec.h"
00036 #include "clang/Sema/DelayedDiagnostic.h"
00037 #include "clang/Sema/Designator.h"
00038 #include "clang/Sema/Initialization.h"
00039 #include "clang/Sema/Lookup.h"
00040 #include "clang/Sema/ParsedTemplate.h"
00041 #include "clang/Sema/Scope.h"
00042 #include "clang/Sema/ScopeInfo.h"
00043 #include "clang/Sema/SemaFixItUtils.h"
00044 #include "clang/Sema/Template.h"
00045 #include "llvm/Support/ConvertUTF.h"
00046 using namespace clang;
00047 using namespace sema;
00048 
00049 /// \brief Determine whether the use of this declaration is valid, without
00050 /// emitting diagnostics.
00051 bool Sema::CanUseDecl(NamedDecl *D) {
00052   // See if this is an auto-typed variable whose initializer we are parsing.
00053   if (ParsingInitForAutoVars.count(D))
00054     return false;
00055 
00056   // See if this is a deleted function.
00057   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00058     if (FD->isDeleted())
00059       return false;
00060 
00061     // If the function has a deduced return type, and we can't deduce it,
00062     // then we can't use it either.
00063     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
00064         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
00065       return false;
00066   }
00067 
00068   // See if this function is unavailable.
00069   if (D->getAvailability() == AR_Unavailable &&
00070       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
00071     return false;
00072 
00073   return true;
00074 }
00075 
00076 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
00077   // Warn if this is used but marked unused.
00078   if (D->hasAttr<UnusedAttr>()) {
00079     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
00080     if (!DC->hasAttr<UnusedAttr>())
00081       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
00082   }
00083 }
00084 
00085 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
00086                               NamedDecl *D, SourceLocation Loc,
00087                               const ObjCInterfaceDecl *UnknownObjCClass,
00088                               bool ObjCPropertyAccess) {
00089   // See if this declaration is unavailable or deprecated.
00090   std::string Message;
00091     
00092   // Forward class declarations get their attributes from their definition.
00093   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
00094     if (IDecl->getDefinition())
00095       D = IDecl->getDefinition();
00096   }
00097   AvailabilityResult Result = D->getAvailability(&Message);
00098   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
00099     if (Result == AR_Available) {
00100       const DeclContext *DC = ECD->getDeclContext();
00101       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
00102         Result = TheEnumDecl->getAvailability(&Message);
00103     }
00104 
00105   const ObjCPropertyDecl *ObjCPDecl = nullptr;
00106   if (Result == AR_Deprecated || Result == AR_Unavailable) {
00107     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00108       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
00109         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
00110         if (PDeclResult == Result)
00111           ObjCPDecl = PD;
00112       }
00113     }
00114   }
00115   
00116   switch (Result) {
00117     case AR_Available:
00118     case AR_NotYetIntroduced:
00119       break;
00120             
00121     case AR_Deprecated:
00122       if (S.getCurContextAvailability() != AR_Deprecated)
00123         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
00124                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
00125                                   ObjCPropertyAccess);
00126       break;
00127 
00128     case AR_Unavailable:
00129       if (S.getCurContextAvailability() != AR_Unavailable)
00130         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
00131                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
00132                                   ObjCPropertyAccess);
00133       break;
00134 
00135     }
00136     return Result;
00137 }
00138 
00139 /// \brief Emit a note explaining that this function is deleted.
00140 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
00141   assert(Decl->isDeleted());
00142 
00143   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
00144 
00145   if (Method && Method->isDeleted() && Method->isDefaulted()) {
00146     // If the method was explicitly defaulted, point at that declaration.
00147     if (!Method->isImplicit())
00148       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
00149 
00150     // Try to diagnose why this special member function was implicitly
00151     // deleted. This might fail, if that reason no longer applies.
00152     CXXSpecialMember CSM = getSpecialMember(Method);
00153     if (CSM != CXXInvalid)
00154       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
00155 
00156     return;
00157   }
00158 
00159   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
00160     if (CXXConstructorDecl *BaseCD =
00161             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
00162       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
00163       if (BaseCD->isDeleted()) {
00164         NoteDeletedFunction(BaseCD);
00165       } else {
00166         // FIXME: An explanation of why exactly it can't be inherited
00167         // would be nice.
00168         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
00169       }
00170       return;
00171     }
00172   }
00173 
00174   Diag(Decl->getLocation(), diag::note_availability_specified_here)
00175     << Decl << true;
00176 }
00177 
00178 /// \brief Determine whether a FunctionDecl was ever declared with an
00179 /// explicit storage class.
00180 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
00181   for (auto I : D->redecls()) {
00182     if (I->getStorageClass() != SC_None)
00183       return true;
00184   }
00185   return false;
00186 }
00187 
00188 /// \brief Check whether we're in an extern inline function and referring to a
00189 /// variable or function with internal linkage (C11 6.7.4p3).
00190 ///
00191 /// This is only a warning because we used to silently accept this code, but
00192 /// in many cases it will not behave correctly. This is not enabled in C++ mode
00193 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
00194 /// and so while there may still be user mistakes, most of the time we can't
00195 /// prove that there are errors.
00196 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
00197                                                       const NamedDecl *D,
00198                                                       SourceLocation Loc) {
00199   // This is disabled under C++; there are too many ways for this to fire in
00200   // contexts where the warning is a false positive, or where it is technically
00201   // correct but benign.
00202   if (S.getLangOpts().CPlusPlus)
00203     return;
00204 
00205   // Check if this is an inlined function or method.
00206   FunctionDecl *Current = S.getCurFunctionDecl();
00207   if (!Current)
00208     return;
00209   if (!Current->isInlined())
00210     return;
00211   if (!Current->isExternallyVisible())
00212     return;
00213 
00214   // Check if the decl has internal linkage.
00215   if (D->getFormalLinkage() != InternalLinkage)
00216     return;
00217 
00218   // Downgrade from ExtWarn to Extension if
00219   //  (1) the supposedly external inline function is in the main file,
00220   //      and probably won't be included anywhere else.
00221   //  (2) the thing we're referencing is a pure function.
00222   //  (3) the thing we're referencing is another inline function.
00223   // This last can give us false negatives, but it's better than warning on
00224   // wrappers for simple C library functions.
00225   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
00226   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
00227   if (!DowngradeWarning && UsedFn)
00228     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
00229 
00230   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
00231                                : diag::ext_internal_in_extern_inline)
00232     << /*IsVar=*/!UsedFn << D;
00233 
00234   S.MaybeSuggestAddingStaticToDecl(Current);
00235 
00236   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
00237       << D;
00238 }
00239 
00240 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
00241   const FunctionDecl *First = Cur->getFirstDecl();
00242 
00243   // Suggest "static" on the function, if possible.
00244   if (!hasAnyExplicitStorageClass(First)) {
00245     SourceLocation DeclBegin = First->getSourceRange().getBegin();
00246     Diag(DeclBegin, diag::note_convert_inline_to_static)
00247       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
00248   }
00249 }
00250 
00251 /// \brief Determine whether the use of this declaration is valid, and
00252 /// emit any corresponding diagnostics.
00253 ///
00254 /// This routine diagnoses various problems with referencing
00255 /// declarations that can occur when using a declaration. For example,
00256 /// it might warn if a deprecated or unavailable declaration is being
00257 /// used, or produce an error (and return true) if a C++0x deleted
00258 /// function is being used.
00259 ///
00260 /// \returns true if there was an error (this declaration cannot be
00261 /// referenced), false otherwise.
00262 ///
00263 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
00264                              const ObjCInterfaceDecl *UnknownObjCClass,
00265                              bool ObjCPropertyAccess) {
00266   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
00267     // If there were any diagnostics suppressed by template argument deduction,
00268     // emit them now.
00269     SuppressedDiagnosticsMap::iterator
00270       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
00271     if (Pos != SuppressedDiagnostics.end()) {
00272       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
00273       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
00274         Diag(Suppressed[I].first, Suppressed[I].second);
00275 
00276       // Clear out the list of suppressed diagnostics, so that we don't emit
00277       // them again for this specialization. However, we don't obsolete this
00278       // entry from the table, because we want to avoid ever emitting these
00279       // diagnostics again.
00280       Suppressed.clear();
00281     }
00282 
00283     // C++ [basic.start.main]p3:
00284     //   The function 'main' shall not be used within a program.
00285     if (cast<FunctionDecl>(D)->isMain())
00286       Diag(Loc, diag::ext_main_used);
00287   }
00288 
00289   // See if this is an auto-typed variable whose initializer we are parsing.
00290   if (ParsingInitForAutoVars.count(D)) {
00291     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
00292       << D->getDeclName();
00293     return true;
00294   }
00295 
00296   // See if this is a deleted function.
00297   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00298     if (FD->isDeleted()) {
00299       Diag(Loc, diag::err_deleted_function_use);
00300       NoteDeletedFunction(FD);
00301       return true;
00302     }
00303 
00304     // If the function has a deduced return type, and we can't deduce it,
00305     // then we can't use it either.
00306     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
00307         DeduceReturnType(FD, Loc))
00308       return true;
00309   }
00310   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
00311 
00312   DiagnoseUnusedOfDecl(*this, D, Loc);
00313 
00314   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
00315 
00316   return false;
00317 }
00318 
00319 /// \brief Retrieve the message suffix that should be added to a
00320 /// diagnostic complaining about the given function being deleted or
00321 /// unavailable.
00322 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
00323   std::string Message;
00324   if (FD->getAvailability(&Message))
00325     return ": " + Message;
00326 
00327   return std::string();
00328 }
00329 
00330 /// DiagnoseSentinelCalls - This routine checks whether a call or
00331 /// message-send is to a declaration with the sentinel attribute, and
00332 /// if so, it checks that the requirements of the sentinel are
00333 /// satisfied.
00334 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
00335                                  ArrayRef<Expr *> Args) {
00336   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
00337   if (!attr)
00338     return;
00339 
00340   // The number of formal parameters of the declaration.
00341   unsigned numFormalParams;
00342 
00343   // The kind of declaration.  This is also an index into a %select in
00344   // the diagnostic.
00345   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
00346 
00347   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00348     numFormalParams = MD->param_size();
00349     calleeType = CT_Method;
00350   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00351     numFormalParams = FD->param_size();
00352     calleeType = CT_Function;
00353   } else if (isa<VarDecl>(D)) {
00354     QualType type = cast<ValueDecl>(D)->getType();
00355     const FunctionType *fn = nullptr;
00356     if (const PointerType *ptr = type->getAs<PointerType>()) {
00357       fn = ptr->getPointeeType()->getAs<FunctionType>();
00358       if (!fn) return;
00359       calleeType = CT_Function;
00360     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
00361       fn = ptr->getPointeeType()->castAs<FunctionType>();
00362       calleeType = CT_Block;
00363     } else {
00364       return;
00365     }
00366 
00367     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
00368       numFormalParams = proto->getNumParams();
00369     } else {
00370       numFormalParams = 0;
00371     }
00372   } else {
00373     return;
00374   }
00375 
00376   // "nullPos" is the number of formal parameters at the end which
00377   // effectively count as part of the variadic arguments.  This is
00378   // useful if you would prefer to not have *any* formal parameters,
00379   // but the language forces you to have at least one.
00380   unsigned nullPos = attr->getNullPos();
00381   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
00382   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
00383 
00384   // The number of arguments which should follow the sentinel.
00385   unsigned numArgsAfterSentinel = attr->getSentinel();
00386 
00387   // If there aren't enough arguments for all the formal parameters,
00388   // the sentinel, and the args after the sentinel, complain.
00389   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
00390     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00391     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
00392     return;
00393   }
00394 
00395   // Otherwise, find the sentinel expression.
00396   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
00397   if (!sentinelExpr) return;
00398   if (sentinelExpr->isValueDependent()) return;
00399   if (Context.isSentinelNullExpr(sentinelExpr)) return;
00400 
00401   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
00402   // or 'NULL' if those are actually defined in the context.  Only use
00403   // 'nil' for ObjC methods, where it's much more likely that the
00404   // variadic arguments form a list of object pointers.
00405   SourceLocation MissingNilLoc
00406     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
00407   std::string NullValue;
00408   if (calleeType == CT_Method &&
00409       PP.getIdentifierInfo("nil")->hasMacroDefinition())
00410     NullValue = "nil";
00411   else if (getLangOpts().CPlusPlus11)
00412     NullValue = "nullptr";
00413   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
00414     NullValue = "NULL";
00415   else
00416     NullValue = "(void*) 0";
00417 
00418   if (MissingNilLoc.isInvalid())
00419     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
00420   else
00421     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
00422       << int(calleeType)
00423       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
00424   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
00425 }
00426 
00427 SourceRange Sema::getExprRange(Expr *E) const {
00428   return E ? E->getSourceRange() : SourceRange();
00429 }
00430 
00431 //===----------------------------------------------------------------------===//
00432 //  Standard Promotions and Conversions
00433 //===----------------------------------------------------------------------===//
00434 
00435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
00436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
00437   // Handle any placeholder expressions which made it here.
00438   if (E->getType()->isPlaceholderType()) {
00439     ExprResult result = CheckPlaceholderExpr(E);
00440     if (result.isInvalid()) return ExprError();
00441     E = result.get();
00442   }
00443   
00444   QualType Ty = E->getType();
00445   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
00446 
00447   if (Ty->isFunctionType()) {
00448     // If we are here, we are not calling a function but taking
00449     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
00450     if (getLangOpts().OpenCL) {
00451       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
00452       return ExprError();
00453     }
00454     E = ImpCastExprToType(E, Context.getPointerType(Ty),
00455                           CK_FunctionToPointerDecay).get();
00456   } else if (Ty->isArrayType()) {
00457     // In C90 mode, arrays only promote to pointers if the array expression is
00458     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
00459     // type 'array of type' is converted to an expression that has type 'pointer
00460     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
00461     // that has type 'array of type' ...".  The relevant change is "an lvalue"
00462     // (C90) to "an expression" (C99).
00463     //
00464     // C++ 4.2p1:
00465     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
00466     // T" can be converted to an rvalue of type "pointer to T".
00467     //
00468     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
00469       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
00470                             CK_ArrayToPointerDecay).get();
00471   }
00472   return E;
00473 }
00474 
00475 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
00476   // Check to see if we are dereferencing a null pointer.  If so,
00477   // and if not volatile-qualified, this is undefined behavior that the
00478   // optimizer will delete, so warn about it.  People sometimes try to use this
00479   // to get a deterministic trap and are surprised by clang's behavior.  This
00480   // only handles the pattern "*null", which is a very syntactic check.
00481   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
00482     if (UO->getOpcode() == UO_Deref &&
00483         UO->getSubExpr()->IgnoreParenCasts()->
00484           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
00485         !UO->getType().isVolatileQualified()) {
00486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
00487                           S.PDiag(diag::warn_indirection_through_null)
00488                             << UO->getSubExpr()->getSourceRange());
00489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
00490                         S.PDiag(diag::note_indirection_through_null));
00491   }
00492 }
00493 
00494 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
00495                                     SourceLocation AssignLoc,
00496                                     const Expr* RHS) {
00497   const ObjCIvarDecl *IV = OIRE->getDecl();
00498   if (!IV)
00499     return;
00500   
00501   DeclarationName MemberName = IV->getDeclName();
00502   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
00503   if (!Member || !Member->isStr("isa"))
00504     return;
00505   
00506   const Expr *Base = OIRE->getBase();
00507   QualType BaseType = Base->getType();
00508   if (OIRE->isArrow())
00509     BaseType = BaseType->getPointeeType();
00510   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
00511     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
00512       ObjCInterfaceDecl *ClassDeclared = nullptr;
00513       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
00514       if (!ClassDeclared->getSuperClass()
00515           && (*ClassDeclared->ivar_begin()) == IV) {
00516         if (RHS) {
00517           NamedDecl *ObjectSetClass =
00518             S.LookupSingleName(S.TUScope,
00519                                &S.Context.Idents.get("object_setClass"),
00520                                SourceLocation(), S.LookupOrdinaryName);
00521           if (ObjectSetClass) {
00522             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
00523             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
00524             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
00525             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
00526                                                      AssignLoc), ",") <<
00527             FixItHint::CreateInsertion(RHSLocEnd, ")");
00528           }
00529           else
00530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
00531         } else {
00532           NamedDecl *ObjectGetClass =
00533             S.LookupSingleName(S.TUScope,
00534                                &S.Context.Idents.get("object_getClass"),
00535                                SourceLocation(), S.LookupOrdinaryName);
00536           if (ObjectGetClass)
00537             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
00538             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
00539             FixItHint::CreateReplacement(
00540                                          SourceRange(OIRE->getOpLoc(),
00541                                                      OIRE->getLocEnd()), ")");
00542           else
00543             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
00544         }
00545         S.Diag(IV->getLocation(), diag::note_ivar_decl);
00546       }
00547     }
00548 }
00549 
00550 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
00551   // Handle any placeholder expressions which made it here.
00552   if (E->getType()->isPlaceholderType()) {
00553     ExprResult result = CheckPlaceholderExpr(E);
00554     if (result.isInvalid()) return ExprError();
00555     E = result.get();
00556   }
00557   
00558   // C++ [conv.lval]p1:
00559   //   A glvalue of a non-function, non-array type T can be
00560   //   converted to a prvalue.
00561   if (!E->isGLValue()) return E;
00562 
00563   QualType T = E->getType();
00564   assert(!T.isNull() && "r-value conversion on typeless expression?");
00565 
00566   // We don't want to throw lvalue-to-rvalue casts on top of
00567   // expressions of certain types in C++.
00568   if (getLangOpts().CPlusPlus &&
00569       (E->getType() == Context.OverloadTy ||
00570        T->isDependentType() ||
00571        T->isRecordType()))
00572     return E;
00573 
00574   // The C standard is actually really unclear on this point, and
00575   // DR106 tells us what the result should be but not why.  It's
00576   // generally best to say that void types just doesn't undergo
00577   // lvalue-to-rvalue at all.  Note that expressions of unqualified
00578   // 'void' type are never l-values, but qualified void can be.
00579   if (T->isVoidType())
00580     return E;
00581 
00582   // OpenCL usually rejects direct accesses to values of 'half' type.
00583   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
00584       T->isHalfType()) {
00585     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
00586       << 0 << T;
00587     return ExprError();
00588   }
00589 
00590   CheckForNullPointerDereference(*this, E);
00591   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
00592     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
00593                                      &Context.Idents.get("object_getClass"),
00594                                      SourceLocation(), LookupOrdinaryName);
00595     if (ObjectGetClass)
00596       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
00597         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
00598         FixItHint::CreateReplacement(
00599                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
00600     else
00601       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
00602   }
00603   else if (const ObjCIvarRefExpr *OIRE =
00604             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
00605     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
00606 
00607   // C++ [conv.lval]p1:
00608   //   [...] If T is a non-class type, the type of the prvalue is the
00609   //   cv-unqualified version of T. Otherwise, the type of the
00610   //   rvalue is T.
00611   //
00612   // C99 6.3.2.1p2:
00613   //   If the lvalue has qualified type, the value has the unqualified
00614   //   version of the type of the lvalue; otherwise, the value has the
00615   //   type of the lvalue.
00616   if (T.hasQualifiers())
00617     T = T.getUnqualifiedType();
00618 
00619   UpdateMarkingForLValueToRValue(E);
00620   
00621   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
00622   // balance that.
00623   if (getLangOpts().ObjCAutoRefCount &&
00624       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
00625     ExprNeedsCleanups = true;
00626 
00627   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
00628                                             nullptr, VK_RValue);
00629 
00630   // C11 6.3.2.1p2:
00631   //   ... if the lvalue has atomic type, the value has the non-atomic version 
00632   //   of the type of the lvalue ...
00633   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
00634     T = Atomic->getValueType().getUnqualifiedType();
00635     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
00636                                    nullptr, VK_RValue);
00637   }
00638   
00639   return Res;
00640 }
00641 
00642 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
00643   ExprResult Res = DefaultFunctionArrayConversion(E);
00644   if (Res.isInvalid())
00645     return ExprError();
00646   Res = DefaultLvalueConversion(Res.get());
00647   if (Res.isInvalid())
00648     return ExprError();
00649   return Res;
00650 }
00651 
00652 /// CallExprUnaryConversions - a special case of an unary conversion
00653 /// performed on a function designator of a call expression.
00654 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
00655   QualType Ty = E->getType();
00656   ExprResult Res = E;
00657   // Only do implicit cast for a function type, but not for a pointer
00658   // to function type.
00659   if (Ty->isFunctionType()) {
00660     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
00661                             CK_FunctionToPointerDecay).get();
00662     if (Res.isInvalid())
00663       return ExprError();
00664   }
00665   Res = DefaultLvalueConversion(Res.get());
00666   if (Res.isInvalid())
00667     return ExprError();
00668   return Res.get();
00669 }
00670 
00671 /// UsualUnaryConversions - Performs various conversions that are common to most
00672 /// operators (C99 6.3). The conversions of array and function types are
00673 /// sometimes suppressed. For example, the array->pointer conversion doesn't
00674 /// apply if the array is an argument to the sizeof or address (&) operators.
00675 /// In these instances, this routine should *not* be called.
00676 ExprResult Sema::UsualUnaryConversions(Expr *E) {
00677   // First, convert to an r-value.
00678   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
00679   if (Res.isInvalid())
00680     return ExprError();
00681   E = Res.get();
00682 
00683   QualType Ty = E->getType();
00684   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
00685 
00686   // Half FP have to be promoted to float unless it is natively supported
00687   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
00688     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
00689 
00690   // Try to perform integral promotions if the object has a theoretically
00691   // promotable type.
00692   if (Ty->isIntegralOrUnscopedEnumerationType()) {
00693     // C99 6.3.1.1p2:
00694     //
00695     //   The following may be used in an expression wherever an int or
00696     //   unsigned int may be used:
00697     //     - an object or expression with an integer type whose integer
00698     //       conversion rank is less than or equal to the rank of int
00699     //       and unsigned int.
00700     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
00701     //
00702     //   If an int can represent all values of the original type, the
00703     //   value is converted to an int; otherwise, it is converted to an
00704     //   unsigned int. These are called the integer promotions. All
00705     //   other types are unchanged by the integer promotions.
00706 
00707     QualType PTy = Context.isPromotableBitField(E);
00708     if (!PTy.isNull()) {
00709       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
00710       return E;
00711     }
00712     if (Ty->isPromotableIntegerType()) {
00713       QualType PT = Context.getPromotedIntegerType(Ty);
00714       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
00715       return E;
00716     }
00717   }
00718   return E;
00719 }
00720 
00721 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
00722 /// do not have a prototype. Arguments that have type float or __fp16
00723 /// are promoted to double. All other argument types are converted by
00724 /// UsualUnaryConversions().
00725 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
00726   QualType Ty = E->getType();
00727   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
00728 
00729   ExprResult Res = UsualUnaryConversions(E);
00730   if (Res.isInvalid())
00731     return ExprError();
00732   E = Res.get();
00733 
00734   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
00735   // double.
00736   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
00737   if (BTy && (BTy->getKind() == BuiltinType::Half ||
00738               BTy->getKind() == BuiltinType::Float))
00739     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
00740 
00741   // C++ performs lvalue-to-rvalue conversion as a default argument
00742   // promotion, even on class types, but note:
00743   //   C++11 [conv.lval]p2:
00744   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
00745   //     operand or a subexpression thereof the value contained in the
00746   //     referenced object is not accessed. Otherwise, if the glvalue
00747   //     has a class type, the conversion copy-initializes a temporary
00748   //     of type T from the glvalue and the result of the conversion
00749   //     is a prvalue for the temporary.
00750   // FIXME: add some way to gate this entire thing for correctness in
00751   // potentially potentially evaluated contexts.
00752   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
00753     ExprResult Temp = PerformCopyInitialization(
00754                        InitializedEntity::InitializeTemporary(E->getType()),
00755                                                 E->getExprLoc(), E);
00756     if (Temp.isInvalid())
00757       return ExprError();
00758     E = Temp.get();
00759   }
00760 
00761   return E;
00762 }
00763 
00764 /// Determine the degree of POD-ness for an expression.
00765 /// Incomplete types are considered POD, since this check can be performed
00766 /// when we're in an unevaluated context.
00767 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
00768   if (Ty->isIncompleteType()) {
00769     // C++11 [expr.call]p7:
00770     //   After these conversions, if the argument does not have arithmetic,
00771     //   enumeration, pointer, pointer to member, or class type, the program
00772     //   is ill-formed.
00773     //
00774     // Since we've already performed array-to-pointer and function-to-pointer
00775     // decay, the only such type in C++ is cv void. This also handles
00776     // initializer lists as variadic arguments.
00777     if (Ty->isVoidType())
00778       return VAK_Invalid;
00779 
00780     if (Ty->isObjCObjectType())
00781       return VAK_Invalid;
00782     return VAK_Valid;
00783   }
00784 
00785   if (Ty.isCXX98PODType(Context))
00786     return VAK_Valid;
00787 
00788   // C++11 [expr.call]p7:
00789   //   Passing a potentially-evaluated argument of class type (Clause 9)
00790   //   having a non-trivial copy constructor, a non-trivial move constructor,
00791   //   or a non-trivial destructor, with no corresponding parameter,
00792   //   is conditionally-supported with implementation-defined semantics.
00793   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
00794     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
00795       if (!Record->hasNonTrivialCopyConstructor() &&
00796           !Record->hasNonTrivialMoveConstructor() &&
00797           !Record->hasNonTrivialDestructor())
00798         return VAK_ValidInCXX11;
00799 
00800   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
00801     return VAK_Valid;
00802 
00803   if (Ty->isObjCObjectType())
00804     return VAK_Invalid;
00805 
00806   if (getLangOpts().MSVCCompat)
00807     return VAK_MSVCUndefined;
00808 
00809   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
00810   // permitted to reject them. We should consider doing so.
00811   return VAK_Undefined;
00812 }
00813 
00814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
00815   // Don't allow one to pass an Objective-C interface to a vararg.
00816   const QualType &Ty = E->getType();
00817   VarArgKind VAK = isValidVarArgType(Ty);
00818 
00819   // Complain about passing non-POD types through varargs.
00820   switch (VAK) {
00821   case VAK_ValidInCXX11:
00822     DiagRuntimeBehavior(
00823         E->getLocStart(), nullptr,
00824         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
00825           << Ty << CT);
00826     // Fall through.
00827   case VAK_Valid:
00828     if (Ty->isRecordType()) {
00829       // This is unlikely to be what the user intended. If the class has a
00830       // 'c_str' member function, the user probably meant to call that.
00831       DiagRuntimeBehavior(E->getLocStart(), nullptr,
00832                           PDiag(diag::warn_pass_class_arg_to_vararg)
00833                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
00834     }
00835     break;
00836 
00837   case VAK_Undefined:
00838   case VAK_MSVCUndefined:
00839     DiagRuntimeBehavior(
00840         E->getLocStart(), nullptr,
00841         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
00842           << getLangOpts().CPlusPlus11 << Ty << CT);
00843     break;
00844 
00845   case VAK_Invalid:
00846     if (Ty->isObjCObjectType())
00847       DiagRuntimeBehavior(
00848           E->getLocStart(), nullptr,
00849           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
00850             << Ty << CT);
00851     else
00852       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
00853         << isa<InitListExpr>(E) << Ty << CT;
00854     break;
00855   }
00856 }
00857 
00858 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
00859 /// will create a trap if the resulting type is not a POD type.
00860 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
00861                                                   FunctionDecl *FDecl) {
00862   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
00863     // Strip the unbridged-cast placeholder expression off, if applicable.
00864     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
00865         (CT == VariadicMethod ||
00866          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
00867       E = stripARCUnbridgedCast(E);
00868 
00869     // Otherwise, do normal placeholder checking.
00870     } else {
00871       ExprResult ExprRes = CheckPlaceholderExpr(E);
00872       if (ExprRes.isInvalid())
00873         return ExprError();
00874       E = ExprRes.get();
00875     }
00876   }
00877   
00878   ExprResult ExprRes = DefaultArgumentPromotion(E);
00879   if (ExprRes.isInvalid())
00880     return ExprError();
00881   E = ExprRes.get();
00882 
00883   // Diagnostics regarding non-POD argument types are
00884   // emitted along with format string checking in Sema::CheckFunctionCall().
00885   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
00886     // Turn this into a trap.
00887     CXXScopeSpec SS;
00888     SourceLocation TemplateKWLoc;
00889     UnqualifiedId Name;
00890     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
00891                        E->getLocStart());
00892     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
00893                                           Name, true, false);
00894     if (TrapFn.isInvalid())
00895       return ExprError();
00896 
00897     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
00898                                     E->getLocStart(), None,
00899                                     E->getLocEnd());
00900     if (Call.isInvalid())
00901       return ExprError();
00902 
00903     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
00904                                   Call.get(), E);
00905     if (Comma.isInvalid())
00906       return ExprError();
00907     return Comma.get();
00908   }
00909 
00910   if (!getLangOpts().CPlusPlus &&
00911       RequireCompleteType(E->getExprLoc(), E->getType(),
00912                           diag::err_call_incomplete_argument))
00913     return ExprError();
00914 
00915   return E;
00916 }
00917 
00918 /// \brief Converts an integer to complex float type.  Helper function of
00919 /// UsualArithmeticConversions()
00920 ///
00921 /// \return false if the integer expression is an integer type and is
00922 /// successfully converted to the complex type.
00923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
00924                                                   ExprResult &ComplexExpr,
00925                                                   QualType IntTy,
00926                                                   QualType ComplexTy,
00927                                                   bool SkipCast) {
00928   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
00929   if (SkipCast) return false;
00930   if (IntTy->isIntegerType()) {
00931     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
00932     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
00933     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
00934                                   CK_FloatingRealToComplex);
00935   } else {
00936     assert(IntTy->isComplexIntegerType());
00937     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
00938                                   CK_IntegralComplexToFloatingComplex);
00939   }
00940   return false;
00941 }
00942 
00943 /// \brief Handle arithmetic conversion with complex types.  Helper function of
00944 /// UsualArithmeticConversions()
00945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
00946                                              ExprResult &RHS, QualType LHSType,
00947                                              QualType RHSType,
00948                                              bool IsCompAssign) {
00949   // if we have an integer operand, the result is the complex type.
00950   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
00951                                              /*skipCast*/false))
00952     return LHSType;
00953   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
00954                                              /*skipCast*/IsCompAssign))
00955     return RHSType;
00956 
00957   // This handles complex/complex, complex/float, or float/complex.
00958   // When both operands are complex, the shorter operand is converted to the
00959   // type of the longer, and that is the type of the result. This corresponds
00960   // to what is done when combining two real floating-point operands.
00961   // The fun begins when size promotion occur across type domains.
00962   // From H&S 6.3.4: When one operand is complex and the other is a real
00963   // floating-point type, the less precise type is converted, within it's
00964   // real or complex domain, to the precision of the other type. For example,
00965   // when combining a "long double" with a "double _Complex", the
00966   // "double _Complex" is promoted to "long double _Complex".
00967 
00968   // Compute the rank of the two types, regardless of whether they are complex.
00969   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
00970 
00971   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
00972   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
00973   QualType LHSElementType =
00974       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
00975   QualType RHSElementType =
00976       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
00977 
00978   QualType ResultType = S.Context.getComplexType(LHSElementType);
00979   if (Order < 0) {
00980     // Promote the precision of the LHS if not an assignment.
00981     ResultType = S.Context.getComplexType(RHSElementType);
00982     if (!IsCompAssign) {
00983       if (LHSComplexType)
00984         LHS =
00985             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
00986       else
00987         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
00988     }
00989   } else if (Order > 0) {
00990     // Promote the precision of the RHS.
00991     if (RHSComplexType)
00992       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
00993     else
00994       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
00995   }
00996   return ResultType;
00997 }
00998 
00999 /// \brief Hande arithmetic conversion from integer to float.  Helper function
01000 /// of UsualArithmeticConversions()
01001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
01002                                            ExprResult &IntExpr,
01003                                            QualType FloatTy, QualType IntTy,
01004                                            bool ConvertFloat, bool ConvertInt) {
01005   if (IntTy->isIntegerType()) {
01006     if (ConvertInt)
01007       // Convert intExpr to the lhs floating point type.
01008       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
01009                                     CK_IntegralToFloating);
01010     return FloatTy;
01011   }
01012      
01013   // Convert both sides to the appropriate complex float.
01014   assert(IntTy->isComplexIntegerType());
01015   QualType result = S.Context.getComplexType(FloatTy);
01016 
01017   // _Complex int -> _Complex float
01018   if (ConvertInt)
01019     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
01020                                   CK_IntegralComplexToFloatingComplex);
01021 
01022   // float -> _Complex float
01023   if (ConvertFloat)
01024     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
01025                                     CK_FloatingRealToComplex);
01026 
01027   return result;
01028 }
01029 
01030 /// \brief Handle arithmethic conversion with floating point types.  Helper
01031 /// function of UsualArithmeticConversions()
01032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
01033                                       ExprResult &RHS, QualType LHSType,
01034                                       QualType RHSType, bool IsCompAssign) {
01035   bool LHSFloat = LHSType->isRealFloatingType();
01036   bool RHSFloat = RHSType->isRealFloatingType();
01037 
01038   // If we have two real floating types, convert the smaller operand
01039   // to the bigger result.
01040   if (LHSFloat && RHSFloat) {
01041     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
01042     if (order > 0) {
01043       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
01044       return LHSType;
01045     }
01046 
01047     assert(order < 0 && "illegal float comparison");
01048     if (!IsCompAssign)
01049       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
01050     return RHSType;
01051   }
01052 
01053   if (LHSFloat)
01054     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
01055                                       /*convertFloat=*/!IsCompAssign,
01056                                       /*convertInt=*/ true);
01057   assert(RHSFloat);
01058   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
01059                                     /*convertInt=*/ true,
01060                                     /*convertFloat=*/!IsCompAssign);
01061 }
01062 
01063 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
01064 
01065 namespace {
01066 /// These helper callbacks are placed in an anonymous namespace to
01067 /// permit their use as function template parameters.
01068 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
01069   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
01070 }
01071 
01072 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
01073   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
01074                              CK_IntegralComplexCast);
01075 }
01076 }
01077 
01078 /// \brief Handle integer arithmetic conversions.  Helper function of
01079 /// UsualArithmeticConversions()
01080 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
01081 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
01082                                         ExprResult &RHS, QualType LHSType,
01083                                         QualType RHSType, bool IsCompAssign) {
01084   // The rules for this case are in C99 6.3.1.8
01085   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
01086   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
01087   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
01088   if (LHSSigned == RHSSigned) {
01089     // Same signedness; use the higher-ranked type
01090     if (order >= 0) {
01091       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
01092       return LHSType;
01093     } else if (!IsCompAssign)
01094       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
01095     return RHSType;
01096   } else if (order != (LHSSigned ? 1 : -1)) {
01097     // The unsigned type has greater than or equal rank to the
01098     // signed type, so use the unsigned type
01099     if (RHSSigned) {
01100       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
01101       return LHSType;
01102     } else if (!IsCompAssign)
01103       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
01104     return RHSType;
01105   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
01106     // The two types are different widths; if we are here, that
01107     // means the signed type is larger than the unsigned type, so
01108     // use the signed type.
01109     if (LHSSigned) {
01110       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
01111       return LHSType;
01112     } else if (!IsCompAssign)
01113       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
01114     return RHSType;
01115   } else {
01116     // The signed type is higher-ranked than the unsigned type,
01117     // but isn't actually any bigger (like unsigned int and long
01118     // on most 32-bit systems).  Use the unsigned type corresponding
01119     // to the signed type.
01120     QualType result =
01121       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
01122     RHS = (*doRHSCast)(S, RHS.get(), result);
01123     if (!IsCompAssign)
01124       LHS = (*doLHSCast)(S, LHS.get(), result);
01125     return result;
01126   }
01127 }
01128 
01129 /// \brief Handle conversions with GCC complex int extension.  Helper function
01130 /// of UsualArithmeticConversions()
01131 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
01132                                            ExprResult &RHS, QualType LHSType,
01133                                            QualType RHSType,
01134                                            bool IsCompAssign) {
01135   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
01136   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
01137 
01138   if (LHSComplexInt && RHSComplexInt) {
01139     QualType LHSEltType = LHSComplexInt->getElementType();
01140     QualType RHSEltType = RHSComplexInt->getElementType();
01141     QualType ScalarType =
01142       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
01143         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
01144 
01145     return S.Context.getComplexType(ScalarType);
01146   }
01147 
01148   if (LHSComplexInt) {
01149     QualType LHSEltType = LHSComplexInt->getElementType();
01150     QualType ScalarType =
01151       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
01152         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
01153     QualType ComplexType = S.Context.getComplexType(ScalarType);
01154     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
01155                               CK_IntegralRealToComplex);
01156  
01157     return ComplexType;
01158   }
01159 
01160   assert(RHSComplexInt);
01161 
01162   QualType RHSEltType = RHSComplexInt->getElementType();
01163   QualType ScalarType =
01164     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
01165       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
01166   QualType ComplexType = S.Context.getComplexType(ScalarType);
01167   
01168   if (!IsCompAssign)
01169     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
01170                               CK_IntegralRealToComplex);
01171   return ComplexType;
01172 }
01173 
01174 /// UsualArithmeticConversions - Performs various conversions that are common to
01175 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
01176 /// routine returns the first non-arithmetic type found. The client is
01177 /// responsible for emitting appropriate error diagnostics.
01178 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
01179                                           bool IsCompAssign) {
01180   if (!IsCompAssign) {
01181     LHS = UsualUnaryConversions(LHS.get());
01182     if (LHS.isInvalid())
01183       return QualType();
01184   }
01185 
01186   RHS = UsualUnaryConversions(RHS.get());
01187   if (RHS.isInvalid())
01188     return QualType();
01189 
01190   // For conversion purposes, we ignore any qualifiers.
01191   // For example, "const float" and "float" are equivalent.
01192   QualType LHSType =
01193     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
01194   QualType RHSType =
01195     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
01196 
01197   // For conversion purposes, we ignore any atomic qualifier on the LHS.
01198   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
01199     LHSType = AtomicLHS->getValueType();
01200 
01201   // If both types are identical, no conversion is needed.
01202   if (LHSType == RHSType)
01203     return LHSType;
01204 
01205   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
01206   // The caller can deal with this (e.g. pointer + int).
01207   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
01208     return QualType();
01209 
01210   // Apply unary and bitfield promotions to the LHS's type.
01211   QualType LHSUnpromotedType = LHSType;
01212   if (LHSType->isPromotableIntegerType())
01213     LHSType = Context.getPromotedIntegerType(LHSType);
01214   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
01215   if (!LHSBitfieldPromoteTy.isNull())
01216     LHSType = LHSBitfieldPromoteTy;
01217   if (LHSType != LHSUnpromotedType && !IsCompAssign)
01218     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
01219 
01220   // If both types are identical, no conversion is needed.
01221   if (LHSType == RHSType)
01222     return LHSType;
01223 
01224   // At this point, we have two different arithmetic types.
01225 
01226   // Handle complex types first (C99 6.3.1.8p1).
01227   if (LHSType->isComplexType() || RHSType->isComplexType())
01228     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
01229                                         IsCompAssign);
01230 
01231   // Now handle "real" floating types (i.e. float, double, long double).
01232   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
01233     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
01234                                  IsCompAssign);
01235 
01236   // Handle GCC complex int extension.
01237   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
01238     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
01239                                       IsCompAssign);
01240 
01241   // Finally, we have two differing integer types.
01242   return handleIntegerConversion<doIntegralCast, doIntegralCast>
01243            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
01244 }
01245 
01246 
01247 //===----------------------------------------------------------------------===//
01248 //  Semantic Analysis for various Expression Types
01249 //===----------------------------------------------------------------------===//
01250 
01251 
01252 ExprResult
01253 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
01254                                 SourceLocation DefaultLoc,
01255                                 SourceLocation RParenLoc,
01256                                 Expr *ControllingExpr,
01257                                 ArrayRef<ParsedType> ArgTypes,
01258                                 ArrayRef<Expr *> ArgExprs) {
01259   unsigned NumAssocs = ArgTypes.size();
01260   assert(NumAssocs == ArgExprs.size());
01261 
01262   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
01263   for (unsigned i = 0; i < NumAssocs; ++i) {
01264     if (ArgTypes[i])
01265       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
01266     else
01267       Types[i] = nullptr;
01268   }
01269 
01270   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
01271                                              ControllingExpr,
01272                                              llvm::makeArrayRef(Types, NumAssocs),
01273                                              ArgExprs);
01274   delete [] Types;
01275   return ER;
01276 }
01277 
01278 ExprResult
01279 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
01280                                  SourceLocation DefaultLoc,
01281                                  SourceLocation RParenLoc,
01282                                  Expr *ControllingExpr,
01283                                  ArrayRef<TypeSourceInfo *> Types,
01284                                  ArrayRef<Expr *> Exprs) {
01285   unsigned NumAssocs = Types.size();
01286   assert(NumAssocs == Exprs.size());
01287   if (ControllingExpr->getType()->isPlaceholderType()) {
01288     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
01289     if (result.isInvalid()) return ExprError();
01290     ControllingExpr = result.get();
01291   }
01292 
01293   bool TypeErrorFound = false,
01294        IsResultDependent = ControllingExpr->isTypeDependent(),
01295        ContainsUnexpandedParameterPack
01296          = ControllingExpr->containsUnexpandedParameterPack();
01297 
01298   for (unsigned i = 0; i < NumAssocs; ++i) {
01299     if (Exprs[i]->containsUnexpandedParameterPack())
01300       ContainsUnexpandedParameterPack = true;
01301 
01302     if (Types[i]) {
01303       if (Types[i]->getType()->containsUnexpandedParameterPack())
01304         ContainsUnexpandedParameterPack = true;
01305 
01306       if (Types[i]->getType()->isDependentType()) {
01307         IsResultDependent = true;
01308       } else {
01309         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
01310         // complete object type other than a variably modified type."
01311         unsigned D = 0;
01312         if (Types[i]->getType()->isIncompleteType())
01313           D = diag::err_assoc_type_incomplete;
01314         else if (!Types[i]->getType()->isObjectType())
01315           D = diag::err_assoc_type_nonobject;
01316         else if (Types[i]->getType()->isVariablyModifiedType())
01317           D = diag::err_assoc_type_variably_modified;
01318 
01319         if (D != 0) {
01320           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
01321             << Types[i]->getTypeLoc().getSourceRange()
01322             << Types[i]->getType();
01323           TypeErrorFound = true;
01324         }
01325 
01326         // C11 6.5.1.1p2 "No two generic associations in the same generic
01327         // selection shall specify compatible types."
01328         for (unsigned j = i+1; j < NumAssocs; ++j)
01329           if (Types[j] && !Types[j]->getType()->isDependentType() &&
01330               Context.typesAreCompatible(Types[i]->getType(),
01331                                          Types[j]->getType())) {
01332             Diag(Types[j]->getTypeLoc().getBeginLoc(),
01333                  diag::err_assoc_compatible_types)
01334               << Types[j]->getTypeLoc().getSourceRange()
01335               << Types[j]->getType()
01336               << Types[i]->getType();
01337             Diag(Types[i]->getTypeLoc().getBeginLoc(),
01338                  diag::note_compat_assoc)
01339               << Types[i]->getTypeLoc().getSourceRange()
01340               << Types[i]->getType();
01341             TypeErrorFound = true;
01342           }
01343       }
01344     }
01345   }
01346   if (TypeErrorFound)
01347     return ExprError();
01348 
01349   // If we determined that the generic selection is result-dependent, don't
01350   // try to compute the result expression.
01351   if (IsResultDependent)
01352     return new (Context) GenericSelectionExpr(
01353         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
01354         ContainsUnexpandedParameterPack);
01355 
01356   SmallVector<unsigned, 1> CompatIndices;
01357   unsigned DefaultIndex = -1U;
01358   for (unsigned i = 0; i < NumAssocs; ++i) {
01359     if (!Types[i])
01360       DefaultIndex = i;
01361     else if (Context.typesAreCompatible(ControllingExpr->getType(),
01362                                         Types[i]->getType()))
01363       CompatIndices.push_back(i);
01364   }
01365 
01366   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
01367   // type compatible with at most one of the types named in its generic
01368   // association list."
01369   if (CompatIndices.size() > 1) {
01370     // We strip parens here because the controlling expression is typically
01371     // parenthesized in macro definitions.
01372     ControllingExpr = ControllingExpr->IgnoreParens();
01373     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
01374       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
01375       << (unsigned) CompatIndices.size();
01376     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
01377          E = CompatIndices.end(); I != E; ++I) {
01378       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
01379            diag::note_compat_assoc)
01380         << Types[*I]->getTypeLoc().getSourceRange()
01381         << Types[*I]->getType();
01382     }
01383     return ExprError();
01384   }
01385 
01386   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
01387   // its controlling expression shall have type compatible with exactly one of
01388   // the types named in its generic association list."
01389   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
01390     // We strip parens here because the controlling expression is typically
01391     // parenthesized in macro definitions.
01392     ControllingExpr = ControllingExpr->IgnoreParens();
01393     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
01394       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
01395     return ExprError();
01396   }
01397 
01398   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
01399   // type name that is compatible with the type of the controlling expression,
01400   // then the result expression of the generic selection is the expression
01401   // in that generic association. Otherwise, the result expression of the
01402   // generic selection is the expression in the default generic association."
01403   unsigned ResultIndex =
01404     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
01405 
01406   return new (Context) GenericSelectionExpr(
01407       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
01408       ContainsUnexpandedParameterPack, ResultIndex);
01409 }
01410 
01411 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
01412 /// location of the token and the offset of the ud-suffix within it.
01413 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
01414                                      unsigned Offset) {
01415   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
01416                                         S.getLangOpts());
01417 }
01418 
01419 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
01420 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
01421 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
01422                                                  IdentifierInfo *UDSuffix,
01423                                                  SourceLocation UDSuffixLoc,
01424                                                  ArrayRef<Expr*> Args,
01425                                                  SourceLocation LitEndLoc) {
01426   assert(Args.size() <= 2 && "too many arguments for literal operator");
01427 
01428   QualType ArgTy[2];
01429   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
01430     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
01431     if (ArgTy[ArgIdx]->isArrayType())
01432       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
01433   }
01434 
01435   DeclarationName OpName =
01436     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
01437   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
01438   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
01439 
01440   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
01441   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
01442                               /*AllowRaw*/false, /*AllowTemplate*/false,
01443                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
01444     return ExprError();
01445 
01446   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
01447 }
01448 
01449 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
01450 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
01451 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
01452 /// multiple tokens.  However, the common case is that StringToks points to one
01453 /// string.
01454 ///
01455 ExprResult
01456 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
01457   assert(!StringToks.empty() && "Must have at least one string!");
01458 
01459   StringLiteralParser Literal(StringToks, PP);
01460   if (Literal.hadError)
01461     return ExprError();
01462 
01463   SmallVector<SourceLocation, 4> StringTokLocs;
01464   for (unsigned i = 0; i != StringToks.size(); ++i)
01465     StringTokLocs.push_back(StringToks[i].getLocation());
01466 
01467   QualType CharTy = Context.CharTy;
01468   StringLiteral::StringKind Kind = StringLiteral::Ascii;
01469   if (Literal.isWide()) {
01470     CharTy = Context.getWideCharType();
01471     Kind = StringLiteral::Wide;
01472   } else if (Literal.isUTF8()) {
01473     Kind = StringLiteral::UTF8;
01474   } else if (Literal.isUTF16()) {
01475     CharTy = Context.Char16Ty;
01476     Kind = StringLiteral::UTF16;
01477   } else if (Literal.isUTF32()) {
01478     CharTy = Context.Char32Ty;
01479     Kind = StringLiteral::UTF32;
01480   } else if (Literal.isPascal()) {
01481     CharTy = Context.UnsignedCharTy;
01482   }
01483 
01484   QualType CharTyConst = CharTy;
01485   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
01486   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
01487     CharTyConst.addConst();
01488 
01489   // Get an array type for the string, according to C99 6.4.5.  This includes
01490   // the nul terminator character as well as the string length for pascal
01491   // strings.
01492   QualType StrTy = Context.getConstantArrayType(CharTyConst,
01493                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
01494                                  ArrayType::Normal, 0);
01495 
01496   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
01497   if (getLangOpts().OpenCL) {
01498     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
01499   }
01500 
01501   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
01502   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
01503                                              Kind, Literal.Pascal, StrTy,
01504                                              &StringTokLocs[0],
01505                                              StringTokLocs.size());
01506   if (Literal.getUDSuffix().empty())
01507     return Lit;
01508 
01509   // We're building a user-defined literal.
01510   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
01511   SourceLocation UDSuffixLoc =
01512     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
01513                    Literal.getUDSuffixOffset());
01514 
01515   // Make sure we're allowed user-defined literals here.
01516   if (!UDLScope)
01517     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
01518 
01519   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
01520   //   operator "" X (str, len)
01521   QualType SizeType = Context.getSizeType();
01522 
01523   DeclarationName OpName =
01524     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
01525   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
01526   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
01527 
01528   QualType ArgTy[] = {
01529     Context.getArrayDecayedType(StrTy), SizeType
01530   };
01531 
01532   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
01533   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
01534                                 /*AllowRaw*/false, /*AllowTemplate*/false,
01535                                 /*AllowStringTemplate*/true)) {
01536 
01537   case LOLR_Cooked: {
01538     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
01539     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
01540                                                     StringTokLocs[0]);
01541     Expr *Args[] = { Lit, LenArg };
01542 
01543     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
01544   }
01545 
01546   case LOLR_StringTemplate: {
01547     TemplateArgumentListInfo ExplicitArgs;
01548 
01549     unsigned CharBits = Context.getIntWidth(CharTy);
01550     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
01551     llvm::APSInt Value(CharBits, CharIsUnsigned);
01552 
01553     TemplateArgument TypeArg(CharTy);
01554     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
01555     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
01556 
01557     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
01558       Value = Lit->getCodeUnit(I);
01559       TemplateArgument Arg(Context, Value, CharTy);
01560       TemplateArgumentLocInfo ArgInfo;
01561       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
01562     }
01563     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
01564                                     &ExplicitArgs);
01565   }
01566   case LOLR_Raw:
01567   case LOLR_Template:
01568     llvm_unreachable("unexpected literal operator lookup result");
01569   case LOLR_Error:
01570     return ExprError();
01571   }
01572   llvm_unreachable("unexpected literal operator lookup result");
01573 }
01574 
01575 ExprResult
01576 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
01577                        SourceLocation Loc,
01578                        const CXXScopeSpec *SS) {
01579   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
01580   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
01581 }
01582 
01583 /// BuildDeclRefExpr - Build an expression that references a
01584 /// declaration that does not require a closure capture.
01585 ExprResult
01586 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
01587                        const DeclarationNameInfo &NameInfo,
01588                        const CXXScopeSpec *SS, NamedDecl *FoundD,
01589                        const TemplateArgumentListInfo *TemplateArgs) {
01590   if (getLangOpts().CUDA)
01591     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
01592       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
01593         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
01594                            CalleeTarget = IdentifyCUDATarget(Callee);
01595         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
01596           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
01597             << CalleeTarget << D->getIdentifier() << CallerTarget;
01598           Diag(D->getLocation(), diag::note_previous_decl)
01599             << D->getIdentifier();
01600           return ExprError();
01601         }
01602       }
01603 
01604   bool refersToEnclosingScope =
01605     (CurContext != D->getDeclContext() &&
01606      D->getDeclContext()->isFunctionOrMethod()) ||
01607     (isa<VarDecl>(D) &&
01608      cast<VarDecl>(D)->isInitCapture());
01609 
01610   DeclRefExpr *E;
01611   if (isa<VarTemplateSpecializationDecl>(D)) {
01612     VarTemplateSpecializationDecl *VarSpec =
01613         cast<VarTemplateSpecializationDecl>(D);
01614 
01615     E = DeclRefExpr::Create(
01616         Context,
01617         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
01618         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
01619         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
01620   } else {
01621     assert(!TemplateArgs && "No template arguments for non-variable"
01622                             " template specialization references");
01623     E = DeclRefExpr::Create(
01624         Context,
01625         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
01626         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
01627   }
01628 
01629   MarkDeclRefReferenced(E);
01630 
01631   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
01632       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
01633       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
01634       recordUseOfEvaluatedWeak(E);
01635 
01636   // Just in case we're building an illegal pointer-to-member.
01637   FieldDecl *FD = dyn_cast<FieldDecl>(D);
01638   if (FD && FD->isBitField())
01639     E->setObjectKind(OK_BitField);
01640 
01641   return E;
01642 }
01643 
01644 /// Decomposes the given name into a DeclarationNameInfo, its location, and
01645 /// possibly a list of template arguments.
01646 ///
01647 /// If this produces template arguments, it is permitted to call
01648 /// DecomposeTemplateName.
01649 ///
01650 /// This actually loses a lot of source location information for
01651 /// non-standard name kinds; we should consider preserving that in
01652 /// some way.
01653 void
01654 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
01655                              TemplateArgumentListInfo &Buffer,
01656                              DeclarationNameInfo &NameInfo,
01657                              const TemplateArgumentListInfo *&TemplateArgs) {
01658   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
01659     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
01660     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
01661 
01662     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
01663                                        Id.TemplateId->NumArgs);
01664     translateTemplateArguments(TemplateArgsPtr, Buffer);
01665 
01666     TemplateName TName = Id.TemplateId->Template.get();
01667     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
01668     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
01669     TemplateArgs = &Buffer;
01670   } else {
01671     NameInfo = GetNameFromUnqualifiedId(Id);
01672     TemplateArgs = nullptr;
01673   }
01674 }
01675 
01676 /// Diagnose an empty lookup.
01677 ///
01678 /// \return false if new lookup candidates were found
01679 bool
01680 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
01681                           std::unique_ptr<CorrectionCandidateCallback> CCC,
01682                           TemplateArgumentListInfo *ExplicitTemplateArgs,
01683                           ArrayRef<Expr *> Args) {
01684   DeclarationName Name = R.getLookupName();
01685 
01686   unsigned diagnostic = diag::err_undeclared_var_use;
01687   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
01688   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
01689       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
01690       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
01691     diagnostic = diag::err_undeclared_use;
01692     diagnostic_suggest = diag::err_undeclared_use_suggest;
01693   }
01694 
01695   // If the original lookup was an unqualified lookup, fake an
01696   // unqualified lookup.  This is useful when (for example) the
01697   // original lookup would not have found something because it was a
01698   // dependent name.
01699   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
01700     ? CurContext : nullptr;
01701   while (DC) {
01702     if (isa<CXXRecordDecl>(DC)) {
01703       LookupQualifiedName(R, DC);
01704 
01705       if (!R.empty()) {
01706         // Don't give errors about ambiguities in this lookup.
01707         R.suppressDiagnostics();
01708 
01709         // During a default argument instantiation the CurContext points
01710         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
01711         // function parameter list, hence add an explicit check.
01712         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
01713                               ActiveTemplateInstantiations.back().Kind ==
01714             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
01715         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
01716         bool isInstance = CurMethod &&
01717                           CurMethod->isInstance() &&
01718                           DC == CurMethod->getParent() && !isDefaultArgument;
01719                           
01720 
01721         // Give a code modification hint to insert 'this->'.
01722         // TODO: fixit for inserting 'Base<T>::' in the other cases.
01723         // Actually quite difficult!
01724         if (getLangOpts().MSVCCompat)
01725           diagnostic = diag::ext_found_via_dependent_bases_lookup;
01726         if (isInstance) {
01727           Diag(R.getNameLoc(), diagnostic) << Name
01728             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
01729           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
01730               CallsUndergoingInstantiation.back()->getCallee());
01731 
01732           CXXMethodDecl *DepMethod;
01733           if (CurMethod->isDependentContext())
01734             DepMethod = CurMethod;
01735           else if (CurMethod->getTemplatedKind() ==
01736               FunctionDecl::TK_FunctionTemplateSpecialization)
01737             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
01738                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
01739           else
01740             DepMethod = cast<CXXMethodDecl>(
01741                 CurMethod->getInstantiatedFromMemberFunction());
01742           assert(DepMethod && "No template pattern found");
01743 
01744           QualType DepThisType = DepMethod->getThisType(Context);
01745           CheckCXXThisCapture(R.getNameLoc());
01746           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
01747                                      R.getNameLoc(), DepThisType, false);
01748           TemplateArgumentListInfo TList;
01749           if (ULE->hasExplicitTemplateArgs())
01750             ULE->copyTemplateArgumentsInto(TList);
01751           
01752           CXXScopeSpec SS;
01753           SS.Adopt(ULE->getQualifierLoc());
01754           CXXDependentScopeMemberExpr *DepExpr =
01755               CXXDependentScopeMemberExpr::Create(
01756                   Context, DepThis, DepThisType, true, SourceLocation(),
01757                   SS.getWithLocInContext(Context),
01758                   ULE->getTemplateKeywordLoc(), nullptr,
01759                   R.getLookupNameInfo(),
01760                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
01761           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
01762         } else {
01763           Diag(R.getNameLoc(), diagnostic) << Name;
01764         }
01765 
01766         // Do we really want to note all of these?
01767         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
01768           Diag((*I)->getLocation(), diag::note_dependent_var_use);
01769 
01770         // Return true if we are inside a default argument instantiation
01771         // and the found name refers to an instance member function, otherwise
01772         // the function calling DiagnoseEmptyLookup will try to create an
01773         // implicit member call and this is wrong for default argument.
01774         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
01775           Diag(R.getNameLoc(), diag::err_member_call_without_object);
01776           return true;
01777         }
01778 
01779         // Tell the callee to try to recover.
01780         return false;
01781       }
01782 
01783       R.clear();
01784     }
01785 
01786     // In Microsoft mode, if we are performing lookup from within a friend
01787     // function definition declared at class scope then we must set
01788     // DC to the lexical parent to be able to search into the parent
01789     // class.
01790     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
01791         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
01792         DC->getLexicalParent()->isRecord())
01793       DC = DC->getLexicalParent();
01794     else
01795       DC = DC->getParent();
01796   }
01797 
01798   // We didn't find anything, so try to correct for a typo.
01799   TypoCorrection Corrected;
01800   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
01801                                     S, &SS, std::move(CCC), CTK_ErrorRecovery))) {
01802     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
01803     bool DroppedSpecifier =
01804         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
01805     R.setLookupName(Corrected.getCorrection());
01806 
01807     bool AcceptableWithRecovery = false;
01808     bool AcceptableWithoutRecovery = false;
01809     NamedDecl *ND = Corrected.getCorrectionDecl();
01810     if (ND) {
01811       if (Corrected.isOverloaded()) {
01812         OverloadCandidateSet OCS(R.getNameLoc(),
01813                                  OverloadCandidateSet::CSK_Normal);
01814         OverloadCandidateSet::iterator Best;
01815         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
01816                                         CDEnd = Corrected.end();
01817              CD != CDEnd; ++CD) {
01818           if (FunctionTemplateDecl *FTD =
01819                    dyn_cast<FunctionTemplateDecl>(*CD))
01820             AddTemplateOverloadCandidate(
01821                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
01822                 Args, OCS);
01823           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
01824             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
01825               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
01826                                    Args, OCS);
01827         }
01828         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
01829         case OR_Success:
01830           ND = Best->Function;
01831           Corrected.setCorrectionDecl(ND);
01832           break;
01833         default:
01834           // FIXME: Arbitrarily pick the first declaration for the note.
01835           Corrected.setCorrectionDecl(ND);
01836           break;
01837         }
01838       }
01839       R.addDecl(ND);
01840       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
01841         CXXRecordDecl *Record = nullptr;
01842         if (Corrected.getCorrectionSpecifier()) {
01843           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
01844           Record = Ty->getAsCXXRecordDecl();
01845         }
01846         if (!Record)
01847           Record = cast<CXXRecordDecl>(
01848               ND->getDeclContext()->getRedeclContext());
01849         R.setNamingClass(Record);
01850       }
01851 
01852       AcceptableWithRecovery =
01853           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
01854       // FIXME: If we ended up with a typo for a type name or
01855       // Objective-C class name, we're in trouble because the parser
01856       // is in the wrong place to recover. Suggest the typo
01857       // correction, but don't make it a fix-it since we're not going
01858       // to recover well anyway.
01859       AcceptableWithoutRecovery =
01860           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
01861     } else {
01862       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
01863       // because we aren't able to recover.
01864       AcceptableWithoutRecovery = true;
01865     }
01866 
01867     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
01868       unsigned NoteID = (Corrected.getCorrectionDecl() &&
01869                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
01870                             ? diag::note_implicit_param_decl
01871                             : diag::note_previous_decl;
01872       if (SS.isEmpty())
01873         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
01874                      PDiag(NoteID), AcceptableWithRecovery);
01875       else
01876         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
01877                                   << Name << computeDeclContext(SS, false)
01878                                   << DroppedSpecifier << SS.getRange(),
01879                      PDiag(NoteID), AcceptableWithRecovery);
01880 
01881       // Tell the callee whether to try to recover.
01882       return !AcceptableWithRecovery;
01883     }
01884   }
01885   R.clear();
01886 
01887   // Emit a special diagnostic for failed member lookups.
01888   // FIXME: computing the declaration context might fail here (?)
01889   if (!SS.isEmpty()) {
01890     Diag(R.getNameLoc(), diag::err_no_member)
01891       << Name << computeDeclContext(SS, false)
01892       << SS.getRange();
01893     return true;
01894   }
01895 
01896   // Give up, we can't recover.
01897   Diag(R.getNameLoc(), diagnostic) << Name;
01898   return true;
01899 }
01900 
01901 /// In Microsoft mode, if we are inside a template class whose parent class has
01902 /// dependent base classes, and we can't resolve an unqualified identifier, then
01903 /// assume the identifier is a member of a dependent base class.  We can only
01904 /// recover successfully in static methods, instance methods, and other contexts
01905 /// where 'this' is available.  This doesn't precisely match MSVC's
01906 /// instantiation model, but it's close enough.
01907 static Expr *
01908 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
01909                                DeclarationNameInfo &NameInfo,
01910                                SourceLocation TemplateKWLoc,
01911                                const TemplateArgumentListInfo *TemplateArgs) {
01912   // Only try to recover from lookup into dependent bases in static methods or
01913   // contexts where 'this' is available.
01914   QualType ThisType = S.getCurrentThisType();
01915   const CXXRecordDecl *RD = nullptr;
01916   if (!ThisType.isNull())
01917     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
01918   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
01919     RD = MD->getParent();
01920   if (!RD || !RD->hasAnyDependentBases())
01921     return nullptr;
01922 
01923   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
01924   // is available, suggest inserting 'this->' as a fixit.
01925   SourceLocation Loc = NameInfo.getLoc();
01926   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
01927   DB << NameInfo.getName() << RD;
01928 
01929   if (!ThisType.isNull()) {
01930     DB << FixItHint::CreateInsertion(Loc, "this->");
01931     return CXXDependentScopeMemberExpr::Create(
01932         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
01933         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
01934         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
01935   }
01936 
01937   // Synthesize a fake NNS that points to the derived class.  This will
01938   // perform name lookup during template instantiation.
01939   CXXScopeSpec SS;
01940   auto *NNS =
01941       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
01942   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
01943   return DependentScopeDeclRefExpr::Create(
01944       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
01945       TemplateArgs);
01946 }
01947 
01948 ExprResult
01949 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
01950                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
01951                         bool HasTrailingLParen, bool IsAddressOfOperand,
01952                         std::unique_ptr<CorrectionCandidateCallback> CCC,
01953                         bool IsInlineAsmIdentifier) {
01954   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
01955          "cannot be direct & operand and have a trailing lparen");
01956   if (SS.isInvalid())
01957     return ExprError();
01958 
01959   TemplateArgumentListInfo TemplateArgsBuffer;
01960 
01961   // Decompose the UnqualifiedId into the following data.
01962   DeclarationNameInfo NameInfo;
01963   const TemplateArgumentListInfo *TemplateArgs;
01964   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
01965 
01966   DeclarationName Name = NameInfo.getName();
01967   IdentifierInfo *II = Name.getAsIdentifierInfo();
01968   SourceLocation NameLoc = NameInfo.getLoc();
01969 
01970   // C++ [temp.dep.expr]p3:
01971   //   An id-expression is type-dependent if it contains:
01972   //     -- an identifier that was declared with a dependent type,
01973   //        (note: handled after lookup)
01974   //     -- a template-id that is dependent,
01975   //        (note: handled in BuildTemplateIdExpr)
01976   //     -- a conversion-function-id that specifies a dependent type,
01977   //     -- a nested-name-specifier that contains a class-name that
01978   //        names a dependent type.
01979   // Determine whether this is a member of an unknown specialization;
01980   // we need to handle these differently.
01981   bool DependentID = false;
01982   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
01983       Name.getCXXNameType()->isDependentType()) {
01984     DependentID = true;
01985   } else if (SS.isSet()) {
01986     if (DeclContext *DC = computeDeclContext(SS, false)) {
01987       if (RequireCompleteDeclContext(SS, DC))
01988         return ExprError();
01989     } else {
01990       DependentID = true;
01991     }
01992   }
01993 
01994   if (DependentID)
01995     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
01996                                       IsAddressOfOperand, TemplateArgs);
01997 
01998   // Perform the required lookup.
01999   LookupResult R(*this, NameInfo, 
02000                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
02001                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
02002   if (TemplateArgs) {
02003     // Lookup the template name again to correctly establish the context in
02004     // which it was found. This is really unfortunate as we already did the
02005     // lookup to determine that it was a template name in the first place. If
02006     // this becomes a performance hit, we can work harder to preserve those
02007     // results until we get here but it's likely not worth it.
02008     bool MemberOfUnknownSpecialization;
02009     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
02010                        MemberOfUnknownSpecialization);
02011     
02012     if (MemberOfUnknownSpecialization ||
02013         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
02014       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
02015                                         IsAddressOfOperand, TemplateArgs);
02016   } else {
02017     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
02018     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
02019 
02020     // If the result might be in a dependent base class, this is a dependent 
02021     // id-expression.
02022     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
02023       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
02024                                         IsAddressOfOperand, TemplateArgs);
02025 
02026     // If this reference is in an Objective-C method, then we need to do
02027     // some special Objective-C lookup, too.
02028     if (IvarLookupFollowUp) {
02029       ExprResult E(LookupInObjCMethod(R, S, II, true));
02030       if (E.isInvalid())
02031         return ExprError();
02032 
02033       if (Expr *Ex = E.getAs<Expr>())
02034         return Ex;
02035     }
02036   }
02037 
02038   if (R.isAmbiguous())
02039     return ExprError();
02040 
02041   // This could be an implicitly declared function reference (legal in C90,
02042   // extension in C99, forbidden in C++).
02043   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
02044     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
02045     if (D) R.addDecl(D);
02046   }
02047 
02048   // Determine whether this name might be a candidate for
02049   // argument-dependent lookup.
02050   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
02051 
02052   if (R.empty() && !ADL) {
02053     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
02054       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
02055                                                    TemplateKWLoc, TemplateArgs))
02056         return E;
02057     }
02058 
02059     // Don't diagnose an empty lookup for inline assembly.
02060     if (IsInlineAsmIdentifier)
02061       return ExprError();
02062 
02063     // If this name wasn't predeclared and if this is not a function
02064     // call, diagnose the problem.
02065     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>();
02066     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
02067     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
02068            "Typo correction callback misconfigured");
02069     if (DiagnoseEmptyLookup(S, SS, R,
02070                             CCC ? std::move(CCC) : std::move(DefaultValidator)))
02071       return ExprError();
02072 
02073     assert(!R.empty() &&
02074            "DiagnoseEmptyLookup returned false but added no results");
02075 
02076     // If we found an Objective-C instance variable, let
02077     // LookupInObjCMethod build the appropriate expression to
02078     // reference the ivar.
02079     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
02080       R.clear();
02081       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
02082       // In a hopelessly buggy code, Objective-C instance variable
02083       // lookup fails and no expression will be built to reference it.
02084       if (!E.isInvalid() && !E.get())
02085         return ExprError();
02086       return E;
02087     }
02088   }
02089 
02090   // This is guaranteed from this point on.
02091   assert(!R.empty() || ADL);
02092 
02093   // Check whether this might be a C++ implicit instance member access.
02094   // C++ [class.mfct.non-static]p3:
02095   //   When an id-expression that is not part of a class member access
02096   //   syntax and not used to form a pointer to member is used in the
02097   //   body of a non-static member function of class X, if name lookup
02098   //   resolves the name in the id-expression to a non-static non-type
02099   //   member of some class C, the id-expression is transformed into a
02100   //   class member access expression using (*this) as the
02101   //   postfix-expression to the left of the . operator.
02102   //
02103   // But we don't actually need to do this for '&' operands if R
02104   // resolved to a function or overloaded function set, because the
02105   // expression is ill-formed if it actually works out to be a
02106   // non-static member function:
02107   //
02108   // C++ [expr.ref]p4:
02109   //   Otherwise, if E1.E2 refers to a non-static member function. . .
02110   //   [t]he expression can be used only as the left-hand operand of a
02111   //   member function call.
02112   //
02113   // There are other safeguards against such uses, but it's important
02114   // to get this right here so that we don't end up making a
02115   // spuriously dependent expression if we're inside a dependent
02116   // instance method.
02117   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
02118     bool MightBeImplicitMember;
02119     if (!IsAddressOfOperand)
02120       MightBeImplicitMember = true;
02121     else if (!SS.isEmpty())
02122       MightBeImplicitMember = false;
02123     else if (R.isOverloadedResult())
02124       MightBeImplicitMember = false;
02125     else if (R.isUnresolvableResult())
02126       MightBeImplicitMember = true;
02127     else
02128       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
02129                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
02130                               isa<MSPropertyDecl>(R.getFoundDecl());
02131 
02132     if (MightBeImplicitMember)
02133       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
02134                                              R, TemplateArgs);
02135   }
02136 
02137   if (TemplateArgs || TemplateKWLoc.isValid()) {
02138 
02139     // In C++1y, if this is a variable template id, then check it
02140     // in BuildTemplateIdExpr().
02141     // The single lookup result must be a variable template declaration.
02142     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
02143         Id.TemplateId->Kind == TNK_Var_template) {
02144       assert(R.getAsSingle<VarTemplateDecl>() &&
02145              "There should only be one declaration found.");
02146     }
02147 
02148     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
02149   }
02150 
02151   return BuildDeclarationNameExpr(SS, R, ADL);
02152 }
02153 
02154 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
02155 /// declaration name, generally during template instantiation.
02156 /// There's a large number of things which don't need to be done along
02157 /// this path.
02158 ExprResult
02159 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
02160                                         const DeclarationNameInfo &NameInfo,
02161                                         bool IsAddressOfOperand,
02162                                         TypeSourceInfo **RecoveryTSI) {
02163   DeclContext *DC = computeDeclContext(SS, false);
02164   if (!DC)
02165     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
02166                                      NameInfo, /*TemplateArgs=*/nullptr);
02167 
02168   if (RequireCompleteDeclContext(SS, DC))
02169     return ExprError();
02170 
02171   LookupResult R(*this, NameInfo, LookupOrdinaryName);
02172   LookupQualifiedName(R, DC);
02173 
02174   if (R.isAmbiguous())
02175     return ExprError();
02176 
02177   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
02178     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
02179                                      NameInfo, /*TemplateArgs=*/nullptr);
02180 
02181   if (R.empty()) {
02182     Diag(NameInfo.getLoc(), diag::err_no_member)
02183       << NameInfo.getName() << DC << SS.getRange();
02184     return ExprError();
02185   }
02186 
02187   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
02188     // Diagnose a missing typename if this resolved unambiguously to a type in
02189     // a dependent context.  If we can recover with a type, downgrade this to
02190     // a warning in Microsoft compatibility mode.
02191     unsigned DiagID = diag::err_typename_missing;
02192     if (RecoveryTSI && getLangOpts().MSVCCompat)
02193       DiagID = diag::ext_typename_missing;
02194     SourceLocation Loc = SS.getBeginLoc();
02195     auto D = Diag(Loc, DiagID);
02196     D << SS.getScopeRep() << NameInfo.getName().getAsString()
02197       << SourceRange(Loc, NameInfo.getEndLoc());
02198 
02199     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
02200     // context.
02201     if (!RecoveryTSI)
02202       return ExprError();
02203 
02204     // Only issue the fixit if we're prepared to recover.
02205     D << FixItHint::CreateInsertion(Loc, "typename ");
02206 
02207     // Recover by pretending this was an elaborated type.
02208     QualType Ty = Context.getTypeDeclType(TD);
02209     TypeLocBuilder TLB;
02210     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
02211 
02212     QualType ET = getElaboratedType(ETK_None, SS, Ty);
02213     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
02214     QTL.setElaboratedKeywordLoc(SourceLocation());
02215     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
02216 
02217     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
02218 
02219     return ExprEmpty();
02220   }
02221 
02222   // Defend against this resolving to an implicit member access. We usually
02223   // won't get here if this might be a legitimate a class member (we end up in
02224   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
02225   // a pointer-to-member or in an unevaluated context in C++11.
02226   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
02227     return BuildPossibleImplicitMemberExpr(SS,
02228                                            /*TemplateKWLoc=*/SourceLocation(),
02229                                            R, /*TemplateArgs=*/nullptr);
02230 
02231   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
02232 }
02233 
02234 /// LookupInObjCMethod - The parser has read a name in, and Sema has
02235 /// detected that we're currently inside an ObjC method.  Perform some
02236 /// additional lookup.
02237 ///
02238 /// Ideally, most of this would be done by lookup, but there's
02239 /// actually quite a lot of extra work involved.
02240 ///
02241 /// Returns a null sentinel to indicate trivial success.
02242 ExprResult
02243 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
02244                          IdentifierInfo *II, bool AllowBuiltinCreation) {
02245   SourceLocation Loc = Lookup.getNameLoc();
02246   ObjCMethodDecl *CurMethod = getCurMethodDecl();
02247   
02248   // Check for error condition which is already reported.
02249   if (!CurMethod)
02250     return ExprError();
02251 
02252   // There are two cases to handle here.  1) scoped lookup could have failed,
02253   // in which case we should look for an ivar.  2) scoped lookup could have
02254   // found a decl, but that decl is outside the current instance method (i.e.
02255   // a global variable).  In these two cases, we do a lookup for an ivar with
02256   // this name, if the lookup sucedes, we replace it our current decl.
02257 
02258   // If we're in a class method, we don't normally want to look for
02259   // ivars.  But if we don't find anything else, and there's an
02260   // ivar, that's an error.
02261   bool IsClassMethod = CurMethod->isClassMethod();
02262 
02263   bool LookForIvars;
02264   if (Lookup.empty())
02265     LookForIvars = true;
02266   else if (IsClassMethod)
02267     LookForIvars = false;
02268   else
02269     LookForIvars = (Lookup.isSingleResult() &&
02270                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
02271   ObjCInterfaceDecl *IFace = nullptr;
02272   if (LookForIvars) {
02273     IFace = CurMethod->getClassInterface();
02274     ObjCInterfaceDecl *ClassDeclared;
02275     ObjCIvarDecl *IV = nullptr;
02276     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
02277       // Diagnose using an ivar in a class method.
02278       if (IsClassMethod)
02279         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
02280                          << IV->getDeclName());
02281 
02282       // If we're referencing an invalid decl, just return this as a silent
02283       // error node.  The error diagnostic was already emitted on the decl.
02284       if (IV->isInvalidDecl())
02285         return ExprError();
02286 
02287       // Check if referencing a field with __attribute__((deprecated)).
02288       if (DiagnoseUseOfDecl(IV, Loc))
02289         return ExprError();
02290 
02291       // Diagnose the use of an ivar outside of the declaring class.
02292       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
02293           !declaresSameEntity(ClassDeclared, IFace) &&
02294           !getLangOpts().DebuggerSupport)
02295         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
02296 
02297       // FIXME: This should use a new expr for a direct reference, don't
02298       // turn this into Self->ivar, just return a BareIVarExpr or something.
02299       IdentifierInfo &II = Context.Idents.get("self");
02300       UnqualifiedId SelfName;
02301       SelfName.setIdentifier(&II, SourceLocation());
02302       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
02303       CXXScopeSpec SelfScopeSpec;
02304       SourceLocation TemplateKWLoc;
02305       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
02306                                               SelfName, false, false);
02307       if (SelfExpr.isInvalid())
02308         return ExprError();
02309 
02310       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
02311       if (SelfExpr.isInvalid())
02312         return ExprError();
02313 
02314       MarkAnyDeclReferenced(Loc, IV, true);
02315 
02316       ObjCMethodFamily MF = CurMethod->getMethodFamily();
02317       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
02318           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
02319         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
02320 
02321       ObjCIvarRefExpr *Result = new (Context)
02322           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
02323                           SelfExpr.get(), true, true);
02324 
02325       if (getLangOpts().ObjCAutoRefCount) {
02326         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
02327           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
02328             recordUseOfEvaluatedWeak(Result);
02329         }
02330         if (CurContext->isClosure())
02331           Diag(Loc, diag::warn_implicitly_retains_self)
02332             << FixItHint::CreateInsertion(Loc, "self->");
02333       }
02334       
02335       return Result;
02336     }
02337   } else if (CurMethod->isInstanceMethod()) {
02338     // We should warn if a local variable hides an ivar.
02339     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
02340       ObjCInterfaceDecl *ClassDeclared;
02341       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
02342         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
02343             declaresSameEntity(IFace, ClassDeclared))
02344           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
02345       }
02346     }
02347   } else if (Lookup.isSingleResult() &&
02348              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
02349     // If accessing a stand-alone ivar in a class method, this is an error.
02350     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
02351       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
02352                        << IV->getDeclName());
02353   }
02354 
02355   if (Lookup.empty() && II && AllowBuiltinCreation) {
02356     // FIXME. Consolidate this with similar code in LookupName.
02357     if (unsigned BuiltinID = II->getBuiltinID()) {
02358       if (!(getLangOpts().CPlusPlus &&
02359             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
02360         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
02361                                            S, Lookup.isForRedeclaration(),
02362                                            Lookup.getNameLoc());
02363         if (D) Lookup.addDecl(D);
02364       }
02365     }
02366   }
02367   // Sentinel value saying that we didn't do anything special.
02368   return ExprResult((Expr *)nullptr);
02369 }
02370 
02371 /// \brief Cast a base object to a member's actual type.
02372 ///
02373 /// Logically this happens in three phases:
02374 ///
02375 /// * First we cast from the base type to the naming class.
02376 ///   The naming class is the class into which we were looking
02377 ///   when we found the member;  it's the qualifier type if a
02378 ///   qualifier was provided, and otherwise it's the base type.
02379 ///
02380 /// * Next we cast from the naming class to the declaring class.
02381 ///   If the member we found was brought into a class's scope by
02382 ///   a using declaration, this is that class;  otherwise it's
02383 ///   the class declaring the member.
02384 ///
02385 /// * Finally we cast from the declaring class to the "true"
02386 ///   declaring class of the member.  This conversion does not
02387 ///   obey access control.
02388 ExprResult
02389 Sema::PerformObjectMemberConversion(Expr *From,
02390                                     NestedNameSpecifier *Qualifier,
02391                                     NamedDecl *FoundDecl,
02392                                     NamedDecl *Member) {
02393   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
02394   if (!RD)
02395     return From;
02396 
02397   QualType DestRecordType;
02398   QualType DestType;
02399   QualType FromRecordType;
02400   QualType FromType = From->getType();
02401   bool PointerConversions = false;
02402   if (isa<FieldDecl>(Member)) {
02403     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
02404 
02405     if (FromType->getAs<PointerType>()) {
02406       DestType = Context.getPointerType(DestRecordType);
02407       FromRecordType = FromType->getPointeeType();
02408       PointerConversions = true;
02409     } else {
02410       DestType = DestRecordType;
02411       FromRecordType = FromType;
02412     }
02413   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
02414     if (Method->isStatic())
02415       return From;
02416 
02417     DestType = Method->getThisType(Context);
02418     DestRecordType = DestType->getPointeeType();
02419 
02420     if (FromType->getAs<PointerType>()) {
02421       FromRecordType = FromType->getPointeeType();
02422       PointerConversions = true;
02423     } else {
02424       FromRecordType = FromType;
02425       DestType = DestRecordType;
02426     }
02427   } else {
02428     // No conversion necessary.
02429     return From;
02430   }
02431 
02432   if (DestType->isDependentType() || FromType->isDependentType())
02433     return From;
02434 
02435   // If the unqualified types are the same, no conversion is necessary.
02436   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
02437     return From;
02438 
02439   SourceRange FromRange = From->getSourceRange();
02440   SourceLocation FromLoc = FromRange.getBegin();
02441 
02442   ExprValueKind VK = From->getValueKind();
02443 
02444   // C++ [class.member.lookup]p8:
02445   //   [...] Ambiguities can often be resolved by qualifying a name with its
02446   //   class name.
02447   //
02448   // If the member was a qualified name and the qualified referred to a
02449   // specific base subobject type, we'll cast to that intermediate type
02450   // first and then to the object in which the member is declared. That allows
02451   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
02452   //
02453   //   class Base { public: int x; };
02454   //   class Derived1 : public Base { };
02455   //   class Derived2 : public Base { };
02456   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
02457   //
02458   //   void VeryDerived::f() {
02459   //     x = 17; // error: ambiguous base subobjects
02460   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
02461   //   }
02462   if (Qualifier && Qualifier->getAsType()) {
02463     QualType QType = QualType(Qualifier->getAsType(), 0);
02464     assert(QType->isRecordType() && "lookup done with non-record type");
02465 
02466     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
02467 
02468     // In C++98, the qualifier type doesn't actually have to be a base
02469     // type of the object type, in which case we just ignore it.
02470     // Otherwise build the appropriate casts.
02471     if (IsDerivedFrom(FromRecordType, QRecordType)) {
02472       CXXCastPath BasePath;
02473       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
02474                                        FromLoc, FromRange, &BasePath))
02475         return ExprError();
02476 
02477       if (PointerConversions)
02478         QType = Context.getPointerType(QType);
02479       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
02480                                VK, &BasePath).get();
02481 
02482       FromType = QType;
02483       FromRecordType = QRecordType;
02484 
02485       // If the qualifier type was the same as the destination type,
02486       // we're done.
02487       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
02488         return From;
02489     }
02490   }
02491 
02492   bool IgnoreAccess = false;
02493 
02494   // If we actually found the member through a using declaration, cast
02495   // down to the using declaration's type.
02496   //
02497   // Pointer equality is fine here because only one declaration of a
02498   // class ever has member declarations.
02499   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
02500     assert(isa<UsingShadowDecl>(FoundDecl));
02501     QualType URecordType = Context.getTypeDeclType(
02502                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
02503 
02504     // We only need to do this if the naming-class to declaring-class
02505     // conversion is non-trivial.
02506     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
02507       assert(IsDerivedFrom(FromRecordType, URecordType));
02508       CXXCastPath BasePath;
02509       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
02510                                        FromLoc, FromRange, &BasePath))
02511         return ExprError();
02512 
02513       QualType UType = URecordType;
02514       if (PointerConversions)
02515         UType = Context.getPointerType(UType);
02516       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
02517                                VK, &BasePath).get();
02518       FromType = UType;
02519       FromRecordType = URecordType;
02520     }
02521 
02522     // We don't do access control for the conversion from the
02523     // declaring class to the true declaring class.
02524     IgnoreAccess = true;
02525   }
02526 
02527   CXXCastPath BasePath;
02528   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
02529                                    FromLoc, FromRange, &BasePath,
02530                                    IgnoreAccess))
02531     return ExprError();
02532 
02533   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
02534                            VK, &BasePath);
02535 }
02536 
02537 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
02538                                       const LookupResult &R,
02539                                       bool HasTrailingLParen) {
02540   // Only when used directly as the postfix-expression of a call.
02541   if (!HasTrailingLParen)
02542     return false;
02543 
02544   // Never if a scope specifier was provided.
02545   if (SS.isSet())
02546     return false;
02547 
02548   // Only in C++ or ObjC++.
02549   if (!getLangOpts().CPlusPlus)
02550     return false;
02551 
02552   // Turn off ADL when we find certain kinds of declarations during
02553   // normal lookup:
02554   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
02555     NamedDecl *D = *I;
02556 
02557     // C++0x [basic.lookup.argdep]p3:
02558     //     -- a declaration of a class member
02559     // Since using decls preserve this property, we check this on the
02560     // original decl.
02561     if (D->isCXXClassMember())
02562       return false;
02563 
02564     // C++0x [basic.lookup.argdep]p3:
02565     //     -- a block-scope function declaration that is not a
02566     //        using-declaration
02567     // NOTE: we also trigger this for function templates (in fact, we
02568     // don't check the decl type at all, since all other decl types
02569     // turn off ADL anyway).
02570     if (isa<UsingShadowDecl>(D))
02571       D = cast<UsingShadowDecl>(D)->getTargetDecl();
02572     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
02573       return false;
02574 
02575     // C++0x [basic.lookup.argdep]p3:
02576     //     -- a declaration that is neither a function or a function
02577     //        template
02578     // And also for builtin functions.
02579     if (isa<FunctionDecl>(D)) {
02580       FunctionDecl *FDecl = cast<FunctionDecl>(D);
02581 
02582       // But also builtin functions.
02583       if (FDecl->getBuiltinID() && FDecl->isImplicit())
02584         return false;
02585     } else if (!isa<FunctionTemplateDecl>(D))
02586       return false;
02587   }
02588 
02589   return true;
02590 }
02591 
02592 
02593 /// Diagnoses obvious problems with the use of the given declaration
02594 /// as an expression.  This is only actually called for lookups that
02595 /// were not overloaded, and it doesn't promise that the declaration
02596 /// will in fact be used.
02597 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
02598   if (isa<TypedefNameDecl>(D)) {
02599     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
02600     return true;
02601   }
02602 
02603   if (isa<ObjCInterfaceDecl>(D)) {
02604     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
02605     return true;
02606   }
02607 
02608   if (isa<NamespaceDecl>(D)) {
02609     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
02610     return true;
02611   }
02612 
02613   return false;
02614 }
02615 
02616 ExprResult
02617 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
02618                                LookupResult &R,
02619                                bool NeedsADL) {
02620   // If this is a single, fully-resolved result and we don't need ADL,
02621   // just build an ordinary singleton decl ref.
02622   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
02623     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
02624                                     R.getRepresentativeDecl());
02625 
02626   // We only need to check the declaration if there's exactly one
02627   // result, because in the overloaded case the results can only be
02628   // functions and function templates.
02629   if (R.isSingleResult() &&
02630       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
02631     return ExprError();
02632 
02633   // Otherwise, just build an unresolved lookup expression.  Suppress
02634   // any lookup-related diagnostics; we'll hash these out later, when
02635   // we've picked a target.
02636   R.suppressDiagnostics();
02637 
02638   UnresolvedLookupExpr *ULE
02639     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
02640                                    SS.getWithLocInContext(Context),
02641                                    R.getLookupNameInfo(),
02642                                    NeedsADL, R.isOverloadedResult(),
02643                                    R.begin(), R.end());
02644 
02645   return ULE;
02646 }
02647 
02648 /// \brief Complete semantic analysis for a reference to the given declaration.
02649 ExprResult Sema::BuildDeclarationNameExpr(
02650     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
02651     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
02652   assert(D && "Cannot refer to a NULL declaration");
02653   assert(!isa<FunctionTemplateDecl>(D) &&
02654          "Cannot refer unambiguously to a function template");
02655 
02656   SourceLocation Loc = NameInfo.getLoc();
02657   if (CheckDeclInExpr(*this, Loc, D))
02658     return ExprError();
02659 
02660   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
02661     // Specifically diagnose references to class templates that are missing
02662     // a template argument list.
02663     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
02664                                            << Template << SS.getRange();
02665     Diag(Template->getLocation(), diag::note_template_decl_here);
02666     return ExprError();
02667   }
02668 
02669   // Make sure that we're referring to a value.
02670   ValueDecl *VD = dyn_cast<ValueDecl>(D);
02671   if (!VD) {
02672     Diag(Loc, diag::err_ref_non_value)
02673       << D << SS.getRange();
02674     Diag(D->getLocation(), diag::note_declared_at);
02675     return ExprError();
02676   }
02677 
02678   // Check whether this declaration can be used. Note that we suppress
02679   // this check when we're going to perform argument-dependent lookup
02680   // on this function name, because this might not be the function
02681   // that overload resolution actually selects.
02682   if (DiagnoseUseOfDecl(VD, Loc))
02683     return ExprError();
02684 
02685   // Only create DeclRefExpr's for valid Decl's.
02686   if (VD->isInvalidDecl())
02687     return ExprError();
02688 
02689   // Handle members of anonymous structs and unions.  If we got here,
02690   // and the reference is to a class member indirect field, then this
02691   // must be the subject of a pointer-to-member expression.
02692   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
02693     if (!indirectField->isCXXClassMember())
02694       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
02695                                                       indirectField);
02696 
02697   {
02698     QualType type = VD->getType();
02699     ExprValueKind valueKind = VK_RValue;
02700 
02701     switch (D->getKind()) {
02702     // Ignore all the non-ValueDecl kinds.
02703 #define ABSTRACT_DECL(kind)
02704 #define VALUE(type, base)
02705 #define DECL(type, base) \
02706     case Decl::type:
02707 #include "clang/AST/DeclNodes.inc"
02708       llvm_unreachable("invalid value decl kind");
02709 
02710     // These shouldn't make it here.
02711     case Decl::ObjCAtDefsField:
02712     case Decl::ObjCIvar:
02713       llvm_unreachable("forming non-member reference to ivar?");
02714 
02715     // Enum constants are always r-values and never references.
02716     // Unresolved using declarations are dependent.
02717     case Decl::EnumConstant:
02718     case Decl::UnresolvedUsingValue:
02719       valueKind = VK_RValue;
02720       break;
02721 
02722     // Fields and indirect fields that got here must be for
02723     // pointer-to-member expressions; we just call them l-values for
02724     // internal consistency, because this subexpression doesn't really
02725     // exist in the high-level semantics.
02726     case Decl::Field:
02727     case Decl::IndirectField:
02728       assert(getLangOpts().CPlusPlus &&
02729              "building reference to field in C?");
02730 
02731       // These can't have reference type in well-formed programs, but
02732       // for internal consistency we do this anyway.
02733       type = type.getNonReferenceType();
02734       valueKind = VK_LValue;
02735       break;
02736 
02737     // Non-type template parameters are either l-values or r-values
02738     // depending on the type.
02739     case Decl::NonTypeTemplateParm: {
02740       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
02741         type = reftype->getPointeeType();
02742         valueKind = VK_LValue; // even if the parameter is an r-value reference
02743         break;
02744       }
02745 
02746       // For non-references, we need to strip qualifiers just in case
02747       // the template parameter was declared as 'const int' or whatever.
02748       valueKind = VK_RValue;
02749       type = type.getUnqualifiedType();
02750       break;
02751     }
02752 
02753     case Decl::Var:
02754     case Decl::VarTemplateSpecialization:
02755     case Decl::VarTemplatePartialSpecialization:
02756       // In C, "extern void blah;" is valid and is an r-value.
02757       if (!getLangOpts().CPlusPlus &&
02758           !type.hasQualifiers() &&
02759           type->isVoidType()) {
02760         valueKind = VK_RValue;
02761         break;
02762       }
02763       // fallthrough
02764 
02765     case Decl::ImplicitParam:
02766     case Decl::ParmVar: {
02767       // These are always l-values.
02768       valueKind = VK_LValue;
02769       type = type.getNonReferenceType();
02770 
02771       // FIXME: Does the addition of const really only apply in
02772       // potentially-evaluated contexts? Since the variable isn't actually
02773       // captured in an unevaluated context, it seems that the answer is no.
02774       if (!isUnevaluatedContext()) {
02775         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
02776         if (!CapturedType.isNull())
02777           type = CapturedType;
02778       }
02779       
02780       break;
02781     }
02782         
02783     case Decl::Function: {
02784       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
02785         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
02786           type = Context.BuiltinFnTy;
02787           valueKind = VK_RValue;
02788           break;
02789         }
02790       }
02791 
02792       const FunctionType *fty = type->castAs<FunctionType>();
02793 
02794       // If we're referring to a function with an __unknown_anytype
02795       // result type, make the entire expression __unknown_anytype.
02796       if (fty->getReturnType() == Context.UnknownAnyTy) {
02797         type = Context.UnknownAnyTy;
02798         valueKind = VK_RValue;
02799         break;
02800       }
02801 
02802       // Functions are l-values in C++.
02803       if (getLangOpts().CPlusPlus) {
02804         valueKind = VK_LValue;
02805         break;
02806       }
02807       
02808       // C99 DR 316 says that, if a function type comes from a
02809       // function definition (without a prototype), that type is only
02810       // used for checking compatibility. Therefore, when referencing
02811       // the function, we pretend that we don't have the full function
02812       // type.
02813       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
02814           isa<FunctionProtoType>(fty))
02815         type = Context.getFunctionNoProtoType(fty->getReturnType(),
02816                                               fty->getExtInfo());
02817 
02818       // Functions are r-values in C.
02819       valueKind = VK_RValue;
02820       break;
02821     }
02822 
02823     case Decl::MSProperty:
02824       valueKind = VK_LValue;
02825       break;
02826 
02827     case Decl::CXXMethod:
02828       // If we're referring to a method with an __unknown_anytype
02829       // result type, make the entire expression __unknown_anytype.
02830       // This should only be possible with a type written directly.
02831       if (const FunctionProtoType *proto
02832             = dyn_cast<FunctionProtoType>(VD->getType()))
02833         if (proto->getReturnType() == Context.UnknownAnyTy) {
02834           type = Context.UnknownAnyTy;
02835           valueKind = VK_RValue;
02836           break;
02837         }
02838 
02839       // C++ methods are l-values if static, r-values if non-static.
02840       if (cast<CXXMethodDecl>(VD)->isStatic()) {
02841         valueKind = VK_LValue;
02842         break;
02843       }
02844       // fallthrough
02845 
02846     case Decl::CXXConversion:
02847     case Decl::CXXDestructor:
02848     case Decl::CXXConstructor:
02849       valueKind = VK_RValue;
02850       break;
02851     }
02852 
02853     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
02854                             TemplateArgs);
02855   }
02856 }
02857 
02858 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
02859                                     SmallString<32> &Target) {
02860   Target.resize(CharByteWidth * (Source.size() + 1));
02861   char *ResultPtr = &Target[0];
02862   const UTF8 *ErrorPtr;
02863   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
02864   (void)success;
02865   assert(success);
02866   Target.resize(ResultPtr - &Target[0]);
02867 }
02868 
02869 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
02870                                      PredefinedExpr::IdentType IT) {
02871   // Pick the current block, lambda, captured statement or function.
02872   Decl *currentDecl = nullptr;
02873   if (const BlockScopeInfo *BSI = getCurBlock())
02874     currentDecl = BSI->TheDecl;
02875   else if (const LambdaScopeInfo *LSI = getCurLambda())
02876     currentDecl = LSI->CallOperator;
02877   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
02878     currentDecl = CSI->TheCapturedDecl;
02879   else
02880     currentDecl = getCurFunctionOrMethodDecl();
02881 
02882   if (!currentDecl) {
02883     Diag(Loc, diag::ext_predef_outside_function);
02884     currentDecl = Context.getTranslationUnitDecl();
02885   }
02886 
02887   QualType ResTy;
02888   StringLiteral *SL = nullptr;
02889   if (cast<DeclContext>(currentDecl)->isDependentContext())
02890     ResTy = Context.DependentTy;
02891   else {
02892     // Pre-defined identifiers are of type char[x], where x is the length of
02893     // the string.
02894     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
02895     unsigned Length = Str.length();
02896 
02897     llvm::APInt LengthI(32, Length + 1);
02898     if (IT == PredefinedExpr::LFunction) {
02899       ResTy = Context.WideCharTy.withConst();
02900       SmallString<32> RawChars;
02901       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
02902                               Str, RawChars);
02903       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
02904                                            /*IndexTypeQuals*/ 0);
02905       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
02906                                  /*Pascal*/ false, ResTy, Loc);
02907     } else {
02908       ResTy = Context.CharTy.withConst();
02909       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
02910                                            /*IndexTypeQuals*/ 0);
02911       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
02912                                  /*Pascal*/ false, ResTy, Loc);
02913     }
02914   }
02915 
02916   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
02917 }
02918 
02919 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
02920   PredefinedExpr::IdentType IT;
02921 
02922   switch (Kind) {
02923   default: llvm_unreachable("Unknown simple primary expr!");
02924   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
02925   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
02926   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
02927   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
02928   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
02929   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
02930   }
02931 
02932   return BuildPredefinedExpr(Loc, IT);
02933 }
02934 
02935 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
02936   SmallString<16> CharBuffer;
02937   bool Invalid = false;
02938   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
02939   if (Invalid)
02940     return ExprError();
02941 
02942   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
02943                             PP, Tok.getKind());
02944   if (Literal.hadError())
02945     return ExprError();
02946 
02947   QualType Ty;
02948   if (Literal.isWide())
02949     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
02950   else if (Literal.isUTF16())
02951     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
02952   else if (Literal.isUTF32())
02953     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
02954   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
02955     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
02956   else
02957     Ty = Context.CharTy;  // 'x' -> char in C++
02958 
02959   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
02960   if (Literal.isWide())
02961     Kind = CharacterLiteral::Wide;
02962   else if (Literal.isUTF16())
02963     Kind = CharacterLiteral::UTF16;
02964   else if (Literal.isUTF32())
02965     Kind = CharacterLiteral::UTF32;
02966 
02967   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
02968                                              Tok.getLocation());
02969 
02970   if (Literal.getUDSuffix().empty())
02971     return Lit;
02972 
02973   // We're building a user-defined literal.
02974   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
02975   SourceLocation UDSuffixLoc =
02976     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
02977 
02978   // Make sure we're allowed user-defined literals here.
02979   if (!UDLScope)
02980     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
02981 
02982   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
02983   //   operator "" X (ch)
02984   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
02985                                         Lit, Tok.getLocation());
02986 }
02987 
02988 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
02989   unsigned IntSize = Context.getTargetInfo().getIntWidth();
02990   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
02991                                 Context.IntTy, Loc);
02992 }
02993 
02994 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
02995                                   QualType Ty, SourceLocation Loc) {
02996   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
02997 
02998   using llvm::APFloat;
02999   APFloat Val(Format);
03000 
03001   APFloat::opStatus result = Literal.GetFloatValue(Val);
03002 
03003   // Overflow is always an error, but underflow is only an error if
03004   // we underflowed to zero (APFloat reports denormals as underflow).
03005   if ((result & APFloat::opOverflow) ||
03006       ((result & APFloat::opUnderflow) && Val.isZero())) {
03007     unsigned diagnostic;
03008     SmallString<20> buffer;
03009     if (result & APFloat::opOverflow) {
03010       diagnostic = diag::warn_float_overflow;
03011       APFloat::getLargest(Format).toString(buffer);
03012     } else {
03013       diagnostic = diag::warn_float_underflow;
03014       APFloat::getSmallest(Format).toString(buffer);
03015     }
03016 
03017     S.Diag(Loc, diagnostic)
03018       << Ty
03019       << StringRef(buffer.data(), buffer.size());
03020   }
03021 
03022   bool isExact = (result == APFloat::opOK);
03023   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
03024 }
03025 
03026 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
03027   assert(E && "Invalid expression");
03028 
03029   if (E->isValueDependent())
03030     return false;
03031 
03032   QualType QT = E->getType();
03033   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
03034     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
03035     return true;
03036   }
03037 
03038   llvm::APSInt ValueAPS;
03039   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
03040 
03041   if (R.isInvalid())
03042     return true;
03043 
03044   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
03045   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
03046     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
03047         << ValueAPS.toString(10) << ValueIsPositive;
03048     return true;
03049   }
03050 
03051   return false;
03052 }
03053 
03054 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
03055   // Fast path for a single digit (which is quite common).  A single digit
03056   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
03057   if (Tok.getLength() == 1) {
03058     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
03059     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
03060   }
03061 
03062   SmallString<128> SpellingBuffer;
03063   // NumericLiteralParser wants to overread by one character.  Add padding to
03064   // the buffer in case the token is copied to the buffer.  If getSpelling()
03065   // returns a StringRef to the memory buffer, it should have a null char at
03066   // the EOF, so it is also safe.
03067   SpellingBuffer.resize(Tok.getLength() + 1);
03068 
03069   // Get the spelling of the token, which eliminates trigraphs, etc.
03070   bool Invalid = false;
03071   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
03072   if (Invalid)
03073     return ExprError();
03074 
03075   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
03076   if (Literal.hadError)
03077     return ExprError();
03078 
03079   if (Literal.hasUDSuffix()) {
03080     // We're building a user-defined literal.
03081     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
03082     SourceLocation UDSuffixLoc =
03083       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
03084 
03085     // Make sure we're allowed user-defined literals here.
03086     if (!UDLScope)
03087       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
03088 
03089     QualType CookedTy;
03090     if (Literal.isFloatingLiteral()) {
03091       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
03092       // long double, the literal is treated as a call of the form
03093       //   operator "" X (f L)
03094       CookedTy = Context.LongDoubleTy;
03095     } else {
03096       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
03097       // unsigned long long, the literal is treated as a call of the form
03098       //   operator "" X (n ULL)
03099       CookedTy = Context.UnsignedLongLongTy;
03100     }
03101 
03102     DeclarationName OpName =
03103       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
03104     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
03105     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
03106 
03107     SourceLocation TokLoc = Tok.getLocation();
03108 
03109     // Perform literal operator lookup to determine if we're building a raw
03110     // literal or a cooked one.
03111     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
03112     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
03113                                   /*AllowRaw*/true, /*AllowTemplate*/true,
03114                                   /*AllowStringTemplate*/false)) {
03115     case LOLR_Error:
03116       return ExprError();
03117 
03118     case LOLR_Cooked: {
03119       Expr *Lit;
03120       if (Literal.isFloatingLiteral()) {
03121         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
03122       } else {
03123         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
03124         if (Literal.GetIntegerValue(ResultVal))
03125           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
03126               << /* Unsigned */ 1;
03127         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
03128                                      Tok.getLocation());
03129       }
03130       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
03131     }
03132 
03133     case LOLR_Raw: {
03134       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
03135       // literal is treated as a call of the form
03136       //   operator "" X ("n")
03137       unsigned Length = Literal.getUDSuffixOffset();
03138       QualType StrTy = Context.getConstantArrayType(
03139           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
03140           ArrayType::Normal, 0);
03141       Expr *Lit = StringLiteral::Create(
03142           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
03143           /*Pascal*/false, StrTy, &TokLoc, 1);
03144       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
03145     }
03146 
03147     case LOLR_Template: {
03148       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
03149       // template), L is treated as a call fo the form
03150       //   operator "" X <'c1', 'c2', ... 'ck'>()
03151       // where n is the source character sequence c1 c2 ... ck.
03152       TemplateArgumentListInfo ExplicitArgs;
03153       unsigned CharBits = Context.getIntWidth(Context.CharTy);
03154       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
03155       llvm::APSInt Value(CharBits, CharIsUnsigned);
03156       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
03157         Value = TokSpelling[I];
03158         TemplateArgument Arg(Context, Value, Context.CharTy);
03159         TemplateArgumentLocInfo ArgInfo;
03160         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
03161       }
03162       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
03163                                       &ExplicitArgs);
03164     }
03165     case LOLR_StringTemplate:
03166       llvm_unreachable("unexpected literal operator lookup result");
03167     }
03168   }
03169 
03170   Expr *Res;
03171 
03172   if (Literal.isFloatingLiteral()) {
03173     QualType Ty;
03174     if (Literal.isFloat)
03175       Ty = Context.FloatTy;
03176     else if (!Literal.isLong)
03177       Ty = Context.DoubleTy;
03178     else
03179       Ty = Context.LongDoubleTy;
03180 
03181     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
03182 
03183     if (Ty == Context.DoubleTy) {
03184       if (getLangOpts().SinglePrecisionConstants) {
03185         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
03186       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
03187         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
03188         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
03189       }
03190     }
03191   } else if (!Literal.isIntegerLiteral()) {
03192     return ExprError();
03193   } else {
03194     QualType Ty;
03195 
03196     // 'long long' is a C99 or C++11 feature.
03197     if (!getLangOpts().C99 && Literal.isLongLong) {
03198       if (getLangOpts().CPlusPlus)
03199         Diag(Tok.getLocation(),
03200              getLangOpts().CPlusPlus11 ?
03201              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
03202       else
03203         Diag(Tok.getLocation(), diag::ext_c99_longlong);
03204     }
03205 
03206     // Get the value in the widest-possible width.
03207     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
03208     // The microsoft literal suffix extensions support 128-bit literals, which
03209     // may be wider than [u]intmax_t.
03210     // FIXME: Actually, they don't. We seem to have accidentally invented the
03211     //        i128 suffix.
03212     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
03213         Context.getTargetInfo().hasInt128Type())
03214       MaxWidth = 128;
03215     llvm::APInt ResultVal(MaxWidth, 0);
03216 
03217     if (Literal.GetIntegerValue(ResultVal)) {
03218       // If this value didn't fit into uintmax_t, error and force to ull.
03219       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
03220           << /* Unsigned */ 1;
03221       Ty = Context.UnsignedLongLongTy;
03222       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
03223              "long long is not intmax_t?");
03224     } else {
03225       // If this value fits into a ULL, try to figure out what else it fits into
03226       // according to the rules of C99 6.4.4.1p5.
03227 
03228       // Octal, Hexadecimal, and integers with a U suffix are allowed to
03229       // be an unsigned int.
03230       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
03231 
03232       // Check from smallest to largest, picking the smallest type we can.
03233       unsigned Width = 0;
03234 
03235       // Microsoft specific integer suffixes are explicitly sized.
03236       if (Literal.MicrosoftInteger) {
03237         if (Literal.MicrosoftInteger > MaxWidth) {
03238           // If this target doesn't support __int128, error and force to ull.
03239           Diag(Tok.getLocation(), diag::err_int128_unsupported);
03240           Width = MaxWidth;
03241           Ty = Context.getIntMaxType();
03242         } else {
03243           Width = Literal.MicrosoftInteger;
03244           Ty = Context.getIntTypeForBitwidth(Width,
03245                                              /*Signed=*/!Literal.isUnsigned);
03246         }
03247       }
03248 
03249       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
03250         // Are int/unsigned possibilities?
03251         unsigned IntSize = Context.getTargetInfo().getIntWidth();
03252 
03253         // Does it fit in a unsigned int?
03254         if (ResultVal.isIntN(IntSize)) {
03255           // Does it fit in a signed int?
03256           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
03257             Ty = Context.IntTy;
03258           else if (AllowUnsigned)
03259             Ty = Context.UnsignedIntTy;
03260           Width = IntSize;
03261         }
03262       }
03263 
03264       // Are long/unsigned long possibilities?
03265       if (Ty.isNull() && !Literal.isLongLong) {
03266         unsigned LongSize = Context.getTargetInfo().getLongWidth();
03267 
03268         // Does it fit in a unsigned long?
03269         if (ResultVal.isIntN(LongSize)) {
03270           // Does it fit in a signed long?
03271           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
03272             Ty = Context.LongTy;
03273           else if (AllowUnsigned)
03274             Ty = Context.UnsignedLongTy;
03275           Width = LongSize;
03276         }
03277       }
03278 
03279       // Check long long if needed.
03280       if (Ty.isNull()) {
03281         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
03282 
03283         // Does it fit in a unsigned long long?
03284         if (ResultVal.isIntN(LongLongSize)) {
03285           // Does it fit in a signed long long?
03286           // To be compatible with MSVC, hex integer literals ending with the
03287           // LL or i64 suffix are always signed in Microsoft mode.
03288           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
03289               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
03290             Ty = Context.LongLongTy;
03291           else if (AllowUnsigned)
03292             Ty = Context.UnsignedLongLongTy;
03293           Width = LongLongSize;
03294         }
03295       }
03296 
03297       // If we still couldn't decide a type, we probably have something that
03298       // does not fit in a signed long long, but has no U suffix.
03299       if (Ty.isNull()) {
03300         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
03301         Ty = Context.UnsignedLongLongTy;
03302         Width = Context.getTargetInfo().getLongLongWidth();
03303       }
03304 
03305       if (ResultVal.getBitWidth() != Width)
03306         ResultVal = ResultVal.trunc(Width);
03307     }
03308     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
03309   }
03310 
03311   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
03312   if (Literal.isImaginary)
03313     Res = new (Context) ImaginaryLiteral(Res,
03314                                         Context.getComplexType(Res->getType()));
03315 
03316   return Res;
03317 }
03318 
03319 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
03320   assert(E && "ActOnParenExpr() missing expr");
03321   return new (Context) ParenExpr(L, R, E);
03322 }
03323 
03324 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
03325                                          SourceLocation Loc,
03326                                          SourceRange ArgRange) {
03327   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
03328   // scalar or vector data type argument..."
03329   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
03330   // type (C99 6.2.5p18) or void.
03331   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
03332     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
03333       << T << ArgRange;
03334     return true;
03335   }
03336 
03337   assert((T->isVoidType() || !T->isIncompleteType()) &&
03338          "Scalar types should always be complete");
03339   return false;
03340 }
03341 
03342 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
03343                                            SourceLocation Loc,
03344                                            SourceRange ArgRange,
03345                                            UnaryExprOrTypeTrait TraitKind) {
03346   // Invalid types must be hard errors for SFINAE in C++.
03347   if (S.LangOpts.CPlusPlus)
03348     return true;
03349 
03350   // C99 6.5.3.4p1:
03351   if (T->isFunctionType() &&
03352       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
03353     // sizeof(function)/alignof(function) is allowed as an extension.
03354     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
03355       << TraitKind << ArgRange;
03356     return false;
03357   }
03358 
03359   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
03360   // this is an error (OpenCL v1.1 s6.3.k)
03361   if (T->isVoidType()) {
03362     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
03363                                         : diag::ext_sizeof_alignof_void_type;
03364     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
03365     return false;
03366   }
03367 
03368   return true;
03369 }
03370 
03371 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
03372                                              SourceLocation Loc,
03373                                              SourceRange ArgRange,
03374                                              UnaryExprOrTypeTrait TraitKind) {
03375   // Reject sizeof(interface) and sizeof(interface<proto>) if the
03376   // runtime doesn't allow it.
03377   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
03378     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
03379       << T << (TraitKind == UETT_SizeOf)
03380       << ArgRange;
03381     return true;
03382   }
03383 
03384   return false;
03385 }
03386 
03387 /// \brief Check whether E is a pointer from a decayed array type (the decayed
03388 /// pointer type is equal to T) and emit a warning if it is.
03389 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
03390                                      Expr *E) {
03391   // Don't warn if the operation changed the type.
03392   if (T != E->getType())
03393     return;
03394 
03395   // Now look for array decays.
03396   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
03397   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
03398     return;
03399 
03400   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
03401                                              << ICE->getType()
03402                                              << ICE->getSubExpr()->getType();
03403 }
03404 
03405 /// \brief Check the constraints on expression operands to unary type expression
03406 /// and type traits.
03407 ///
03408 /// Completes any types necessary and validates the constraints on the operand
03409 /// expression. The logic mostly mirrors the type-based overload, but may modify
03410 /// the expression as it completes the type for that expression through template
03411 /// instantiation, etc.
03412 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
03413                                             UnaryExprOrTypeTrait ExprKind) {
03414   QualType ExprTy = E->getType();
03415   assert(!ExprTy->isReferenceType());
03416 
03417   if (ExprKind == UETT_VecStep)
03418     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
03419                                         E->getSourceRange());
03420 
03421   // Whitelist some types as extensions
03422   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
03423                                       E->getSourceRange(), ExprKind))
03424     return false;
03425 
03426   // 'alignof' applied to an expression only requires the base element type of
03427   // the expression to be complete. 'sizeof' requires the expression's type to
03428   // be complete (and will attempt to complete it if it's an array of unknown
03429   // bound).
03430   if (ExprKind == UETT_AlignOf) {
03431     if (RequireCompleteType(E->getExprLoc(),
03432                             Context.getBaseElementType(E->getType()),
03433                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
03434                             E->getSourceRange()))
03435       return true;
03436   } else {
03437     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
03438                                 ExprKind, E->getSourceRange()))
03439       return true;
03440   }
03441 
03442   // Completing the expression's type may have changed it.
03443   ExprTy = E->getType();
03444   assert(!ExprTy->isReferenceType());
03445 
03446   if (ExprTy->isFunctionType()) {
03447     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
03448       << ExprKind << E->getSourceRange();
03449     return true;
03450   }
03451 
03452   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
03453                                        E->getSourceRange(), ExprKind))
03454     return true;
03455 
03456   if (ExprKind == UETT_SizeOf) {
03457     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
03458       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
03459         QualType OType = PVD->getOriginalType();
03460         QualType Type = PVD->getType();
03461         if (Type->isPointerType() && OType->isArrayType()) {
03462           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
03463             << Type << OType;
03464           Diag(PVD->getLocation(), diag::note_declared_at);
03465         }
03466       }
03467     }
03468 
03469     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
03470     // decays into a pointer and returns an unintended result. This is most
03471     // likely a typo for "sizeof(array) op x".
03472     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
03473       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
03474                                BO->getLHS());
03475       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
03476                                BO->getRHS());
03477     }
03478   }
03479 
03480   return false;
03481 }
03482 
03483 /// \brief Check the constraints on operands to unary expression and type
03484 /// traits.
03485 ///
03486 /// This will complete any types necessary, and validate the various constraints
03487 /// on those operands.
03488 ///
03489 /// The UsualUnaryConversions() function is *not* called by this routine.
03490 /// C99 6.3.2.1p[2-4] all state:
03491 ///   Except when it is the operand of the sizeof operator ...
03492 ///
03493 /// C++ [expr.sizeof]p4
03494 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
03495 ///   standard conversions are not applied to the operand of sizeof.
03496 ///
03497 /// This policy is followed for all of the unary trait expressions.
03498 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
03499                                             SourceLocation OpLoc,
03500                                             SourceRange ExprRange,
03501                                             UnaryExprOrTypeTrait ExprKind) {
03502   if (ExprType->isDependentType())
03503     return false;
03504 
03505   // C++ [expr.sizeof]p2:
03506   //     When applied to a reference or a reference type, the result
03507   //     is the size of the referenced type.
03508   // C++11 [expr.alignof]p3:
03509   //     When alignof is applied to a reference type, the result
03510   //     shall be the alignment of the referenced type.
03511   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
03512     ExprType = Ref->getPointeeType();
03513 
03514   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
03515   //   When alignof or _Alignof is applied to an array type, the result
03516   //   is the alignment of the element type.
03517   if (ExprKind == UETT_AlignOf)
03518     ExprType = Context.getBaseElementType(ExprType);
03519 
03520   if (ExprKind == UETT_VecStep)
03521     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
03522 
03523   // Whitelist some types as extensions
03524   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
03525                                       ExprKind))
03526     return false;
03527 
03528   if (RequireCompleteType(OpLoc, ExprType,
03529                           diag::err_sizeof_alignof_incomplete_type,
03530                           ExprKind, ExprRange))
03531     return true;
03532 
03533   if (ExprType->isFunctionType()) {
03534     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
03535       << ExprKind << ExprRange;
03536     return true;
03537   }
03538 
03539   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
03540                                        ExprKind))
03541     return true;
03542 
03543   return false;
03544 }
03545 
03546 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
03547   E = E->IgnoreParens();
03548 
03549   // Cannot know anything else if the expression is dependent.
03550   if (E->isTypeDependent())
03551     return false;
03552 
03553   if (E->getObjectKind() == OK_BitField) {
03554     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
03555        << 1 << E->getSourceRange();
03556     return true;
03557   }
03558 
03559   ValueDecl *D = nullptr;
03560   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
03561     D = DRE->getDecl();
03562   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
03563     D = ME->getMemberDecl();
03564   }
03565 
03566   // If it's a field, require the containing struct to have a
03567   // complete definition so that we can compute the layout.
03568   //
03569   // This can happen in C++11 onwards, either by naming the member
03570   // in a way that is not transformed into a member access expression
03571   // (in an unevaluated operand, for instance), or by naming the member
03572   // in a trailing-return-type.
03573   //
03574   // For the record, since __alignof__ on expressions is a GCC
03575   // extension, GCC seems to permit this but always gives the
03576   // nonsensical answer 0.
03577   //
03578   // We don't really need the layout here --- we could instead just
03579   // directly check for all the appropriate alignment-lowing
03580   // attributes --- but that would require duplicating a lot of
03581   // logic that just isn't worth duplicating for such a marginal
03582   // use-case.
03583   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
03584     // Fast path this check, since we at least know the record has a
03585     // definition if we can find a member of it.
03586     if (!FD->getParent()->isCompleteDefinition()) {
03587       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
03588         << E->getSourceRange();
03589       return true;
03590     }
03591 
03592     // Otherwise, if it's a field, and the field doesn't have
03593     // reference type, then it must have a complete type (or be a
03594     // flexible array member, which we explicitly want to
03595     // white-list anyway), which makes the following checks trivial.
03596     if (!FD->getType()->isReferenceType())
03597       return false;
03598   }
03599 
03600   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
03601 }
03602 
03603 bool Sema::CheckVecStepExpr(Expr *E) {
03604   E = E->IgnoreParens();
03605 
03606   // Cannot know anything else if the expression is dependent.
03607   if (E->isTypeDependent())
03608     return false;
03609 
03610   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
03611 }
03612 
03613 /// \brief Build a sizeof or alignof expression given a type operand.
03614 ExprResult
03615 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
03616                                      SourceLocation OpLoc,
03617                                      UnaryExprOrTypeTrait ExprKind,
03618                                      SourceRange R) {
03619   if (!TInfo)
03620     return ExprError();
03621 
03622   QualType T = TInfo->getType();
03623 
03624   if (!T->isDependentType() &&
03625       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
03626     return ExprError();
03627 
03628   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
03629   return new (Context) UnaryExprOrTypeTraitExpr(
03630       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
03631 }
03632 
03633 /// \brief Build a sizeof or alignof expression given an expression
03634 /// operand.
03635 ExprResult
03636 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
03637                                      UnaryExprOrTypeTrait ExprKind) {
03638   ExprResult PE = CheckPlaceholderExpr(E);
03639   if (PE.isInvalid()) 
03640     return ExprError();
03641 
03642   E = PE.get();
03643   
03644   // Verify that the operand is valid.
03645   bool isInvalid = false;
03646   if (E->isTypeDependent()) {
03647     // Delay type-checking for type-dependent expressions.
03648   } else if (ExprKind == UETT_AlignOf) {
03649     isInvalid = CheckAlignOfExpr(*this, E);
03650   } else if (ExprKind == UETT_VecStep) {
03651     isInvalid = CheckVecStepExpr(E);
03652   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
03653     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
03654     isInvalid = true;
03655   } else {
03656     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
03657   }
03658 
03659   if (isInvalid)
03660     return ExprError();
03661 
03662   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
03663     PE = TransformToPotentiallyEvaluated(E);
03664     if (PE.isInvalid()) return ExprError();
03665     E = PE.get();
03666   }
03667 
03668   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
03669   return new (Context) UnaryExprOrTypeTraitExpr(
03670       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
03671 }
03672 
03673 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
03674 /// expr and the same for @c alignof and @c __alignof
03675 /// Note that the ArgRange is invalid if isType is false.
03676 ExprResult
03677 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
03678                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
03679                                     void *TyOrEx, const SourceRange &ArgRange) {
03680   // If error parsing type, ignore.
03681   if (!TyOrEx) return ExprError();
03682 
03683   if (IsType) {
03684     TypeSourceInfo *TInfo;
03685     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
03686     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
03687   }
03688 
03689   Expr *ArgEx = (Expr *)TyOrEx;
03690   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
03691   return Result;
03692 }
03693 
03694 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
03695                                      bool IsReal) {
03696   if (V.get()->isTypeDependent())
03697     return S.Context.DependentTy;
03698 
03699   // _Real and _Imag are only l-values for normal l-values.
03700   if (V.get()->getObjectKind() != OK_Ordinary) {
03701     V = S.DefaultLvalueConversion(V.get());
03702     if (V.isInvalid())
03703       return QualType();
03704   }
03705 
03706   // These operators return the element type of a complex type.
03707   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
03708     return CT->getElementType();
03709 
03710   // Otherwise they pass through real integer and floating point types here.
03711   if (V.get()->getType()->isArithmeticType())
03712     return V.get()->getType();
03713 
03714   // Test for placeholders.
03715   ExprResult PR = S.CheckPlaceholderExpr(V.get());
03716   if (PR.isInvalid()) return QualType();
03717   if (PR.get() != V.get()) {
03718     V = PR;
03719     return CheckRealImagOperand(S, V, Loc, IsReal);
03720   }
03721 
03722   // Reject anything else.
03723   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
03724     << (IsReal ? "__real" : "__imag");
03725   return QualType();
03726 }
03727 
03728 
03729 
03730 ExprResult
03731 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
03732                           tok::TokenKind Kind, Expr *Input) {
03733   UnaryOperatorKind Opc;
03734   switch (Kind) {
03735   default: llvm_unreachable("Unknown unary op!");
03736   case tok::plusplus:   Opc = UO_PostInc; break;
03737   case tok::minusminus: Opc = UO_PostDec; break;
03738   }
03739 
03740   // Since this might is a postfix expression, get rid of ParenListExprs.
03741   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
03742   if (Result.isInvalid()) return ExprError();
03743   Input = Result.get();
03744 
03745   return BuildUnaryOp(S, OpLoc, Opc, Input);
03746 }
03747 
03748 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
03749 ///
03750 /// \return true on error
03751 static bool checkArithmeticOnObjCPointer(Sema &S,
03752                                          SourceLocation opLoc,
03753                                          Expr *op) {
03754   assert(op->getType()->isObjCObjectPointerType());
03755   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
03756       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
03757     return false;
03758 
03759   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
03760     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
03761     << op->getSourceRange();
03762   return true;
03763 }
03764 
03765 ExprResult
03766 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
03767                               Expr *idx, SourceLocation rbLoc) {
03768   // Since this might be a postfix expression, get rid of ParenListExprs.
03769   if (isa<ParenListExpr>(base)) {
03770     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
03771     if (result.isInvalid()) return ExprError();
03772     base = result.get();
03773   }
03774 
03775   // Handle any non-overload placeholder types in the base and index
03776   // expressions.  We can't handle overloads here because the other
03777   // operand might be an overloadable type, in which case the overload
03778   // resolution for the operator overload should get the first crack
03779   // at the overload.
03780   if (base->getType()->isNonOverloadPlaceholderType()) {
03781     ExprResult result = CheckPlaceholderExpr(base);
03782     if (result.isInvalid()) return ExprError();
03783     base = result.get();
03784   }
03785   if (idx->getType()->isNonOverloadPlaceholderType()) {
03786     ExprResult result = CheckPlaceholderExpr(idx);
03787     if (result.isInvalid()) return ExprError();
03788     idx = result.get();
03789   }
03790 
03791   // Build an unanalyzed expression if either operand is type-dependent.
03792   if (getLangOpts().CPlusPlus &&
03793       (base->isTypeDependent() || idx->isTypeDependent())) {
03794     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
03795                                             VK_LValue, OK_Ordinary, rbLoc);
03796   }
03797 
03798   // Use C++ overloaded-operator rules if either operand has record
03799   // type.  The spec says to do this if either type is *overloadable*,
03800   // but enum types can't declare subscript operators or conversion
03801   // operators, so there's nothing interesting for overload resolution
03802   // to do if there aren't any record types involved.
03803   //
03804   // ObjC pointers have their own subscripting logic that is not tied
03805   // to overload resolution and so should not take this path.
03806   if (getLangOpts().CPlusPlus &&
03807       (base->getType()->isRecordType() ||
03808        (!base->getType()->isObjCObjectPointerType() &&
03809         idx->getType()->isRecordType()))) {
03810     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
03811   }
03812 
03813   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
03814 }
03815 
03816 ExprResult
03817 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
03818                                       Expr *Idx, SourceLocation RLoc) {
03819   Expr *LHSExp = Base;
03820   Expr *RHSExp = Idx;
03821 
03822   // Perform default conversions.
03823   if (!LHSExp->getType()->getAs<VectorType>()) {
03824     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
03825     if (Result.isInvalid())
03826       return ExprError();
03827     LHSExp = Result.get();
03828   }
03829   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
03830   if (Result.isInvalid())
03831     return ExprError();
03832   RHSExp = Result.get();
03833 
03834   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
03835   ExprValueKind VK = VK_LValue;
03836   ExprObjectKind OK = OK_Ordinary;
03837 
03838   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
03839   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
03840   // in the subscript position. As a result, we need to derive the array base
03841   // and index from the expression types.
03842   Expr *BaseExpr, *IndexExpr;
03843   QualType ResultType;
03844   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
03845     BaseExpr = LHSExp;
03846     IndexExpr = RHSExp;
03847     ResultType = Context.DependentTy;
03848   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
03849     BaseExpr = LHSExp;
03850     IndexExpr = RHSExp;
03851     ResultType = PTy->getPointeeType();
03852   } else if (const ObjCObjectPointerType *PTy =
03853                LHSTy->getAs<ObjCObjectPointerType>()) {
03854     BaseExpr = LHSExp;
03855     IndexExpr = RHSExp;
03856 
03857     // Use custom logic if this should be the pseudo-object subscript
03858     // expression.
03859     if (!LangOpts.isSubscriptPointerArithmetic())
03860       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
03861                                           nullptr);
03862 
03863     ResultType = PTy->getPointeeType();
03864   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
03865      // Handle the uncommon case of "123[Ptr]".
03866     BaseExpr = RHSExp;
03867     IndexExpr = LHSExp;
03868     ResultType = PTy->getPointeeType();
03869   } else if (const ObjCObjectPointerType *PTy =
03870                RHSTy->getAs<ObjCObjectPointerType>()) {
03871      // Handle the uncommon case of "123[Ptr]".
03872     BaseExpr = RHSExp;
03873     IndexExpr = LHSExp;
03874     ResultType = PTy->getPointeeType();
03875     if (!LangOpts.isSubscriptPointerArithmetic()) {
03876       Diag(LLoc, diag::err_subscript_nonfragile_interface)
03877         << ResultType << BaseExpr->getSourceRange();
03878       return ExprError();
03879     }
03880   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
03881     BaseExpr = LHSExp;    // vectors: V[123]
03882     IndexExpr = RHSExp;
03883     VK = LHSExp->getValueKind();
03884     if (VK != VK_RValue)
03885       OK = OK_VectorComponent;
03886 
03887     // FIXME: need to deal with const...
03888     ResultType = VTy->getElementType();
03889   } else if (LHSTy->isArrayType()) {
03890     // If we see an array that wasn't promoted by
03891     // DefaultFunctionArrayLvalueConversion, it must be an array that
03892     // wasn't promoted because of the C90 rule that doesn't
03893     // allow promoting non-lvalue arrays.  Warn, then
03894     // force the promotion here.
03895     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
03896         LHSExp->getSourceRange();
03897     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
03898                                CK_ArrayToPointerDecay).get();
03899     LHSTy = LHSExp->getType();
03900 
03901     BaseExpr = LHSExp;
03902     IndexExpr = RHSExp;
03903     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
03904   } else if (RHSTy->isArrayType()) {
03905     // Same as previous, except for 123[f().a] case
03906     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
03907         RHSExp->getSourceRange();
03908     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
03909                                CK_ArrayToPointerDecay).get();
03910     RHSTy = RHSExp->getType();
03911 
03912     BaseExpr = RHSExp;
03913     IndexExpr = LHSExp;
03914     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
03915   } else {
03916     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
03917        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
03918   }
03919   // C99 6.5.2.1p1
03920   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
03921     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
03922                      << IndexExpr->getSourceRange());
03923 
03924   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
03925        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
03926          && !IndexExpr->isTypeDependent())
03927     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
03928 
03929   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
03930   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
03931   // type. Note that Functions are not objects, and that (in C99 parlance)
03932   // incomplete types are not object types.
03933   if (ResultType->isFunctionType()) {
03934     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
03935       << ResultType << BaseExpr->getSourceRange();
03936     return ExprError();
03937   }
03938 
03939   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
03940     // GNU extension: subscripting on pointer to void
03941     Diag(LLoc, diag::ext_gnu_subscript_void_type)
03942       << BaseExpr->getSourceRange();
03943 
03944     // C forbids expressions of unqualified void type from being l-values.
03945     // See IsCForbiddenLValueType.
03946     if (!ResultType.hasQualifiers()) VK = VK_RValue;
03947   } else if (!ResultType->isDependentType() &&
03948       RequireCompleteType(LLoc, ResultType,
03949                           diag::err_subscript_incomplete_type, BaseExpr))
03950     return ExprError();
03951 
03952   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
03953          !ResultType.isCForbiddenLValueType());
03954 
03955   return new (Context)
03956       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
03957 }
03958 
03959 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
03960                                         FunctionDecl *FD,
03961                                         ParmVarDecl *Param) {
03962   if (Param->hasUnparsedDefaultArg()) {
03963     Diag(CallLoc,
03964          diag::err_use_of_default_argument_to_function_declared_later) <<
03965       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
03966     Diag(UnparsedDefaultArgLocs[Param],
03967          diag::note_default_argument_declared_here);
03968     return ExprError();
03969   }
03970   
03971   if (Param->hasUninstantiatedDefaultArg()) {
03972     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
03973 
03974     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
03975                                                  Param);
03976 
03977     // Instantiate the expression.
03978     MultiLevelTemplateArgumentList MutiLevelArgList
03979       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
03980 
03981     InstantiatingTemplate Inst(*this, CallLoc, Param,
03982                                MutiLevelArgList.getInnermost());
03983     if (Inst.isInvalid())
03984       return ExprError();
03985 
03986     ExprResult Result;
03987     {
03988       // C++ [dcl.fct.default]p5:
03989       //   The names in the [default argument] expression are bound, and
03990       //   the semantic constraints are checked, at the point where the
03991       //   default argument expression appears.
03992       ContextRAII SavedContext(*this, FD);
03993       LocalInstantiationScope Local(*this);
03994       Result = SubstExpr(UninstExpr, MutiLevelArgList);
03995     }
03996     if (Result.isInvalid())
03997       return ExprError();
03998 
03999     // Check the expression as an initializer for the parameter.
04000     InitializedEntity Entity
04001       = InitializedEntity::InitializeParameter(Context, Param);
04002     InitializationKind Kind
04003       = InitializationKind::CreateCopy(Param->getLocation(),
04004              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
04005     Expr *ResultE = Result.getAs<Expr>();
04006 
04007     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
04008     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
04009     if (Result.isInvalid())
04010       return ExprError();
04011 
04012     Expr *Arg = Result.getAs<Expr>();
04013     CheckCompletedExpr(Arg, Param->getOuterLocStart());
04014     // Build the default argument expression.
04015     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
04016   }
04017 
04018   // If the default expression creates temporaries, we need to
04019   // push them to the current stack of expression temporaries so they'll
04020   // be properly destroyed.
04021   // FIXME: We should really be rebuilding the default argument with new
04022   // bound temporaries; see the comment in PR5810.
04023   // We don't need to do that with block decls, though, because
04024   // blocks in default argument expression can never capture anything.
04025   if (isa<ExprWithCleanups>(Param->getInit())) {
04026     // Set the "needs cleanups" bit regardless of whether there are
04027     // any explicit objects.
04028     ExprNeedsCleanups = true;
04029 
04030     // Append all the objects to the cleanup list.  Right now, this
04031     // should always be a no-op, because blocks in default argument
04032     // expressions should never be able to capture anything.
04033     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
04034            "default argument expression has capturing blocks?");
04035   }
04036 
04037   // We already type-checked the argument, so we know it works. 
04038   // Just mark all of the declarations in this potentially-evaluated expression
04039   // as being "referenced".
04040   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
04041                                    /*SkipLocalVariables=*/true);
04042   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
04043 }
04044 
04045 
04046 Sema::VariadicCallType
04047 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
04048                           Expr *Fn) {
04049   if (Proto && Proto->isVariadic()) {
04050     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
04051       return VariadicConstructor;
04052     else if (Fn && Fn->getType()->isBlockPointerType())
04053       return VariadicBlock;
04054     else if (FDecl) {
04055       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
04056         if (Method->isInstance())
04057           return VariadicMethod;
04058     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
04059       return VariadicMethod;
04060     return VariadicFunction;
04061   }
04062   return VariadicDoesNotApply;
04063 }
04064 
04065 namespace {
04066 class FunctionCallCCC : public FunctionCallFilterCCC {
04067 public:
04068   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
04069                   unsigned NumArgs, MemberExpr *ME)
04070       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
04071         FunctionName(FuncName) {}
04072 
04073   bool ValidateCandidate(const TypoCorrection &candidate) override {
04074     if (!candidate.getCorrectionSpecifier() ||
04075         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
04076       return false;
04077     }
04078 
04079     return FunctionCallFilterCCC::ValidateCandidate(candidate);
04080   }
04081 
04082 private:
04083   const IdentifierInfo *const FunctionName;
04084 };
04085 }
04086 
04087 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
04088                                                FunctionDecl *FDecl,
04089                                                ArrayRef<Expr *> Args) {
04090   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
04091   DeclarationName FuncName = FDecl->getDeclName();
04092   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
04093 
04094   if (TypoCorrection Corrected = S.CorrectTypo(
04095           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
04096           S.getScopeForContext(S.CurContext), nullptr,
04097           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
04098                                              Args.size(), ME),
04099           Sema::CTK_ErrorRecovery)) {
04100     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
04101       if (Corrected.isOverloaded()) {
04102         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
04103         OverloadCandidateSet::iterator Best;
04104         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
04105                                            CDEnd = Corrected.end();
04106              CD != CDEnd; ++CD) {
04107           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
04108             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
04109                                    OCS);
04110         }
04111         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
04112         case OR_Success:
04113           ND = Best->Function;
04114           Corrected.setCorrectionDecl(ND);
04115           break;
04116         default:
04117           break;
04118         }
04119       }
04120       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
04121         return Corrected;
04122       }
04123     }
04124   }
04125   return TypoCorrection();
04126 }
04127 
04128 /// ConvertArgumentsForCall - Converts the arguments specified in
04129 /// Args/NumArgs to the parameter types of the function FDecl with
04130 /// function prototype Proto. Call is the call expression itself, and
04131 /// Fn is the function expression. For a C++ member function, this
04132 /// routine does not attempt to convert the object argument. Returns
04133 /// true if the call is ill-formed.
04134 bool
04135 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
04136                               FunctionDecl *FDecl,
04137                               const FunctionProtoType *Proto,
04138                               ArrayRef<Expr *> Args,
04139                               SourceLocation RParenLoc,
04140                               bool IsExecConfig) {
04141   // Bail out early if calling a builtin with custom typechecking.
04142   // We don't need to do this in the 
04143   if (FDecl)
04144     if (unsigned ID = FDecl->getBuiltinID())
04145       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
04146         return false;
04147 
04148   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
04149   // assignment, to the types of the corresponding parameter, ...
04150   unsigned NumParams = Proto->getNumParams();
04151   bool Invalid = false;
04152   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
04153   unsigned FnKind = Fn->getType()->isBlockPointerType()
04154                        ? 1 /* block */
04155                        : (IsExecConfig ? 3 /* kernel function (exec config) */
04156                                        : 0 /* function */);
04157 
04158   // If too few arguments are available (and we don't have default
04159   // arguments for the remaining parameters), don't make the call.
04160   if (Args.size() < NumParams) {
04161     if (Args.size() < MinArgs) {
04162       TypoCorrection TC;
04163       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
04164         unsigned diag_id =
04165             MinArgs == NumParams && !Proto->isVariadic()
04166                 ? diag::err_typecheck_call_too_few_args_suggest
04167                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
04168         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
04169                                         << static_cast<unsigned>(Args.size())
04170                                         << TC.getCorrectionRange());
04171       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
04172         Diag(RParenLoc,
04173              MinArgs == NumParams && !Proto->isVariadic()
04174                  ? diag::err_typecheck_call_too_few_args_one
04175                  : diag::err_typecheck_call_too_few_args_at_least_one)
04176             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
04177       else
04178         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
04179                             ? diag::err_typecheck_call_too_few_args
04180                             : diag::err_typecheck_call_too_few_args_at_least)
04181             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
04182             << Fn->getSourceRange();
04183 
04184       // Emit the location of the prototype.
04185       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
04186         Diag(FDecl->getLocStart(), diag::note_callee_decl)
04187           << FDecl;
04188 
04189       return true;
04190     }
04191     Call->setNumArgs(Context, NumParams);
04192   }
04193 
04194   // If too many are passed and not variadic, error on the extras and drop
04195   // them.
04196   if (Args.size() > NumParams) {
04197     if (!Proto->isVariadic()) {
04198       TypoCorrection TC;
04199       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
04200         unsigned diag_id =
04201             MinArgs == NumParams && !Proto->isVariadic()
04202                 ? diag::err_typecheck_call_too_many_args_suggest
04203                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
04204         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
04205                                         << static_cast<unsigned>(Args.size())
04206                                         << TC.getCorrectionRange());
04207       } else if (NumParams == 1 && FDecl &&
04208                  FDecl->getParamDecl(0)->getDeclName())
04209         Diag(Args[NumParams]->getLocStart(),
04210              MinArgs == NumParams
04211                  ? diag::err_typecheck_call_too_many_args_one
04212                  : diag::err_typecheck_call_too_many_args_at_most_one)
04213             << FnKind << FDecl->getParamDecl(0)
04214             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
04215             << SourceRange(Args[NumParams]->getLocStart(),
04216                            Args.back()->getLocEnd());
04217       else
04218         Diag(Args[NumParams]->getLocStart(),
04219              MinArgs == NumParams
04220                  ? diag::err_typecheck_call_too_many_args
04221                  : diag::err_typecheck_call_too_many_args_at_most)
04222             << FnKind << NumParams << static_cast<unsigned>(Args.size())
04223             << Fn->getSourceRange()
04224             << SourceRange(Args[NumParams]->getLocStart(),
04225                            Args.back()->getLocEnd());
04226 
04227       // Emit the location of the prototype.
04228       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
04229         Diag(FDecl->getLocStart(), diag::note_callee_decl)
04230           << FDecl;
04231       
04232       // This deletes the extra arguments.
04233       Call->setNumArgs(Context, NumParams);
04234       return true;
04235     }
04236   }
04237   SmallVector<Expr *, 8> AllArgs;
04238   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
04239   
04240   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
04241                                    Proto, 0, Args, AllArgs, CallType);
04242   if (Invalid)
04243     return true;
04244   unsigned TotalNumArgs = AllArgs.size();
04245   for (unsigned i = 0; i < TotalNumArgs; ++i)
04246     Call->setArg(i, AllArgs[i]);
04247 
04248   return false;
04249 }
04250 
04251 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
04252                                   const FunctionProtoType *Proto,
04253                                   unsigned FirstParam, ArrayRef<Expr *> Args,
04254                                   SmallVectorImpl<Expr *> &AllArgs,
04255                                   VariadicCallType CallType, bool AllowExplicit,
04256                                   bool IsListInitialization) {
04257   unsigned NumParams = Proto->getNumParams();
04258   bool Invalid = false;
04259   unsigned ArgIx = 0;
04260   // Continue to check argument types (even if we have too few/many args).
04261   for (unsigned i = FirstParam; i < NumParams; i++) {
04262     QualType ProtoArgType = Proto->getParamType(i);
04263 
04264     Expr *Arg;
04265     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
04266     if (ArgIx < Args.size()) {
04267       Arg = Args[ArgIx++];
04268 
04269       if (RequireCompleteType(Arg->getLocStart(),
04270                               ProtoArgType,
04271                               diag::err_call_incomplete_argument, Arg))
04272         return true;
04273 
04274       // Strip the unbridged-cast placeholder expression off, if applicable.
04275       bool CFAudited = false;
04276       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
04277           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
04278           (!Param || !Param->hasAttr<CFConsumedAttr>()))
04279         Arg = stripARCUnbridgedCast(Arg);
04280       else if (getLangOpts().ObjCAutoRefCount &&
04281                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
04282                (!Param || !Param->hasAttr<CFConsumedAttr>()))
04283         CFAudited = true;
04284 
04285       InitializedEntity Entity =
04286           Param ? InitializedEntity::InitializeParameter(Context, Param,
04287                                                          ProtoArgType)
04288                 : InitializedEntity::InitializeParameter(
04289                       Context, ProtoArgType, Proto->isParamConsumed(i));
04290 
04291       // Remember that parameter belongs to a CF audited API.
04292       if (CFAudited)
04293         Entity.setParameterCFAudited();
04294 
04295       ExprResult ArgE = PerformCopyInitialization(
04296           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
04297       if (ArgE.isInvalid())
04298         return true;
04299 
04300       Arg = ArgE.getAs<Expr>();
04301     } else {
04302       assert(Param && "can't use default arguments without a known callee");
04303 
04304       ExprResult ArgExpr =
04305         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
04306       if (ArgExpr.isInvalid())
04307         return true;
04308 
04309       Arg = ArgExpr.getAs<Expr>();
04310     }
04311 
04312     // Check for array bounds violations for each argument to the call. This
04313     // check only triggers warnings when the argument isn't a more complex Expr
04314     // with its own checking, such as a BinaryOperator.
04315     CheckArrayAccess(Arg);
04316 
04317     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
04318     CheckStaticArrayArgument(CallLoc, Param, Arg);
04319 
04320     AllArgs.push_back(Arg);
04321   }
04322 
04323   // If this is a variadic call, handle args passed through "...".
04324   if (CallType != VariadicDoesNotApply) {
04325     // Assume that extern "C" functions with variadic arguments that
04326     // return __unknown_anytype aren't *really* variadic.
04327     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
04328         FDecl->isExternC()) {
04329       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
04330         QualType paramType; // ignored
04331         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
04332         Invalid |= arg.isInvalid();
04333         AllArgs.push_back(arg.get());
04334       }
04335 
04336     // Otherwise do argument promotion, (C99 6.5.2.2p7).
04337     } else {
04338       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
04339         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
04340                                                           FDecl);
04341         Invalid |= Arg.isInvalid();
04342         AllArgs.push_back(Arg.get());
04343       }
04344     }
04345 
04346     // Check for array bounds violations.
04347     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
04348       CheckArrayAccess(Args[i]);
04349   }
04350   return Invalid;
04351 }
04352 
04353 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
04354   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
04355   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
04356     TL = DTL.getOriginalLoc();
04357   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
04358     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
04359       << ATL.getLocalSourceRange();
04360 }
04361 
04362 /// CheckStaticArrayArgument - If the given argument corresponds to a static
04363 /// array parameter, check that it is non-null, and that if it is formed by
04364 /// array-to-pointer decay, the underlying array is sufficiently large.
04365 ///
04366 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
04367 /// array type derivation, then for each call to the function, the value of the
04368 /// corresponding actual argument shall provide access to the first element of
04369 /// an array with at least as many elements as specified by the size expression.
04370 void
04371 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
04372                                ParmVarDecl *Param,
04373                                const Expr *ArgExpr) {
04374   // Static array parameters are not supported in C++.
04375   if (!Param || getLangOpts().CPlusPlus)
04376     return;
04377 
04378   QualType OrigTy = Param->getOriginalType();
04379 
04380   const ArrayType *AT = Context.getAsArrayType(OrigTy);
04381   if (!AT || AT->getSizeModifier() != ArrayType::Static)
04382     return;
04383 
04384   if (ArgExpr->isNullPointerConstant(Context,
04385                                      Expr::NPC_NeverValueDependent)) {
04386     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
04387     DiagnoseCalleeStaticArrayParam(*this, Param);
04388     return;
04389   }
04390 
04391   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
04392   if (!CAT)
04393     return;
04394 
04395   const ConstantArrayType *ArgCAT =
04396     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
04397   if (!ArgCAT)
04398     return;
04399 
04400   if (ArgCAT->getSize().ult(CAT->getSize())) {
04401     Diag(CallLoc, diag::warn_static_array_too_small)
04402       << ArgExpr->getSourceRange()
04403       << (unsigned) ArgCAT->getSize().getZExtValue()
04404       << (unsigned) CAT->getSize().getZExtValue();
04405     DiagnoseCalleeStaticArrayParam(*this, Param);
04406   }
04407 }
04408 
04409 /// Given a function expression of unknown-any type, try to rebuild it
04410 /// to have a function type.
04411 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
04412 
04413 /// Is the given type a placeholder that we need to lower out
04414 /// immediately during argument processing?
04415 static bool isPlaceholderToRemoveAsArg(QualType type) {
04416   // Placeholders are never sugared.
04417   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
04418   if (!placeholder) return false;
04419 
04420   switch (placeholder->getKind()) {
04421   // Ignore all the non-placeholder types.
04422 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
04423 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
04424 #include "clang/AST/BuiltinTypes.def"
04425     return false;
04426 
04427   // We cannot lower out overload sets; they might validly be resolved
04428   // by the call machinery.
04429   case BuiltinType::Overload:
04430     return false;
04431 
04432   // Unbridged casts in ARC can be handled in some call positions and
04433   // should be left in place.
04434   case BuiltinType::ARCUnbridgedCast:
04435     return false;
04436 
04437   // Pseudo-objects should be converted as soon as possible.
04438   case BuiltinType::PseudoObject:
04439     return true;
04440 
04441   // The debugger mode could theoretically but currently does not try
04442   // to resolve unknown-typed arguments based on known parameter types.
04443   case BuiltinType::UnknownAny:
04444     return true;
04445 
04446   // These are always invalid as call arguments and should be reported.
04447   case BuiltinType::BoundMember:
04448   case BuiltinType::BuiltinFn:
04449     return true;
04450   }
04451   llvm_unreachable("bad builtin type kind");
04452 }
04453 
04454 /// Check an argument list for placeholders that we won't try to
04455 /// handle later.
04456 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
04457   // Apply this processing to all the arguments at once instead of
04458   // dying at the first failure.
04459   bool hasInvalid = false;
04460   for (size_t i = 0, e = args.size(); i != e; i++) {
04461     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
04462       ExprResult result = S.CheckPlaceholderExpr(args[i]);
04463       if (result.isInvalid()) hasInvalid = true;
04464       else args[i] = result.get();
04465     }
04466   }
04467   return hasInvalid;
04468 }
04469 
04470 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
04471 /// This provides the location of the left/right parens and a list of comma
04472 /// locations.
04473 ExprResult
04474 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
04475                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
04476                     Expr *ExecConfig, bool IsExecConfig) {
04477   // Since this might be a postfix expression, get rid of ParenListExprs.
04478   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
04479   if (Result.isInvalid()) return ExprError();
04480   Fn = Result.get();
04481 
04482   if (checkArgsForPlaceholders(*this, ArgExprs))
04483     return ExprError();
04484 
04485   if (getLangOpts().CPlusPlus) {
04486     // If this is a pseudo-destructor expression, build the call immediately.
04487     if (isa<CXXPseudoDestructorExpr>(Fn)) {
04488       if (!ArgExprs.empty()) {
04489         // Pseudo-destructor calls should not have any arguments.
04490         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
04491           << FixItHint::CreateRemoval(
04492                                     SourceRange(ArgExprs[0]->getLocStart(),
04493                                                 ArgExprs.back()->getLocEnd()));
04494       }
04495 
04496       return new (Context)
04497           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
04498     }
04499     if (Fn->getType() == Context.PseudoObjectTy) {
04500       ExprResult result = CheckPlaceholderExpr(Fn);
04501       if (result.isInvalid()) return ExprError();
04502       Fn = result.get();
04503     }
04504 
04505     // Determine whether this is a dependent call inside a C++ template,
04506     // in which case we won't do any semantic analysis now.
04507     // FIXME: Will need to cache the results of name lookup (including ADL) in
04508     // Fn.
04509     bool Dependent = false;
04510     if (Fn->isTypeDependent())
04511       Dependent = true;
04512     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
04513       Dependent = true;
04514 
04515     if (Dependent) {
04516       if (ExecConfig) {
04517         return new (Context) CUDAKernelCallExpr(
04518             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
04519             Context.DependentTy, VK_RValue, RParenLoc);
04520       } else {
04521         return new (Context) CallExpr(
04522             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
04523       }
04524     }
04525 
04526     // Determine whether this is a call to an object (C++ [over.call.object]).
04527     if (Fn->getType()->isRecordType())
04528       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
04529                                           RParenLoc);
04530 
04531     if (Fn->getType() == Context.UnknownAnyTy) {
04532       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
04533       if (result.isInvalid()) return ExprError();
04534       Fn = result.get();
04535     }
04536 
04537     if (Fn->getType() == Context.BoundMemberTy) {
04538       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
04539     }
04540   }
04541 
04542   // Check for overloaded calls.  This can happen even in C due to extensions.
04543   if (Fn->getType() == Context.OverloadTy) {
04544     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
04545 
04546     // We aren't supposed to apply this logic for if there's an '&' involved.
04547     if (!find.HasFormOfMemberPointer) {
04548       OverloadExpr *ovl = find.Expression;
04549       if (isa<UnresolvedLookupExpr>(ovl)) {
04550         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
04551         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
04552                                        RParenLoc, ExecConfig);
04553       } else {
04554         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
04555                                          RParenLoc);
04556       }
04557     }
04558   }
04559 
04560   // If we're directly calling a function, get the appropriate declaration.
04561   if (Fn->getType() == Context.UnknownAnyTy) {
04562     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
04563     if (result.isInvalid()) return ExprError();
04564     Fn = result.get();
04565   }
04566 
04567   Expr *NakedFn = Fn->IgnoreParens();
04568 
04569   NamedDecl *NDecl = nullptr;
04570   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
04571     if (UnOp->getOpcode() == UO_AddrOf)
04572       NakedFn = UnOp->getSubExpr()->IgnoreParens();
04573   
04574   if (isa<DeclRefExpr>(NakedFn))
04575     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
04576   else if (isa<MemberExpr>(NakedFn))
04577     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
04578 
04579   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
04580     if (FD->hasAttr<EnableIfAttr>()) {
04581       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
04582         Diag(Fn->getLocStart(),
04583              isa<CXXMethodDecl>(FD) ?
04584                  diag::err_ovl_no_viable_member_function_in_call :
04585                  diag::err_ovl_no_viable_function_in_call)
04586           << FD << FD->getSourceRange();
04587         Diag(FD->getLocation(),
04588              diag::note_ovl_candidate_disabled_by_enable_if_attr)
04589             << Attr->getCond()->getSourceRange() << Attr->getMessage();
04590       }
04591     }
04592   }
04593 
04594   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
04595                                ExecConfig, IsExecConfig);
04596 }
04597 
04598 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
04599 ///
04600 /// __builtin_astype( value, dst type )
04601 ///
04602 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
04603                                  SourceLocation BuiltinLoc,
04604                                  SourceLocation RParenLoc) {
04605   ExprValueKind VK = VK_RValue;
04606   ExprObjectKind OK = OK_Ordinary;
04607   QualType DstTy = GetTypeFromParser(ParsedDestTy);
04608   QualType SrcTy = E->getType();
04609   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
04610     return ExprError(Diag(BuiltinLoc,
04611                           diag::err_invalid_astype_of_different_size)
04612                      << DstTy
04613                      << SrcTy
04614                      << E->getSourceRange());
04615   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
04616 }
04617 
04618 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
04619 /// provided arguments.
04620 ///
04621 /// __builtin_convertvector( value, dst type )
04622 ///
04623 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
04624                                         SourceLocation BuiltinLoc,
04625                                         SourceLocation RParenLoc) {
04626   TypeSourceInfo *TInfo;
04627   GetTypeFromParser(ParsedDestTy, &TInfo);
04628   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
04629 }
04630 
04631 /// BuildResolvedCallExpr - Build a call to a resolved expression,
04632 /// i.e. an expression not of \p OverloadTy.  The expression should
04633 /// unary-convert to an expression of function-pointer or
04634 /// block-pointer type.
04635 ///
04636 /// \param NDecl the declaration being called, if available
04637 ExprResult
04638 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
04639                             SourceLocation LParenLoc,
04640                             ArrayRef<Expr *> Args,
04641                             SourceLocation RParenLoc,
04642                             Expr *Config, bool IsExecConfig) {
04643   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
04644   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
04645 
04646   // Promote the function operand.
04647   // We special-case function promotion here because we only allow promoting
04648   // builtin functions to function pointers in the callee of a call.
04649   ExprResult Result;
04650   if (BuiltinID &&
04651       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
04652     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
04653                                CK_BuiltinFnToFnPtr).get();
04654   } else {
04655     Result = CallExprUnaryConversions(Fn);
04656   }
04657   if (Result.isInvalid())
04658     return ExprError();
04659   Fn = Result.get();
04660 
04661   // Make the call expr early, before semantic checks.  This guarantees cleanup
04662   // of arguments and function on error.
04663   CallExpr *TheCall;
04664   if (Config)
04665     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
04666                                                cast<CallExpr>(Config), Args,
04667                                                Context.BoolTy, VK_RValue,
04668                                                RParenLoc);
04669   else
04670     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
04671                                      VK_RValue, RParenLoc);
04672 
04673   // Bail out early if calling a builtin with custom typechecking.
04674   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
04675     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
04676 
04677  retry:
04678   const FunctionType *FuncT;
04679   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
04680     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
04681     // have type pointer to function".
04682     FuncT = PT->getPointeeType()->getAs<FunctionType>();
04683     if (!FuncT)
04684       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
04685                          << Fn->getType() << Fn->getSourceRange());
04686   } else if (const BlockPointerType *BPT =
04687                Fn->getType()->getAs<BlockPointerType>()) {
04688     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
04689   } else {
04690     // Handle calls to expressions of unknown-any type.
04691     if (Fn->getType() == Context.UnknownAnyTy) {
04692       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
04693       if (rewrite.isInvalid()) return ExprError();
04694       Fn = rewrite.get();
04695       TheCall->setCallee(Fn);
04696       goto retry;
04697     }
04698 
04699     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
04700       << Fn->getType() << Fn->getSourceRange());
04701   }
04702 
04703   if (getLangOpts().CUDA) {
04704     if (Config) {
04705       // CUDA: Kernel calls must be to global functions
04706       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
04707         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
04708             << FDecl->getName() << Fn->getSourceRange());
04709 
04710       // CUDA: Kernel function must have 'void' return type
04711       if (!FuncT->getReturnType()->isVoidType())
04712         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
04713             << Fn->getType() << Fn->getSourceRange());
04714     } else {
04715       // CUDA: Calls to global functions must be configured
04716       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
04717         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
04718             << FDecl->getName() << Fn->getSourceRange());
04719     }
04720   }
04721 
04722   // Check for a valid return type
04723   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
04724                           FDecl))
04725     return ExprError();
04726 
04727   // We know the result type of the call, set it.
04728   TheCall->setType(FuncT->getCallResultType(Context));
04729   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
04730 
04731   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
04732   if (Proto) {
04733     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
04734                                 IsExecConfig))
04735       return ExprError();
04736   } else {
04737     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
04738 
04739     if (FDecl) {
04740       // Check if we have too few/too many template arguments, based
04741       // on our knowledge of the function definition.
04742       const FunctionDecl *Def = nullptr;
04743       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
04744         Proto = Def->getType()->getAs<FunctionProtoType>();
04745        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
04746           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
04747           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
04748       }
04749       
04750       // If the function we're calling isn't a function prototype, but we have
04751       // a function prototype from a prior declaratiom, use that prototype.
04752       if (!FDecl->hasPrototype())
04753         Proto = FDecl->getType()->getAs<FunctionProtoType>();
04754     }
04755 
04756     // Promote the arguments (C99 6.5.2.2p6).
04757     for (unsigned i = 0, e = Args.size(); i != e; i++) {
04758       Expr *Arg = Args[i];
04759 
04760       if (Proto && i < Proto->getNumParams()) {
04761         InitializedEntity Entity = InitializedEntity::InitializeParameter(
04762             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
04763         ExprResult ArgE =
04764             PerformCopyInitialization(Entity, SourceLocation(), Arg);
04765         if (ArgE.isInvalid())
04766           return true;
04767         
04768         Arg = ArgE.getAs<Expr>();
04769 
04770       } else {
04771         ExprResult ArgE = DefaultArgumentPromotion(Arg);
04772 
04773         if (ArgE.isInvalid())
04774           return true;
04775 
04776         Arg = ArgE.getAs<Expr>();
04777       }
04778       
04779       if (RequireCompleteType(Arg->getLocStart(),
04780                               Arg->getType(),
04781                               diag::err_call_incomplete_argument, Arg))
04782         return ExprError();
04783 
04784       TheCall->setArg(i, Arg);
04785     }
04786   }
04787 
04788   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
04789     if (!Method->isStatic())
04790       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
04791         << Fn->getSourceRange());
04792 
04793   // Check for sentinels
04794   if (NDecl)
04795     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
04796 
04797   // Do special checking on direct calls to functions.
04798   if (FDecl) {
04799     if (CheckFunctionCall(FDecl, TheCall, Proto))
04800       return ExprError();
04801 
04802     if (BuiltinID)
04803       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
04804   } else if (NDecl) {
04805     if (CheckPointerCall(NDecl, TheCall, Proto))
04806       return ExprError();
04807   } else {
04808     if (CheckOtherCall(TheCall, Proto))
04809       return ExprError();
04810   }
04811 
04812   return MaybeBindToTemporary(TheCall);
04813 }
04814 
04815 ExprResult
04816 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
04817                            SourceLocation RParenLoc, Expr *InitExpr) {
04818   assert(Ty && "ActOnCompoundLiteral(): missing type");
04819   // FIXME: put back this assert when initializers are worked out.
04820   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
04821 
04822   TypeSourceInfo *TInfo;
04823   QualType literalType = GetTypeFromParser(Ty, &TInfo);
04824   if (!TInfo)
04825     TInfo = Context.getTrivialTypeSourceInfo(literalType);
04826 
04827   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
04828 }
04829 
04830 ExprResult
04831 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
04832                                SourceLocation RParenLoc, Expr *LiteralExpr) {
04833   QualType literalType = TInfo->getType();
04834 
04835   if (literalType->isArrayType()) {
04836     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
04837           diag::err_illegal_decl_array_incomplete_type,
04838           SourceRange(LParenLoc,
04839                       LiteralExpr->getSourceRange().getEnd())))
04840       return ExprError();
04841     if (literalType->isVariableArrayType())
04842       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
04843         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
04844   } else if (!literalType->isDependentType() &&
04845              RequireCompleteType(LParenLoc, literalType,
04846                diag::err_typecheck_decl_incomplete_type,
04847                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
04848     return ExprError();
04849 
04850   InitializedEntity Entity
04851     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
04852   InitializationKind Kind
04853     = InitializationKind::CreateCStyleCast(LParenLoc, 
04854                                            SourceRange(LParenLoc, RParenLoc),
04855                                            /*InitList=*/true);
04856   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
04857   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
04858                                       &literalType);
04859   if (Result.isInvalid())
04860     return ExprError();
04861   LiteralExpr = Result.get();
04862 
04863   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
04864   if (isFileScope &&
04865       !LiteralExpr->isTypeDependent() &&
04866       !LiteralExpr->isValueDependent() &&
04867       !literalType->isDependentType()) { // 6.5.2.5p3
04868     if (CheckForConstantInitializer(LiteralExpr, literalType))
04869       return ExprError();
04870   }
04871 
04872   // In C, compound literals are l-values for some reason.
04873   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
04874 
04875   return MaybeBindToTemporary(
04876            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
04877                                              VK, LiteralExpr, isFileScope));
04878 }
04879 
04880 ExprResult
04881 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
04882                     SourceLocation RBraceLoc) {
04883   // Immediately handle non-overload placeholders.  Overloads can be
04884   // resolved contextually, but everything else here can't.
04885   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
04886     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
04887       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
04888 
04889       // Ignore failures; dropping the entire initializer list because
04890       // of one failure would be terrible for indexing/etc.
04891       if (result.isInvalid()) continue;
04892 
04893       InitArgList[I] = result.get();
04894     }
04895   }
04896 
04897   // Semantic analysis for initializers is done by ActOnDeclarator() and
04898   // CheckInitializer() - it requires knowledge of the object being intialized.
04899 
04900   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
04901                                                RBraceLoc);
04902   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
04903   return E;
04904 }
04905 
04906 /// Do an explicit extend of the given block pointer if we're in ARC.
04907 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
04908   assert(E.get()->getType()->isBlockPointerType());
04909   assert(E.get()->isRValue());
04910 
04911   // Only do this in an r-value context.
04912   if (!S.getLangOpts().ObjCAutoRefCount) return;
04913 
04914   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
04915                                CK_ARCExtendBlockObject, E.get(),
04916                                /*base path*/ nullptr, VK_RValue);
04917   S.ExprNeedsCleanups = true;
04918 }
04919 
04920 /// Prepare a conversion of the given expression to an ObjC object
04921 /// pointer type.
04922 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
04923   QualType type = E.get()->getType();
04924   if (type->isObjCObjectPointerType()) {
04925     return CK_BitCast;
04926   } else if (type->isBlockPointerType()) {
04927     maybeExtendBlockObject(*this, E);
04928     return CK_BlockPointerToObjCPointerCast;
04929   } else {
04930     assert(type->isPointerType());
04931     return CK_CPointerToObjCPointerCast;
04932   }
04933 }
04934 
04935 /// Prepares for a scalar cast, performing all the necessary stages
04936 /// except the final cast and returning the kind required.
04937 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
04938   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
04939   // Also, callers should have filtered out the invalid cases with
04940   // pointers.  Everything else should be possible.
04941 
04942   QualType SrcTy = Src.get()->getType();
04943   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
04944     return CK_NoOp;
04945 
04946   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
04947   case Type::STK_MemberPointer:
04948     llvm_unreachable("member pointer type in C");
04949 
04950   case Type::STK_CPointer:
04951   case Type::STK_BlockPointer:
04952   case Type::STK_ObjCObjectPointer:
04953     switch (DestTy->getScalarTypeKind()) {
04954     case Type::STK_CPointer: {
04955       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
04956       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
04957       if (SrcAS != DestAS)
04958         return CK_AddressSpaceConversion;
04959       return CK_BitCast;
04960     }
04961     case Type::STK_BlockPointer:
04962       return (SrcKind == Type::STK_BlockPointer
04963                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
04964     case Type::STK_ObjCObjectPointer:
04965       if (SrcKind == Type::STK_ObjCObjectPointer)
04966         return CK_BitCast;
04967       if (SrcKind == Type::STK_CPointer)
04968         return CK_CPointerToObjCPointerCast;
04969       maybeExtendBlockObject(*this, Src);
04970       return CK_BlockPointerToObjCPointerCast;
04971     case Type::STK_Bool:
04972       return CK_PointerToBoolean;
04973     case Type::STK_Integral:
04974       return CK_PointerToIntegral;
04975     case Type::STK_Floating:
04976     case Type::STK_FloatingComplex:
04977     case Type::STK_IntegralComplex:
04978     case Type::STK_MemberPointer:
04979       llvm_unreachable("illegal cast from pointer");
04980     }
04981     llvm_unreachable("Should have returned before this");
04982 
04983   case Type::STK_Bool: // casting from bool is like casting from an integer
04984   case Type::STK_Integral:
04985     switch (DestTy->getScalarTypeKind()) {
04986     case Type::STK_CPointer:
04987     case Type::STK_ObjCObjectPointer:
04988     case Type::STK_BlockPointer:
04989       if (Src.get()->isNullPointerConstant(Context,
04990                                            Expr::NPC_ValueDependentIsNull))
04991         return CK_NullToPointer;
04992       return CK_IntegralToPointer;
04993     case Type::STK_Bool:
04994       return CK_IntegralToBoolean;
04995     case Type::STK_Integral:
04996       return CK_IntegralCast;
04997     case Type::STK_Floating:
04998       return CK_IntegralToFloating;
04999     case Type::STK_IntegralComplex:
05000       Src = ImpCastExprToType(Src.get(),
05001                               DestTy->castAs<ComplexType>()->getElementType(),
05002                               CK_IntegralCast);
05003       return CK_IntegralRealToComplex;
05004     case Type::STK_FloatingComplex:
05005       Src = ImpCastExprToType(Src.get(),
05006                               DestTy->castAs<ComplexType>()->getElementType(),
05007                               CK_IntegralToFloating);
05008       return CK_FloatingRealToComplex;
05009     case Type::STK_MemberPointer:
05010       llvm_unreachable("member pointer type in C");
05011     }
05012     llvm_unreachable("Should have returned before this");
05013 
05014   case Type::STK_Floating:
05015     switch (DestTy->getScalarTypeKind()) {
05016     case Type::STK_Floating:
05017       return CK_FloatingCast;
05018     case Type::STK_Bool:
05019       return CK_FloatingToBoolean;
05020     case Type::STK_Integral:
05021       return CK_FloatingToIntegral;
05022     case Type::STK_FloatingComplex:
05023       Src = ImpCastExprToType(Src.get(),
05024                               DestTy->castAs<ComplexType>()->getElementType(),
05025                               CK_FloatingCast);
05026       return CK_FloatingRealToComplex;
05027     case Type::STK_IntegralComplex:
05028       Src = ImpCastExprToType(Src.get(),
05029                               DestTy->castAs<ComplexType>()->getElementType(),
05030                               CK_FloatingToIntegral);
05031       return CK_IntegralRealToComplex;
05032     case Type::STK_CPointer:
05033     case Type::STK_ObjCObjectPointer:
05034     case Type::STK_BlockPointer:
05035       llvm_unreachable("valid float->pointer cast?");
05036     case Type::STK_MemberPointer:
05037       llvm_unreachable("member pointer type in C");
05038     }
05039     llvm_unreachable("Should have returned before this");
05040 
05041   case Type::STK_FloatingComplex:
05042     switch (DestTy->getScalarTypeKind()) {
05043     case Type::STK_FloatingComplex:
05044       return CK_FloatingComplexCast;
05045     case Type::STK_IntegralComplex:
05046       return CK_FloatingComplexToIntegralComplex;
05047     case Type::STK_Floating: {
05048       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
05049       if (Context.hasSameType(ET, DestTy))
05050         return CK_FloatingComplexToReal;
05051       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
05052       return CK_FloatingCast;
05053     }
05054     case Type::STK_Bool:
05055       return CK_FloatingComplexToBoolean;
05056     case Type::STK_Integral:
05057       Src = ImpCastExprToType(Src.get(),
05058                               SrcTy->castAs<ComplexType>()->getElementType(),
05059                               CK_FloatingComplexToReal);
05060       return CK_FloatingToIntegral;
05061     case Type::STK_CPointer:
05062     case Type::STK_ObjCObjectPointer:
05063     case Type::STK_BlockPointer:
05064       llvm_unreachable("valid complex float->pointer cast?");
05065     case Type::STK_MemberPointer:
05066       llvm_unreachable("member pointer type in C");
05067     }
05068     llvm_unreachable("Should have returned before this");
05069 
05070   case Type::STK_IntegralComplex:
05071     switch (DestTy->getScalarTypeKind()) {
05072     case Type::STK_FloatingComplex:
05073       return CK_IntegralComplexToFloatingComplex;
05074     case Type::STK_IntegralComplex:
05075       return CK_IntegralComplexCast;
05076     case Type::STK_Integral: {
05077       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
05078       if (Context.hasSameType(ET, DestTy))
05079         return CK_IntegralComplexToReal;
05080       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
05081       return CK_IntegralCast;
05082     }
05083     case Type::STK_Bool:
05084       return CK_IntegralComplexToBoolean;
05085     case Type::STK_Floating:
05086       Src = ImpCastExprToType(Src.get(),
05087                               SrcTy->castAs<ComplexType>()->getElementType(),
05088                               CK_IntegralComplexToReal);
05089       return CK_IntegralToFloating;
05090     case Type::STK_CPointer:
05091     case Type::STK_ObjCObjectPointer:
05092     case Type::STK_BlockPointer:
05093       llvm_unreachable("valid complex int->pointer cast?");
05094     case Type::STK_MemberPointer:
05095       llvm_unreachable("member pointer type in C");
05096     }
05097     llvm_unreachable("Should have returned before this");
05098   }
05099 
05100   llvm_unreachable("Unhandled scalar cast");
05101 }
05102 
05103 static bool breakDownVectorType(QualType type, uint64_t &len,
05104                                 QualType &eltType) {
05105   // Vectors are simple.
05106   if (const VectorType *vecType = type->getAs<VectorType>()) {
05107     len = vecType->getNumElements();
05108     eltType = vecType->getElementType();
05109     assert(eltType->isScalarType());
05110     return true;
05111   }
05112   
05113   // We allow lax conversion to and from non-vector types, but only if
05114   // they're real types (i.e. non-complex, non-pointer scalar types).
05115   if (!type->isRealType()) return false;
05116   
05117   len = 1;
05118   eltType = type;
05119   return true;
05120 }
05121 
05122 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
05123   uint64_t srcLen, destLen;
05124   QualType srcElt, destElt;
05125   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
05126   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
05127   
05128   // ASTContext::getTypeSize will return the size rounded up to a
05129   // power of 2, so instead of using that, we need to use the raw
05130   // element size multiplied by the element count.
05131   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
05132   uint64_t destEltSize = S.Context.getTypeSize(destElt);
05133   
05134   return (srcLen * srcEltSize == destLen * destEltSize);
05135 }
05136 
05137 /// Is this a legal conversion between two known vector types?
05138 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
05139   assert(destTy->isVectorType() || srcTy->isVectorType());
05140   
05141   if (!Context.getLangOpts().LaxVectorConversions)
05142     return false;
05143   return VectorTypesMatch(*this, srcTy, destTy);
05144 }
05145 
05146 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
05147                            CastKind &Kind) {
05148   assert(VectorTy->isVectorType() && "Not a vector type!");
05149 
05150   if (Ty->isVectorType() || Ty->isIntegerType()) {
05151     if (!VectorTypesMatch(*this, Ty, VectorTy))
05152       return Diag(R.getBegin(),
05153                   Ty->isVectorType() ?
05154                   diag::err_invalid_conversion_between_vectors :
05155                   diag::err_invalid_conversion_between_vector_and_integer)
05156         << VectorTy << Ty << R;
05157   } else
05158     return Diag(R.getBegin(),
05159                 diag::err_invalid_conversion_between_vector_and_scalar)
05160       << VectorTy << Ty << R;
05161 
05162   Kind = CK_BitCast;
05163   return false;
05164 }
05165 
05166 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
05167                                     Expr *CastExpr, CastKind &Kind) {
05168   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
05169 
05170   QualType SrcTy = CastExpr->getType();
05171 
05172   // If SrcTy is a VectorType, the total size must match to explicitly cast to
05173   // an ExtVectorType.
05174   // In OpenCL, casts between vectors of different types are not allowed.
05175   // (See OpenCL 6.2).
05176   if (SrcTy->isVectorType()) {
05177     if (!VectorTypesMatch(*this, SrcTy, DestTy)
05178         || (getLangOpts().OpenCL &&
05179             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
05180       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
05181         << DestTy << SrcTy << R;
05182       return ExprError();
05183     }
05184     Kind = CK_BitCast;
05185     return CastExpr;
05186   }
05187 
05188   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
05189   // conversion will take place first from scalar to elt type, and then
05190   // splat from elt type to vector.
05191   if (SrcTy->isPointerType())
05192     return Diag(R.getBegin(),
05193                 diag::err_invalid_conversion_between_vector_and_scalar)
05194       << DestTy << SrcTy << R;
05195 
05196   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
05197   ExprResult CastExprRes = CastExpr;
05198   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
05199   if (CastExprRes.isInvalid())
05200     return ExprError();
05201   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
05202 
05203   Kind = CK_VectorSplat;
05204   return CastExpr;
05205 }
05206 
05207 ExprResult
05208 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
05209                     Declarator &D, ParsedType &Ty,
05210                     SourceLocation RParenLoc, Expr *CastExpr) {
05211   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
05212          "ActOnCastExpr(): missing type or expr");
05213 
05214   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
05215   if (D.isInvalidType())
05216     return ExprError();
05217 
05218   if (getLangOpts().CPlusPlus) {
05219     // Check that there are no default arguments (C++ only).
05220     CheckExtraCXXDefaultArguments(D);
05221   }
05222 
05223   checkUnusedDeclAttributes(D);
05224 
05225   QualType castType = castTInfo->getType();
05226   Ty = CreateParsedType(castType, castTInfo);
05227 
05228   bool isVectorLiteral = false;
05229 
05230   // Check for an altivec or OpenCL literal,
05231   // i.e. all the elements are integer constants.
05232   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
05233   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
05234   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
05235        && castType->isVectorType() && (PE || PLE)) {
05236     if (PLE && PLE->getNumExprs() == 0) {
05237       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
05238       return ExprError();
05239     }
05240     if (PE || PLE->getNumExprs() == 1) {
05241       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
05242       if (!E->getType()->isVectorType())
05243         isVectorLiteral = true;
05244     }
05245     else
05246       isVectorLiteral = true;
05247   }
05248 
05249   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
05250   // then handle it as such.
05251   if (isVectorLiteral)
05252     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
05253 
05254   // If the Expr being casted is a ParenListExpr, handle it specially.
05255   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
05256   // sequence of BinOp comma operators.
05257   if (isa<ParenListExpr>(CastExpr)) {
05258     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
05259     if (Result.isInvalid()) return ExprError();
05260     CastExpr = Result.get();
05261   }
05262 
05263   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
05264       !getSourceManager().isInSystemMacro(LParenLoc))
05265     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
05266   
05267   CheckTollFreeBridgeCast(castType, CastExpr);
05268   
05269   CheckObjCBridgeRelatedCast(castType, CastExpr);
05270   
05271   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
05272 }
05273 
05274 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
05275                                     SourceLocation RParenLoc, Expr *E,
05276                                     TypeSourceInfo *TInfo) {
05277   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
05278          "Expected paren or paren list expression");
05279 
05280   Expr **exprs;
05281   unsigned numExprs;
05282   Expr *subExpr;
05283   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
05284   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
05285     LiteralLParenLoc = PE->getLParenLoc();
05286     LiteralRParenLoc = PE->getRParenLoc();
05287     exprs = PE->getExprs();
05288     numExprs = PE->getNumExprs();
05289   } else { // isa<ParenExpr> by assertion at function entrance
05290     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
05291     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
05292     subExpr = cast<ParenExpr>(E)->getSubExpr();
05293     exprs = &subExpr;
05294     numExprs = 1;
05295   }
05296 
05297   QualType Ty = TInfo->getType();
05298   assert(Ty->isVectorType() && "Expected vector type");
05299 
05300   SmallVector<Expr *, 8> initExprs;
05301   const VectorType *VTy = Ty->getAs<VectorType>();
05302   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
05303   
05304   // '(...)' form of vector initialization in AltiVec: the number of
05305   // initializers must be one or must match the size of the vector.
05306   // If a single value is specified in the initializer then it will be
05307   // replicated to all the components of the vector
05308   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
05309     // The number of initializers must be one or must match the size of the
05310     // vector. If a single value is specified in the initializer then it will
05311     // be replicated to all the components of the vector
05312     if (numExprs == 1) {
05313       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
05314       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
05315       if (Literal.isInvalid())
05316         return ExprError();
05317       Literal = ImpCastExprToType(Literal.get(), ElemTy,
05318                                   PrepareScalarCast(Literal, ElemTy));
05319       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
05320     }
05321     else if (numExprs < numElems) {
05322       Diag(E->getExprLoc(),
05323            diag::err_incorrect_number_of_vector_initializers);
05324       return ExprError();
05325     }
05326     else
05327       initExprs.append(exprs, exprs + numExprs);
05328   }
05329   else {
05330     // For OpenCL, when the number of initializers is a single value,
05331     // it will be replicated to all components of the vector.
05332     if (getLangOpts().OpenCL &&
05333         VTy->getVectorKind() == VectorType::GenericVector &&
05334         numExprs == 1) {
05335         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
05336         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
05337         if (Literal.isInvalid())
05338           return ExprError();
05339         Literal = ImpCastExprToType(Literal.get(), ElemTy,
05340                                     PrepareScalarCast(Literal, ElemTy));
05341         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
05342     }
05343     
05344     initExprs.append(exprs, exprs + numExprs);
05345   }
05346   // FIXME: This means that pretty-printing the final AST will produce curly
05347   // braces instead of the original commas.
05348   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
05349                                                    initExprs, LiteralRParenLoc);
05350   initE->setType(Ty);
05351   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
05352 }
05353 
05354 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
05355 /// the ParenListExpr into a sequence of comma binary operators.
05356 ExprResult
05357 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
05358   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
05359   if (!E)
05360     return OrigExpr;
05361 
05362   ExprResult Result(E->getExpr(0));
05363 
05364   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
05365     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
05366                         E->getExpr(i));
05367 
05368   if (Result.isInvalid()) return ExprError();
05369 
05370   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
05371 }
05372 
05373 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
05374                                     SourceLocation R,
05375                                     MultiExprArg Val) {
05376   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
05377   return expr;
05378 }
05379 
05380 /// \brief Emit a specialized diagnostic when one expression is a null pointer
05381 /// constant and the other is not a pointer.  Returns true if a diagnostic is
05382 /// emitted.
05383 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
05384                                       SourceLocation QuestionLoc) {
05385   Expr *NullExpr = LHSExpr;
05386   Expr *NonPointerExpr = RHSExpr;
05387   Expr::NullPointerConstantKind NullKind =
05388       NullExpr->isNullPointerConstant(Context,
05389                                       Expr::NPC_ValueDependentIsNotNull);
05390 
05391   if (NullKind == Expr::NPCK_NotNull) {
05392     NullExpr = RHSExpr;
05393     NonPointerExpr = LHSExpr;
05394     NullKind =
05395         NullExpr->isNullPointerConstant(Context,
05396                                         Expr::NPC_ValueDependentIsNotNull);
05397   }
05398 
05399   if (NullKind == Expr::NPCK_NotNull)
05400     return false;
05401 
05402   if (NullKind == Expr::NPCK_ZeroExpression)
05403     return false;
05404 
05405   if (NullKind == Expr::NPCK_ZeroLiteral) {
05406     // In this case, check to make sure that we got here from a "NULL"
05407     // string in the source code.
05408     NullExpr = NullExpr->IgnoreParenImpCasts();
05409     SourceLocation loc = NullExpr->getExprLoc();
05410     if (!findMacroSpelling(loc, "NULL"))
05411       return false;
05412   }
05413 
05414   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
05415   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
05416       << NonPointerExpr->getType() << DiagType
05417       << NonPointerExpr->getSourceRange();
05418   return true;
05419 }
05420 
05421 /// \brief Return false if the condition expression is valid, true otherwise.
05422 static bool checkCondition(Sema &S, Expr *Cond) {
05423   QualType CondTy = Cond->getType();
05424 
05425   // C99 6.5.15p2
05426   if (CondTy->isScalarType()) return false;
05427 
05428   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
05429   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
05430     return false;
05431 
05432   // Emit the proper error message.
05433   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
05434                               diag::err_typecheck_cond_expect_scalar :
05435                               diag::err_typecheck_cond_expect_scalar_or_vector)
05436     << CondTy;
05437   return true;
05438 }
05439 
05440 /// \brief Return false if the two expressions can be converted to a vector,
05441 /// true otherwise
05442 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
05443                                                     ExprResult &RHS,
05444                                                     QualType CondTy) {
05445   // Both operands should be of scalar type.
05446   if (!LHS.get()->getType()->isScalarType()) {
05447     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
05448       << CondTy;
05449     return true;
05450   }
05451   if (!RHS.get()->getType()->isScalarType()) {
05452     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
05453       << CondTy;
05454     return true;
05455   }
05456 
05457   // Implicity convert these scalars to the type of the condition.
05458   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
05459   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
05460   return false;
05461 }
05462 
05463 /// \brief Handle when one or both operands are void type.
05464 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
05465                                          ExprResult &RHS) {
05466     Expr *LHSExpr = LHS.get();
05467     Expr *RHSExpr = RHS.get();
05468 
05469     if (!LHSExpr->getType()->isVoidType())
05470       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
05471         << RHSExpr->getSourceRange();
05472     if (!RHSExpr->getType()->isVoidType())
05473       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
05474         << LHSExpr->getSourceRange();
05475     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
05476     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
05477     return S.Context.VoidTy;
05478 }
05479 
05480 /// \brief Return false if the NullExpr can be promoted to PointerTy,
05481 /// true otherwise.
05482 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
05483                                         QualType PointerTy) {
05484   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
05485       !NullExpr.get()->isNullPointerConstant(S.Context,
05486                                             Expr::NPC_ValueDependentIsNull))
05487     return true;
05488 
05489   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
05490   return false;
05491 }
05492 
05493 /// \brief Checks compatibility between two pointers and return the resulting
05494 /// type.
05495 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
05496                                                      ExprResult &RHS,
05497                                                      SourceLocation Loc) {
05498   QualType LHSTy = LHS.get()->getType();
05499   QualType RHSTy = RHS.get()->getType();
05500 
05501   if (S.Context.hasSameType(LHSTy, RHSTy)) {
05502     // Two identical pointers types are always compatible.
05503     return LHSTy;
05504   }
05505 
05506   QualType lhptee, rhptee;
05507 
05508   // Get the pointee types.
05509   bool IsBlockPointer = false;
05510   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
05511     lhptee = LHSBTy->getPointeeType();
05512     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
05513     IsBlockPointer = true;
05514   } else {
05515     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
05516     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
05517   }
05518 
05519   // C99 6.5.15p6: If both operands are pointers to compatible types or to
05520   // differently qualified versions of compatible types, the result type is
05521   // a pointer to an appropriately qualified version of the composite
05522   // type.
05523 
05524   // Only CVR-qualifiers exist in the standard, and the differently-qualified
05525   // clause doesn't make sense for our extensions. E.g. address space 2 should
05526   // be incompatible with address space 3: they may live on different devices or
05527   // anything.
05528   Qualifiers lhQual = lhptee.getQualifiers();
05529   Qualifiers rhQual = rhptee.getQualifiers();
05530 
05531   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
05532   lhQual.removeCVRQualifiers();
05533   rhQual.removeCVRQualifiers();
05534 
05535   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
05536   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
05537 
05538   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
05539 
05540   if (CompositeTy.isNull()) {
05541     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
05542       << LHSTy << RHSTy << LHS.get()->getSourceRange()
05543       << RHS.get()->getSourceRange();
05544     // In this situation, we assume void* type. No especially good
05545     // reason, but this is what gcc does, and we do have to pick
05546     // to get a consistent AST.
05547     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
05548     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
05549     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
05550     return incompatTy;
05551   }
05552 
05553   // The pointer types are compatible.
05554   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
05555   if (IsBlockPointer)
05556     ResultTy = S.Context.getBlockPointerType(ResultTy);
05557   else
05558     ResultTy = S.Context.getPointerType(ResultTy);
05559 
05560   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
05561   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
05562   return ResultTy;
05563 }
05564 
05565 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
05566 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
05567 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
05568 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
05569   if (QT->isObjCIdType())
05570     return true;
05571   
05572   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
05573   if (!OPT)
05574     return false;
05575 
05576   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
05577     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
05578       return false;
05579   
05580   ObjCProtocolDecl* PNSCopying =
05581     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
05582   ObjCProtocolDecl* PNSObject =
05583     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
05584 
05585   for (auto *Proto : OPT->quals()) {
05586     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
05587         (PNSObject && declaresSameEntity(Proto, PNSObject)))
05588       ;
05589     else
05590       return false;
05591   }
05592   return true;
05593 }
05594 
05595 /// \brief Return the resulting type when the operands are both block pointers.
05596 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
05597                                                           ExprResult &LHS,
05598                                                           ExprResult &RHS,
05599                                                           SourceLocation Loc) {
05600   QualType LHSTy = LHS.get()->getType();
05601   QualType RHSTy = RHS.get()->getType();
05602 
05603   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
05604     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
05605       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
05606       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
05607       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
05608       return destType;
05609     }
05610     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
05611       << LHSTy << RHSTy << LHS.get()->getSourceRange()
05612       << RHS.get()->getSourceRange();
05613     return QualType();
05614   }
05615 
05616   // We have 2 block pointer types.
05617   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
05618 }
05619 
05620 /// \brief Return the resulting type when the operands are both pointers.
05621 static QualType
05622 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
05623                                             ExprResult &RHS,
05624                                             SourceLocation Loc) {
05625   // get the pointer types
05626   QualType LHSTy = LHS.get()->getType();
05627   QualType RHSTy = RHS.get()->getType();
05628 
05629   // get the "pointed to" types
05630   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
05631   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
05632 
05633   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
05634   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
05635     // Figure out necessary qualifiers (C99 6.5.15p6)
05636     QualType destPointee
05637       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
05638     QualType destType = S.Context.getPointerType(destPointee);
05639     // Add qualifiers if necessary.
05640     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
05641     // Promote to void*.
05642     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
05643     return destType;
05644   }
05645   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
05646     QualType destPointee
05647       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
05648     QualType destType = S.Context.getPointerType(destPointee);
05649     // Add qualifiers if necessary.
05650     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
05651     // Promote to void*.
05652     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
05653     return destType;
05654   }
05655 
05656   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
05657 }
05658 
05659 /// \brief Return false if the first expression is not an integer and the second
05660 /// expression is not a pointer, true otherwise.
05661 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
05662                                         Expr* PointerExpr, SourceLocation Loc,
05663                                         bool IsIntFirstExpr) {
05664   if (!PointerExpr->getType()->isPointerType() ||
05665       !Int.get()->getType()->isIntegerType())
05666     return false;
05667 
05668   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
05669   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
05670 
05671   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
05672     << Expr1->getType() << Expr2->getType()
05673     << Expr1->getSourceRange() << Expr2->getSourceRange();
05674   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
05675                             CK_IntegralToPointer);
05676   return true;
05677 }
05678 
05679 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
05680 /// In that case, LHS = cond.
05681 /// C99 6.5.15
05682 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
05683                                         ExprResult &RHS, ExprValueKind &VK,
05684                                         ExprObjectKind &OK,
05685                                         SourceLocation QuestionLoc) {
05686 
05687   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
05688   if (!LHSResult.isUsable()) return QualType();
05689   LHS = LHSResult;
05690 
05691   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
05692   if (!RHSResult.isUsable()) return QualType();
05693   RHS = RHSResult;
05694 
05695   // C++ is sufficiently different to merit its own checker.
05696   if (getLangOpts().CPlusPlus)
05697     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
05698 
05699   VK = VK_RValue;
05700   OK = OK_Ordinary;
05701 
05702   // First, check the condition.
05703   Cond = UsualUnaryConversions(Cond.get());
05704   if (Cond.isInvalid())
05705     return QualType();
05706   if (checkCondition(*this, Cond.get()))
05707     return QualType();
05708 
05709   // Now check the two expressions.
05710   if (LHS.get()->getType()->isVectorType() ||
05711       RHS.get()->getType()->isVectorType())
05712     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
05713 
05714   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
05715   if (LHS.isInvalid() || RHS.isInvalid())
05716     return QualType();
05717 
05718   QualType CondTy = Cond.get()->getType();
05719   QualType LHSTy = LHS.get()->getType();
05720   QualType RHSTy = RHS.get()->getType();
05721 
05722   // If the condition is a vector, and both operands are scalar,
05723   // attempt to implicity convert them to the vector type to act like the
05724   // built in select. (OpenCL v1.1 s6.3.i)
05725   if (getLangOpts().OpenCL && CondTy->isVectorType())
05726     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
05727       return QualType();
05728   
05729   // If both operands have arithmetic type, do the usual arithmetic conversions
05730   // to find a common type: C99 6.5.15p3,5.
05731   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
05732     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
05733     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
05734 
05735     return ResTy;
05736   }
05737 
05738   // If both operands are the same structure or union type, the result is that
05739   // type.
05740   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
05741     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
05742       if (LHSRT->getDecl() == RHSRT->getDecl())
05743         // "If both the operands have structure or union type, the result has
05744         // that type."  This implies that CV qualifiers are dropped.
05745         return LHSTy.getUnqualifiedType();
05746     // FIXME: Type of conditional expression must be complete in C mode.
05747   }
05748 
05749   // C99 6.5.15p5: "If both operands have void type, the result has void type."
05750   // The following || allows only one side to be void (a GCC-ism).
05751   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
05752     return checkConditionalVoidType(*this, LHS, RHS);
05753   }
05754 
05755   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
05756   // the type of the other operand."
05757   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
05758   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
05759 
05760   // All objective-c pointer type analysis is done here.
05761   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
05762                                                         QuestionLoc);
05763   if (LHS.isInvalid() || RHS.isInvalid())
05764     return QualType();
05765   if (!compositeType.isNull())
05766     return compositeType;
05767 
05768 
05769   // Handle block pointer types.
05770   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
05771     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
05772                                                      QuestionLoc);
05773 
05774   // Check constraints for C object pointers types (C99 6.5.15p3,6).
05775   if (LHSTy->isPointerType() && RHSTy->isPointerType())
05776     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
05777                                                        QuestionLoc);
05778 
05779   // GCC compatibility: soften pointer/integer mismatch.  Note that
05780   // null pointers have been filtered out by this point.
05781   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
05782       /*isIntFirstExpr=*/true))
05783     return RHSTy;
05784   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
05785       /*isIntFirstExpr=*/false))
05786     return LHSTy;
05787 
05788   // Emit a better diagnostic if one of the expressions is a null pointer
05789   // constant and the other is not a pointer type. In this case, the user most
05790   // likely forgot to take the address of the other expression.
05791   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
05792     return QualType();
05793 
05794   // Otherwise, the operands are not compatible.
05795   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
05796     << LHSTy << RHSTy << LHS.get()->getSourceRange()
05797     << RHS.get()->getSourceRange();
05798   return QualType();
05799 }
05800 
05801 /// FindCompositeObjCPointerType - Helper method to find composite type of
05802 /// two objective-c pointer types of the two input expressions.
05803 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
05804                                             SourceLocation QuestionLoc) {
05805   QualType LHSTy = LHS.get()->getType();
05806   QualType RHSTy = RHS.get()->getType();
05807 
05808   // Handle things like Class and struct objc_class*.  Here we case the result
05809   // to the pseudo-builtin, because that will be implicitly cast back to the
05810   // redefinition type if an attempt is made to access its fields.
05811   if (LHSTy->isObjCClassType() &&
05812       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
05813     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
05814     return LHSTy;
05815   }
05816   if (RHSTy->isObjCClassType() &&
05817       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
05818     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
05819     return RHSTy;
05820   }
05821   // And the same for struct objc_object* / id
05822   if (LHSTy->isObjCIdType() &&
05823       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
05824     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
05825     return LHSTy;
05826   }
05827   if (RHSTy->isObjCIdType() &&
05828       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
05829     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
05830     return RHSTy;
05831   }
05832   // And the same for struct objc_selector* / SEL
05833   if (Context.isObjCSelType(LHSTy) &&
05834       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
05835     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
05836     return LHSTy;
05837   }
05838   if (Context.isObjCSelType(RHSTy) &&
05839       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
05840     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
05841     return RHSTy;
05842   }
05843   // Check constraints for Objective-C object pointers types.
05844   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
05845 
05846     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
05847       // Two identical object pointer types are always compatible.
05848       return LHSTy;
05849     }
05850     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
05851     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
05852     QualType compositeType = LHSTy;
05853 
05854     // If both operands are interfaces and either operand can be
05855     // assigned to the other, use that type as the composite
05856     // type. This allows
05857     //   xxx ? (A*) a : (B*) b
05858     // where B is a subclass of A.
05859     //
05860     // Additionally, as for assignment, if either type is 'id'
05861     // allow silent coercion. Finally, if the types are
05862     // incompatible then make sure to use 'id' as the composite
05863     // type so the result is acceptable for sending messages to.
05864 
05865     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
05866     // It could return the composite type.
05867     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
05868       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
05869     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
05870       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
05871     } else if ((LHSTy->isObjCQualifiedIdType() ||
05872                 RHSTy->isObjCQualifiedIdType()) &&
05873                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
05874       // Need to handle "id<xx>" explicitly.
05875       // GCC allows qualified id and any Objective-C type to devolve to
05876       // id. Currently localizing to here until clear this should be
05877       // part of ObjCQualifiedIdTypesAreCompatible.
05878       compositeType = Context.getObjCIdType();
05879     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
05880       compositeType = Context.getObjCIdType();
05881     } else if (!(compositeType =
05882                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
05883       ;
05884     else {
05885       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
05886       << LHSTy << RHSTy
05887       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05888       QualType incompatTy = Context.getObjCIdType();
05889       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
05890       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
05891       return incompatTy;
05892     }
05893     // The object pointer types are compatible.
05894     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
05895     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
05896     return compositeType;
05897   }
05898   // Check Objective-C object pointer types and 'void *'
05899   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
05900     if (getLangOpts().ObjCAutoRefCount) {
05901       // ARC forbids the implicit conversion of object pointers to 'void *',
05902       // so these types are not compatible.
05903       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
05904           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05905       LHS = RHS = true;
05906       return QualType();
05907     }
05908     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
05909     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
05910     QualType destPointee
05911     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
05912     QualType destType = Context.getPointerType(destPointee);
05913     // Add qualifiers if necessary.
05914     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
05915     // Promote to void*.
05916     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
05917     return destType;
05918   }
05919   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
05920     if (getLangOpts().ObjCAutoRefCount) {
05921       // ARC forbids the implicit conversion of object pointers to 'void *',
05922       // so these types are not compatible.
05923       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
05924           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05925       LHS = RHS = true;
05926       return QualType();
05927     }
05928     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
05929     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
05930     QualType destPointee
05931     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
05932     QualType destType = Context.getPointerType(destPointee);
05933     // Add qualifiers if necessary.
05934     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
05935     // Promote to void*.
05936     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
05937     return destType;
05938   }
05939   return QualType();
05940 }
05941 
05942 /// SuggestParentheses - Emit a note with a fixit hint that wraps
05943 /// ParenRange in parentheses.
05944 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
05945                                const PartialDiagnostic &Note,
05946                                SourceRange ParenRange) {
05947   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
05948   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
05949       EndLoc.isValid()) {
05950     Self.Diag(Loc, Note)
05951       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
05952       << FixItHint::CreateInsertion(EndLoc, ")");
05953   } else {
05954     // We can't display the parentheses, so just show the bare note.
05955     Self.Diag(Loc, Note) << ParenRange;
05956   }
05957 }
05958 
05959 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
05960   return Opc >= BO_Mul && Opc <= BO_Shr;
05961 }
05962 
05963 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
05964 /// expression, either using a built-in or overloaded operator,
05965 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
05966 /// expression.
05967 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
05968                                    Expr **RHSExprs) {
05969   // Don't strip parenthesis: we should not warn if E is in parenthesis.
05970   E = E->IgnoreImpCasts();
05971   E = E->IgnoreConversionOperator();
05972   E = E->IgnoreImpCasts();
05973 
05974   // Built-in binary operator.
05975   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
05976     if (IsArithmeticOp(OP->getOpcode())) {
05977       *Opcode = OP->getOpcode();
05978       *RHSExprs = OP->getRHS();
05979       return true;
05980     }
05981   }
05982 
05983   // Overloaded operator.
05984   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
05985     if (Call->getNumArgs() != 2)
05986       return false;
05987 
05988     // Make sure this is really a binary operator that is safe to pass into
05989     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
05990     OverloadedOperatorKind OO = Call->getOperator();
05991     if (OO < OO_Plus || OO > OO_Arrow ||
05992         OO == OO_PlusPlus || OO == OO_MinusMinus)
05993       return false;
05994 
05995     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
05996     if (IsArithmeticOp(OpKind)) {
05997       *Opcode = OpKind;
05998       *RHSExprs = Call->getArg(1);
05999       return true;
06000     }
06001   }
06002 
06003   return false;
06004 }
06005 
06006 static bool IsLogicOp(BinaryOperatorKind Opc) {
06007   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
06008 }
06009 
06010 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
06011 /// or is a logical expression such as (x==y) which has int type, but is
06012 /// commonly interpreted as boolean.
06013 static bool ExprLooksBoolean(Expr *E) {
06014   E = E->IgnoreParenImpCasts();
06015 
06016   if (E->getType()->isBooleanType())
06017     return true;
06018   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
06019     return IsLogicOp(OP->getOpcode());
06020   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
06021     return OP->getOpcode() == UO_LNot;
06022 
06023   return false;
06024 }
06025 
06026 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
06027 /// and binary operator are mixed in a way that suggests the programmer assumed
06028 /// the conditional operator has higher precedence, for example:
06029 /// "int x = a + someBinaryCondition ? 1 : 2".
06030 static void DiagnoseConditionalPrecedence(Sema &Self,
06031                                           SourceLocation OpLoc,
06032                                           Expr *Condition,
06033                                           Expr *LHSExpr,
06034                                           Expr *RHSExpr) {
06035   BinaryOperatorKind CondOpcode;
06036   Expr *CondRHS;
06037 
06038   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
06039     return;
06040   if (!ExprLooksBoolean(CondRHS))
06041     return;
06042 
06043   // The condition is an arithmetic binary expression, with a right-
06044   // hand side that looks boolean, so warn.
06045 
06046   Self.Diag(OpLoc, diag::warn_precedence_conditional)
06047       << Condition->getSourceRange()
06048       << BinaryOperator::getOpcodeStr(CondOpcode);
06049 
06050   SuggestParentheses(Self, OpLoc,
06051     Self.PDiag(diag::note_precedence_silence)
06052       << BinaryOperator::getOpcodeStr(CondOpcode),
06053     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
06054 
06055   SuggestParentheses(Self, OpLoc,
06056     Self.PDiag(diag::note_precedence_conditional_first),
06057     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
06058 }
06059 
06060 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
06061 /// in the case of a the GNU conditional expr extension.
06062 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
06063                                     SourceLocation ColonLoc,
06064                                     Expr *CondExpr, Expr *LHSExpr,
06065                                     Expr *RHSExpr) {
06066   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
06067   // was the condition.
06068   OpaqueValueExpr *opaqueValue = nullptr;
06069   Expr *commonExpr = nullptr;
06070   if (!LHSExpr) {
06071     commonExpr = CondExpr;
06072     // Lower out placeholder types first.  This is important so that we don't
06073     // try to capture a placeholder. This happens in few cases in C++; such
06074     // as Objective-C++'s dictionary subscripting syntax.
06075     if (commonExpr->hasPlaceholderType()) {
06076       ExprResult result = CheckPlaceholderExpr(commonExpr);
06077       if (!result.isUsable()) return ExprError();
06078       commonExpr = result.get();
06079     }
06080     // We usually want to apply unary conversions *before* saving, except
06081     // in the special case of a C++ l-value conditional.
06082     if (!(getLangOpts().CPlusPlus
06083           && !commonExpr->isTypeDependent()
06084           && commonExpr->getValueKind() == RHSExpr->getValueKind()
06085           && commonExpr->isGLValue()
06086           && commonExpr->isOrdinaryOrBitFieldObject()
06087           && RHSExpr->isOrdinaryOrBitFieldObject()
06088           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
06089       ExprResult commonRes = UsualUnaryConversions(commonExpr);
06090       if (commonRes.isInvalid())
06091         return ExprError();
06092       commonExpr = commonRes.get();
06093     }
06094 
06095     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
06096                                                 commonExpr->getType(),
06097                                                 commonExpr->getValueKind(),
06098                                                 commonExpr->getObjectKind(),
06099                                                 commonExpr);
06100     LHSExpr = CondExpr = opaqueValue;
06101   }
06102 
06103   ExprValueKind VK = VK_RValue;
06104   ExprObjectKind OK = OK_Ordinary;
06105   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
06106   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
06107                                              VK, OK, QuestionLoc);
06108   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
06109       RHS.isInvalid())
06110     return ExprError();
06111 
06112   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
06113                                 RHS.get());
06114 
06115   if (!commonExpr)
06116     return new (Context)
06117         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
06118                             RHS.get(), result, VK, OK);
06119 
06120   return new (Context) BinaryConditionalOperator(
06121       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
06122       ColonLoc, result, VK, OK);
06123 }
06124 
06125 // checkPointerTypesForAssignment - This is a very tricky routine (despite
06126 // being closely modeled after the C99 spec:-). The odd characteristic of this
06127 // routine is it effectively iqnores the qualifiers on the top level pointee.
06128 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
06129 // FIXME: add a couple examples in this comment.
06130 static Sema::AssignConvertType
06131 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
06132   assert(LHSType.isCanonical() && "LHS not canonicalized!");
06133   assert(RHSType.isCanonical() && "RHS not canonicalized!");
06134 
06135   // get the "pointed to" type (ignoring qualifiers at the top level)
06136   const Type *lhptee, *rhptee;
06137   Qualifiers lhq, rhq;
06138   std::tie(lhptee, lhq) =
06139       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
06140   std::tie(rhptee, rhq) =
06141       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
06142 
06143   Sema::AssignConvertType ConvTy = Sema::Compatible;
06144 
06145   // C99 6.5.16.1p1: This following citation is common to constraints
06146   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
06147   // qualifiers of the type *pointed to* by the right;
06148 
06149   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
06150   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
06151       lhq.compatiblyIncludesObjCLifetime(rhq)) {
06152     // Ignore lifetime for further calculation.
06153     lhq.removeObjCLifetime();
06154     rhq.removeObjCLifetime();
06155   }
06156 
06157   if (!lhq.compatiblyIncludes(rhq)) {
06158     // Treat address-space mismatches as fatal.  TODO: address subspaces
06159     if (lhq.getAddressSpace() != rhq.getAddressSpace())
06160       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
06161 
06162     // It's okay to add or remove GC or lifetime qualifiers when converting to
06163     // and from void*.
06164     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
06165                         .compatiblyIncludes(
06166                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
06167              && (lhptee->isVoidType() || rhptee->isVoidType()))
06168       ; // keep old
06169 
06170     // Treat lifetime mismatches as fatal.
06171     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
06172       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
06173     
06174     // For GCC compatibility, other qualifier mismatches are treated
06175     // as still compatible in C.
06176     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
06177   }
06178 
06179   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
06180   // incomplete type and the other is a pointer to a qualified or unqualified
06181   // version of void...
06182   if (lhptee->isVoidType()) {
06183     if (rhptee->isIncompleteOrObjectType())
06184       return ConvTy;
06185 
06186     // As an extension, we allow cast to/from void* to function pointer.
06187     assert(rhptee->isFunctionType());
06188     return Sema::FunctionVoidPointer;
06189   }
06190 
06191   if (rhptee->isVoidType()) {
06192     if (lhptee->isIncompleteOrObjectType())
06193       return ConvTy;
06194 
06195     // As an extension, we allow cast to/from void* to function pointer.
06196     assert(lhptee->isFunctionType());
06197     return Sema::FunctionVoidPointer;
06198   }
06199 
06200   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
06201   // unqualified versions of compatible types, ...
06202   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
06203   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
06204     // Check if the pointee types are compatible ignoring the sign.
06205     // We explicitly check for char so that we catch "char" vs
06206     // "unsigned char" on systems where "char" is unsigned.
06207     if (lhptee->isCharType())
06208       ltrans = S.Context.UnsignedCharTy;
06209     else if (lhptee->hasSignedIntegerRepresentation())
06210       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
06211 
06212     if (rhptee->isCharType())
06213       rtrans = S.Context.UnsignedCharTy;
06214     else if (rhptee->hasSignedIntegerRepresentation())
06215       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
06216 
06217     if (ltrans == rtrans) {
06218       // Types are compatible ignoring the sign. Qualifier incompatibility
06219       // takes priority over sign incompatibility because the sign
06220       // warning can be disabled.
06221       if (ConvTy != Sema::Compatible)
06222         return ConvTy;
06223 
06224       return Sema::IncompatiblePointerSign;
06225     }
06226 
06227     // If we are a multi-level pointer, it's possible that our issue is simply
06228     // one of qualification - e.g. char ** -> const char ** is not allowed. If
06229     // the eventual target type is the same and the pointers have the same
06230     // level of indirection, this must be the issue.
06231     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
06232       do {
06233         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
06234         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
06235       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
06236 
06237       if (lhptee == rhptee)
06238         return Sema::IncompatibleNestedPointerQualifiers;
06239     }
06240 
06241     // General pointer incompatibility takes priority over qualifiers.
06242     return Sema::IncompatiblePointer;
06243   }
06244   if (!S.getLangOpts().CPlusPlus &&
06245       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
06246     return Sema::IncompatiblePointer;
06247   return ConvTy;
06248 }
06249 
06250 /// checkBlockPointerTypesForAssignment - This routine determines whether two
06251 /// block pointer types are compatible or whether a block and normal pointer
06252 /// are compatible. It is more restrict than comparing two function pointer
06253 // types.
06254 static Sema::AssignConvertType
06255 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
06256                                     QualType RHSType) {
06257   assert(LHSType.isCanonical() && "LHS not canonicalized!");
06258   assert(RHSType.isCanonical() && "RHS not canonicalized!");
06259 
06260   QualType lhptee, rhptee;
06261 
06262   // get the "pointed to" type (ignoring qualifiers at the top level)
06263   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
06264   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
06265 
06266   // In C++, the types have to match exactly.
06267   if (S.getLangOpts().CPlusPlus)
06268     return Sema::IncompatibleBlockPointer;
06269 
06270   Sema::AssignConvertType ConvTy = Sema::Compatible;
06271 
06272   // For blocks we enforce that qualifiers are identical.
06273   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
06274     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
06275 
06276   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
06277     return Sema::IncompatibleBlockPointer;
06278 
06279   return ConvTy;
06280 }
06281 
06282 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
06283 /// for assignment compatibility.
06284 static Sema::AssignConvertType
06285 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
06286                                    QualType RHSType) {
06287   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
06288   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
06289 
06290   if (LHSType->isObjCBuiltinType()) {
06291     // Class is not compatible with ObjC object pointers.
06292     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
06293         !RHSType->isObjCQualifiedClassType())
06294       return Sema::IncompatiblePointer;
06295     return Sema::Compatible;
06296   }
06297   if (RHSType->isObjCBuiltinType()) {
06298     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
06299         !LHSType->isObjCQualifiedClassType())
06300       return Sema::IncompatiblePointer;
06301     return Sema::Compatible;
06302   }
06303   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
06304   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
06305 
06306   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
06307       // make an exception for id<P>
06308       !LHSType->isObjCQualifiedIdType())
06309     return Sema::CompatiblePointerDiscardsQualifiers;
06310 
06311   if (S.Context.typesAreCompatible(LHSType, RHSType))
06312     return Sema::Compatible;
06313   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
06314     return Sema::IncompatibleObjCQualifiedId;
06315   return Sema::IncompatiblePointer;
06316 }
06317 
06318 Sema::AssignConvertType
06319 Sema::CheckAssignmentConstraints(SourceLocation Loc,
06320                                  QualType LHSType, QualType RHSType) {
06321   // Fake up an opaque expression.  We don't actually care about what
06322   // cast operations are required, so if CheckAssignmentConstraints
06323   // adds casts to this they'll be wasted, but fortunately that doesn't
06324   // usually happen on valid code.
06325   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
06326   ExprResult RHSPtr = &RHSExpr;
06327   CastKind K = CK_Invalid;
06328 
06329   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
06330 }
06331 
06332 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
06333 /// has code to accommodate several GCC extensions when type checking
06334 /// pointers. Here are some objectionable examples that GCC considers warnings:
06335 ///
06336 ///  int a, *pint;
06337 ///  short *pshort;
06338 ///  struct foo *pfoo;
06339 ///
06340 ///  pint = pshort; // warning: assignment from incompatible pointer type
06341 ///  a = pint; // warning: assignment makes integer from pointer without a cast
06342 ///  pint = a; // warning: assignment makes pointer from integer without a cast
06343 ///  pint = pfoo; // warning: assignment from incompatible pointer type
06344 ///
06345 /// As a result, the code for dealing with pointers is more complex than the
06346 /// C99 spec dictates.
06347 ///
06348 /// Sets 'Kind' for any result kind except Incompatible.
06349 Sema::AssignConvertType
06350 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
06351                                  CastKind &Kind) {
06352   QualType RHSType = RHS.get()->getType();
06353   QualType OrigLHSType = LHSType;
06354 
06355   // Get canonical types.  We're not formatting these types, just comparing
06356   // them.
06357   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
06358   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
06359 
06360   // Common case: no conversion required.
06361   if (LHSType == RHSType) {
06362     Kind = CK_NoOp;
06363     return Compatible;
06364   }
06365 
06366   // If we have an atomic type, try a non-atomic assignment, then just add an
06367   // atomic qualification step.
06368   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
06369     Sema::AssignConvertType result =
06370       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
06371     if (result != Compatible)
06372       return result;
06373     if (Kind != CK_NoOp)
06374       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
06375     Kind = CK_NonAtomicToAtomic;
06376     return Compatible;
06377   }
06378 
06379   // If the left-hand side is a reference type, then we are in a
06380   // (rare!) case where we've allowed the use of references in C,
06381   // e.g., as a parameter type in a built-in function. In this case,
06382   // just make sure that the type referenced is compatible with the
06383   // right-hand side type. The caller is responsible for adjusting
06384   // LHSType so that the resulting expression does not have reference
06385   // type.
06386   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
06387     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
06388       Kind = CK_LValueBitCast;
06389       return Compatible;
06390     }
06391     return Incompatible;
06392   }
06393 
06394   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
06395   // to the same ExtVector type.
06396   if (LHSType->isExtVectorType()) {
06397     if (RHSType->isExtVectorType())
06398       return Incompatible;
06399     if (RHSType->isArithmeticType()) {
06400       // CK_VectorSplat does T -> vector T, so first cast to the
06401       // element type.
06402       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
06403       if (elType != RHSType) {
06404         Kind = PrepareScalarCast(RHS, elType);
06405         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
06406       }
06407       Kind = CK_VectorSplat;
06408       return Compatible;
06409     }
06410   }
06411 
06412   // Conversions to or from vector type.
06413   if (LHSType->isVectorType() || RHSType->isVectorType()) {
06414     if (LHSType->isVectorType() && RHSType->isVectorType()) {
06415       // Allow assignments of an AltiVec vector type to an equivalent GCC
06416       // vector type and vice versa
06417       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
06418         Kind = CK_BitCast;
06419         return Compatible;
06420       }
06421 
06422       // If we are allowing lax vector conversions, and LHS and RHS are both
06423       // vectors, the total size only needs to be the same. This is a bitcast;
06424       // no bits are changed but the result type is different.
06425       if (isLaxVectorConversion(RHSType, LHSType)) {
06426         Kind = CK_BitCast;
06427         return IncompatibleVectors;
06428       }
06429     }
06430     return Incompatible;
06431   }
06432 
06433   // Arithmetic conversions.
06434   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
06435       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
06436     Kind = PrepareScalarCast(RHS, LHSType);
06437     return Compatible;
06438   }
06439 
06440   // Conversions to normal pointers.
06441   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
06442     // U* -> T*
06443     if (isa<PointerType>(RHSType)) {
06444       Kind = CK_BitCast;
06445       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
06446     }
06447 
06448     // int -> T*
06449     if (RHSType->isIntegerType()) {
06450       Kind = CK_IntegralToPointer; // FIXME: null?
06451       return IntToPointer;
06452     }
06453 
06454     // C pointers are not compatible with ObjC object pointers,
06455     // with two exceptions:
06456     if (isa<ObjCObjectPointerType>(RHSType)) {
06457       //  - conversions to void*
06458       if (LHSPointer->getPointeeType()->isVoidType()) {
06459         Kind = CK_BitCast;
06460         return Compatible;
06461       }
06462 
06463       //  - conversions from 'Class' to the redefinition type
06464       if (RHSType->isObjCClassType() &&
06465           Context.hasSameType(LHSType, 
06466                               Context.getObjCClassRedefinitionType())) {
06467         Kind = CK_BitCast;
06468         return Compatible;
06469       }
06470 
06471       Kind = CK_BitCast;
06472       return IncompatiblePointer;
06473     }
06474 
06475     // U^ -> void*
06476     if (RHSType->getAs<BlockPointerType>()) {
06477       if (LHSPointer->getPointeeType()->isVoidType()) {
06478         Kind = CK_BitCast;
06479         return Compatible;
06480       }
06481     }
06482 
06483     return Incompatible;
06484   }
06485 
06486   // Conversions to block pointers.
06487   if (isa<BlockPointerType>(LHSType)) {
06488     // U^ -> T^
06489     if (RHSType->isBlockPointerType()) {
06490       Kind = CK_BitCast;
06491       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
06492     }
06493 
06494     // int or null -> T^
06495     if (RHSType->isIntegerType()) {
06496       Kind = CK_IntegralToPointer; // FIXME: null
06497       return IntToBlockPointer;
06498     }
06499 
06500     // id -> T^
06501     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
06502       Kind = CK_AnyPointerToBlockPointerCast;
06503       return Compatible;
06504     }
06505 
06506     // void* -> T^
06507     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
06508       if (RHSPT->getPointeeType()->isVoidType()) {
06509         Kind = CK_AnyPointerToBlockPointerCast;
06510         return Compatible;
06511       }
06512 
06513     return Incompatible;
06514   }
06515 
06516   // Conversions to Objective-C pointers.
06517   if (isa<ObjCObjectPointerType>(LHSType)) {
06518     // A* -> B*
06519     if (RHSType->isObjCObjectPointerType()) {
06520       Kind = CK_BitCast;
06521       Sema::AssignConvertType result = 
06522         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
06523       if (getLangOpts().ObjCAutoRefCount &&
06524           result == Compatible && 
06525           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
06526         result = IncompatibleObjCWeakRef;
06527       return result;
06528     }
06529 
06530     // int or null -> A*
06531     if (RHSType->isIntegerType()) {
06532       Kind = CK_IntegralToPointer; // FIXME: null
06533       return IntToPointer;
06534     }
06535 
06536     // In general, C pointers are not compatible with ObjC object pointers,
06537     // with two exceptions:
06538     if (isa<PointerType>(RHSType)) {
06539       Kind = CK_CPointerToObjCPointerCast;
06540 
06541       //  - conversions from 'void*'
06542       if (RHSType->isVoidPointerType()) {
06543         return Compatible;
06544       }
06545 
06546       //  - conversions to 'Class' from its redefinition type
06547       if (LHSType->isObjCClassType() &&
06548           Context.hasSameType(RHSType, 
06549                               Context.getObjCClassRedefinitionType())) {
06550         return Compatible;
06551       }
06552 
06553       return IncompatiblePointer;
06554     }
06555 
06556     // Only under strict condition T^ is compatible with an Objective-C pointer.
06557     if (RHSType->isBlockPointerType() &&
06558         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
06559       maybeExtendBlockObject(*this, RHS);
06560       Kind = CK_BlockPointerToObjCPointerCast;
06561       return Compatible;
06562     }
06563 
06564     return Incompatible;
06565   }
06566 
06567   // Conversions from pointers that are not covered by the above.
06568   if (isa<PointerType>(RHSType)) {
06569     // T* -> _Bool
06570     if (LHSType == Context.BoolTy) {
06571       Kind = CK_PointerToBoolean;
06572       return Compatible;
06573     }
06574 
06575     // T* -> int
06576     if (LHSType->isIntegerType()) {
06577       Kind = CK_PointerToIntegral;
06578       return PointerToInt;
06579     }
06580 
06581     return Incompatible;
06582   }
06583 
06584   // Conversions from Objective-C pointers that are not covered by the above.
06585   if (isa<ObjCObjectPointerType>(RHSType)) {
06586     // T* -> _Bool
06587     if (LHSType == Context.BoolTy) {
06588       Kind = CK_PointerToBoolean;
06589       return Compatible;
06590     }
06591 
06592     // T* -> int
06593     if (LHSType->isIntegerType()) {
06594       Kind = CK_PointerToIntegral;
06595       return PointerToInt;
06596     }
06597 
06598     return Incompatible;
06599   }
06600 
06601   // struct A -> struct B
06602   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
06603     if (Context.typesAreCompatible(LHSType, RHSType)) {
06604       Kind = CK_NoOp;
06605       return Compatible;
06606     }
06607   }
06608 
06609   return Incompatible;
06610 }
06611 
06612 /// \brief Constructs a transparent union from an expression that is
06613 /// used to initialize the transparent union.
06614 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
06615                                       ExprResult &EResult, QualType UnionType,
06616                                       FieldDecl *Field) {
06617   // Build an initializer list that designates the appropriate member
06618   // of the transparent union.
06619   Expr *E = EResult.get();
06620   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
06621                                                    E, SourceLocation());
06622   Initializer->setType(UnionType);
06623   Initializer->setInitializedFieldInUnion(Field);
06624 
06625   // Build a compound literal constructing a value of the transparent
06626   // union type from this initializer list.
06627   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
06628   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
06629                                         VK_RValue, Initializer, false);
06630 }
06631 
06632 Sema::AssignConvertType
06633 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
06634                                                ExprResult &RHS) {
06635   QualType RHSType = RHS.get()->getType();
06636 
06637   // If the ArgType is a Union type, we want to handle a potential
06638   // transparent_union GCC extension.
06639   const RecordType *UT = ArgType->getAsUnionType();
06640   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
06641     return Incompatible;
06642 
06643   // The field to initialize within the transparent union.
06644   RecordDecl *UD = UT->getDecl();
06645   FieldDecl *InitField = nullptr;
06646   // It's compatible if the expression matches any of the fields.
06647   for (auto *it : UD->fields()) {
06648     if (it->getType()->isPointerType()) {
06649       // If the transparent union contains a pointer type, we allow:
06650       // 1) void pointer
06651       // 2) null pointer constant
06652       if (RHSType->isPointerType())
06653         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
06654           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
06655           InitField = it;
06656           break;
06657         }
06658 
06659       if (RHS.get()->isNullPointerConstant(Context,
06660                                            Expr::NPC_ValueDependentIsNull)) {
06661         RHS = ImpCastExprToType(RHS.get(), it->getType(),
06662                                 CK_NullToPointer);
06663         InitField = it;
06664         break;
06665       }
06666     }
06667 
06668     CastKind Kind = CK_Invalid;
06669     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
06670           == Compatible) {
06671       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
06672       InitField = it;
06673       break;
06674     }
06675   }
06676 
06677   if (!InitField)
06678     return Incompatible;
06679 
06680   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
06681   return Compatible;
06682 }
06683 
06684 Sema::AssignConvertType
06685 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
06686                                        bool Diagnose,
06687                                        bool DiagnoseCFAudited) {
06688   if (getLangOpts().CPlusPlus) {
06689     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
06690       // C++ 5.17p3: If the left operand is not of class type, the
06691       // expression is implicitly converted (C++ 4) to the
06692       // cv-unqualified type of the left operand.
06693       ExprResult Res;
06694       if (Diagnose) {
06695         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
06696                                         AA_Assigning);
06697       } else {
06698         ImplicitConversionSequence ICS =
06699             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
06700                                   /*SuppressUserConversions=*/false,
06701                                   /*AllowExplicit=*/false,
06702                                   /*InOverloadResolution=*/false,
06703                                   /*CStyle=*/false,
06704                                   /*AllowObjCWritebackConversion=*/false);
06705         if (ICS.isFailure())
06706           return Incompatible;
06707         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
06708                                         ICS, AA_Assigning);
06709       }
06710       if (Res.isInvalid())
06711         return Incompatible;
06712       Sema::AssignConvertType result = Compatible;
06713       if (getLangOpts().ObjCAutoRefCount &&
06714           !CheckObjCARCUnavailableWeakConversion(LHSType,
06715                                                  RHS.get()->getType()))
06716         result = IncompatibleObjCWeakRef;
06717       RHS = Res;
06718       return result;
06719     }
06720 
06721     // FIXME: Currently, we fall through and treat C++ classes like C
06722     // structures.
06723     // FIXME: We also fall through for atomics; not sure what should
06724     // happen there, though.
06725   }
06726 
06727   // C99 6.5.16.1p1: the left operand is a pointer and the right is
06728   // a null pointer constant.
06729   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
06730        LHSType->isBlockPointerType()) &&
06731       RHS.get()->isNullPointerConstant(Context,
06732                                        Expr::NPC_ValueDependentIsNull)) {
06733     CastKind Kind;
06734     CXXCastPath Path;
06735     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
06736     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
06737     return Compatible;
06738   }
06739 
06740   // This check seems unnatural, however it is necessary to ensure the proper
06741   // conversion of functions/arrays. If the conversion were done for all
06742   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
06743   // expressions that suppress this implicit conversion (&, sizeof).
06744   //
06745   // Suppress this for references: C++ 8.5.3p5.
06746   if (!LHSType->isReferenceType()) {
06747     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
06748     if (RHS.isInvalid())
06749       return Incompatible;
06750   }
06751 
06752   Expr *PRE = RHS.get()->IgnoreParenCasts();
06753   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
06754     ObjCProtocolDecl *PDecl = OPE->getProtocol();
06755     if (PDecl && !PDecl->hasDefinition()) {
06756       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
06757       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
06758     }
06759   }
06760   
06761   CastKind Kind = CK_Invalid;
06762   Sema::AssignConvertType result =
06763     CheckAssignmentConstraints(LHSType, RHS, Kind);
06764 
06765   // C99 6.5.16.1p2: The value of the right operand is converted to the
06766   // type of the assignment expression.
06767   // CheckAssignmentConstraints allows the left-hand side to be a reference,
06768   // so that we can use references in built-in functions even in C.
06769   // The getNonReferenceType() call makes sure that the resulting expression
06770   // does not have reference type.
06771   if (result != Incompatible && RHS.get()->getType() != LHSType) {
06772     QualType Ty = LHSType.getNonLValueExprType(Context);
06773     Expr *E = RHS.get();
06774     if (getLangOpts().ObjCAutoRefCount)
06775       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
06776                              DiagnoseCFAudited);
06777     if (getLangOpts().ObjC1 &&
06778         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
06779                                           LHSType, E->getType(), E) ||
06780          ConversionToObjCStringLiteralCheck(LHSType, E))) {
06781       RHS = E;
06782       return Compatible;
06783     }
06784     
06785     RHS = ImpCastExprToType(E, Ty, Kind);
06786   }
06787   return result;
06788 }
06789 
06790 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
06791                                ExprResult &RHS) {
06792   Diag(Loc, diag::err_typecheck_invalid_operands)
06793     << LHS.get()->getType() << RHS.get()->getType()
06794     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06795   return QualType();
06796 }
06797 
06798 /// Try to convert a value of non-vector type to a vector type by converting
06799 /// the type to the element type of the vector and then performing a splat.
06800 /// If the language is OpenCL, we only use conversions that promote scalar
06801 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
06802 /// for float->int.
06803 ///
06804 /// \param scalar - if non-null, actually perform the conversions
06805 /// \return true if the operation fails (but without diagnosing the failure)
06806 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
06807                                      QualType scalarTy,
06808                                      QualType vectorEltTy,
06809                                      QualType vectorTy) {
06810   // The conversion to apply to the scalar before splatting it,
06811   // if necessary.
06812   CastKind scalarCast = CK_Invalid;
06813   
06814   if (vectorEltTy->isIntegralType(S.Context)) {
06815     if (!scalarTy->isIntegralType(S.Context))
06816       return true;
06817     if (S.getLangOpts().OpenCL &&
06818         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
06819       return true;
06820     scalarCast = CK_IntegralCast;
06821   } else if (vectorEltTy->isRealFloatingType()) {
06822     if (scalarTy->isRealFloatingType()) {
06823       if (S.getLangOpts().OpenCL &&
06824           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
06825         return true;
06826       scalarCast = CK_FloatingCast;
06827     }
06828     else if (scalarTy->isIntegralType(S.Context))
06829       scalarCast = CK_IntegralToFloating;
06830     else
06831       return true;
06832   } else {
06833     return true;
06834   }
06835 
06836   // Adjust scalar if desired.
06837   if (scalar) {
06838     if (scalarCast != CK_Invalid)
06839       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
06840     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
06841   }
06842   return false;
06843 }
06844 
06845 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
06846                                    SourceLocation Loc, bool IsCompAssign) {
06847   if (!IsCompAssign) {
06848     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
06849     if (LHS.isInvalid())
06850       return QualType();
06851   }
06852   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
06853   if (RHS.isInvalid())
06854     return QualType();
06855 
06856   // For conversion purposes, we ignore any qualifiers.
06857   // For example, "const float" and "float" are equivalent.
06858   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
06859   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
06860 
06861   // If the vector types are identical, return.
06862   if (Context.hasSameType(LHSType, RHSType))
06863     return LHSType;
06864 
06865   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
06866   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
06867   assert(LHSVecType || RHSVecType);
06868 
06869   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
06870   if (LHSVecType && RHSVecType &&
06871       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
06872     if (isa<ExtVectorType>(LHSVecType)) {
06873       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
06874       return LHSType;
06875     }
06876 
06877     if (!IsCompAssign)
06878       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
06879     return RHSType;
06880   }
06881 
06882   // If there's an ext-vector type and a scalar, try to convert the scalar to
06883   // the vector element type and splat.
06884   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
06885     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
06886                                   LHSVecType->getElementType(), LHSType))
06887       return LHSType;
06888   }
06889   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
06890     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
06891                                   LHSType, RHSVecType->getElementType(),
06892                                   RHSType))
06893       return RHSType;
06894   }
06895 
06896   // If we're allowing lax vector conversions, only the total (data) size
06897   // needs to be the same.
06898   // FIXME: Should we really be allowing this?
06899   // FIXME: We really just pick the LHS type arbitrarily?
06900   if (isLaxVectorConversion(RHSType, LHSType)) {
06901     QualType resultType = LHSType;
06902     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
06903     return resultType;
06904   }
06905 
06906   // Okay, the expression is invalid.
06907 
06908   // If there's a non-vector, non-real operand, diagnose that.
06909   if ((!RHSVecType && !RHSType->isRealType()) ||
06910       (!LHSVecType && !LHSType->isRealType())) {
06911     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
06912       << LHSType << RHSType
06913       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06914     return QualType();
06915   }
06916 
06917   // Otherwise, use the generic diagnostic.
06918   Diag(Loc, diag::err_typecheck_vector_not_convertable)
06919     << LHSType << RHSType
06920     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06921   return QualType();
06922 }
06923 
06924 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
06925 // expression.  These are mainly cases where the null pointer is used as an
06926 // integer instead of a pointer.
06927 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
06928                                 SourceLocation Loc, bool IsCompare) {
06929   // The canonical way to check for a GNU null is with isNullPointerConstant,
06930   // but we use a bit of a hack here for speed; this is a relatively
06931   // hot path, and isNullPointerConstant is slow.
06932   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
06933   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
06934 
06935   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
06936 
06937   // Avoid analyzing cases where the result will either be invalid (and
06938   // diagnosed as such) or entirely valid and not something to warn about.
06939   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
06940       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
06941     return;
06942 
06943   // Comparison operations would not make sense with a null pointer no matter
06944   // what the other expression is.
06945   if (!IsCompare) {
06946     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
06947         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
06948         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
06949     return;
06950   }
06951 
06952   // The rest of the operations only make sense with a null pointer
06953   // if the other expression is a pointer.
06954   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
06955       NonNullType->canDecayToPointerType())
06956     return;
06957 
06958   S.Diag(Loc, diag::warn_null_in_comparison_operation)
06959       << LHSNull /* LHS is NULL */ << NonNullType
06960       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06961 }
06962 
06963 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
06964                                            SourceLocation Loc,
06965                                            bool IsCompAssign, bool IsDiv) {
06966   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
06967 
06968   if (LHS.get()->getType()->isVectorType() ||
06969       RHS.get()->getType()->isVectorType())
06970     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
06971 
06972   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
06973   if (LHS.isInvalid() || RHS.isInvalid())
06974     return QualType();
06975 
06976 
06977   if (compType.isNull() || !compType->isArithmeticType())
06978     return InvalidOperands(Loc, LHS, RHS);
06979 
06980   // Check for division by zero.
06981   llvm::APSInt RHSValue;
06982   if (IsDiv && !RHS.get()->isValueDependent() &&
06983       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
06984     DiagRuntimeBehavior(Loc, RHS.get(),
06985                         PDiag(diag::warn_division_by_zero)
06986                           << RHS.get()->getSourceRange());
06987 
06988   return compType;
06989 }
06990 
06991 QualType Sema::CheckRemainderOperands(
06992   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
06993   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
06994 
06995   if (LHS.get()->getType()->isVectorType() ||
06996       RHS.get()->getType()->isVectorType()) {
06997     if (LHS.get()->getType()->hasIntegerRepresentation() && 
06998         RHS.get()->getType()->hasIntegerRepresentation())
06999       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
07000     return InvalidOperands(Loc, LHS, RHS);
07001   }
07002 
07003   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
07004   if (LHS.isInvalid() || RHS.isInvalid())
07005     return QualType();
07006 
07007   if (compType.isNull() || !compType->isIntegerType())
07008     return InvalidOperands(Loc, LHS, RHS);
07009 
07010   // Check for remainder by zero.
07011   llvm::APSInt RHSValue;
07012   if (!RHS.get()->isValueDependent() &&
07013       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
07014     DiagRuntimeBehavior(Loc, RHS.get(),
07015                         PDiag(diag::warn_remainder_by_zero)
07016                           << RHS.get()->getSourceRange());
07017 
07018   return compType;
07019 }
07020 
07021 /// \brief Diagnose invalid arithmetic on two void pointers.
07022 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
07023                                                 Expr *LHSExpr, Expr *RHSExpr) {
07024   S.Diag(Loc, S.getLangOpts().CPlusPlus
07025                 ? diag::err_typecheck_pointer_arith_void_type
07026                 : diag::ext_gnu_void_ptr)
07027     << 1 /* two pointers */ << LHSExpr->getSourceRange()
07028                             << RHSExpr->getSourceRange();
07029 }
07030 
07031 /// \brief Diagnose invalid arithmetic on a void pointer.
07032 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
07033                                             Expr *Pointer) {
07034   S.Diag(Loc, S.getLangOpts().CPlusPlus
07035                 ? diag::err_typecheck_pointer_arith_void_type
07036                 : diag::ext_gnu_void_ptr)
07037     << 0 /* one pointer */ << Pointer->getSourceRange();
07038 }
07039 
07040 /// \brief Diagnose invalid arithmetic on two function pointers.
07041 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
07042                                                     Expr *LHS, Expr *RHS) {
07043   assert(LHS->getType()->isAnyPointerType());
07044   assert(RHS->getType()->isAnyPointerType());
07045   S.Diag(Loc, S.getLangOpts().CPlusPlus
07046                 ? diag::err_typecheck_pointer_arith_function_type
07047                 : diag::ext_gnu_ptr_func_arith)
07048     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
07049     // We only show the second type if it differs from the first.
07050     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
07051                                                    RHS->getType())
07052     << RHS->getType()->getPointeeType()
07053     << LHS->getSourceRange() << RHS->getSourceRange();
07054 }
07055 
07056 /// \brief Diagnose invalid arithmetic on a function pointer.
07057 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
07058                                                 Expr *Pointer) {
07059   assert(Pointer->getType()->isAnyPointerType());
07060   S.Diag(Loc, S.getLangOpts().CPlusPlus
07061                 ? diag::err_typecheck_pointer_arith_function_type
07062                 : diag::ext_gnu_ptr_func_arith)
07063     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
07064     << 0 /* one pointer, so only one type */
07065     << Pointer->getSourceRange();
07066 }
07067 
07068 /// \brief Emit error if Operand is incomplete pointer type
07069 ///
07070 /// \returns True if pointer has incomplete type
07071 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
07072                                                  Expr *Operand) {
07073   assert(Operand->getType()->isAnyPointerType() &&
07074          !Operand->getType()->isDependentType());
07075   QualType PointeeTy = Operand->getType()->getPointeeType();
07076   return S.RequireCompleteType(Loc, PointeeTy,
07077                                diag::err_typecheck_arithmetic_incomplete_type,
07078                                PointeeTy, Operand->getSourceRange());
07079 }
07080 
07081 /// \brief Check the validity of an arithmetic pointer operand.
07082 ///
07083 /// If the operand has pointer type, this code will check for pointer types
07084 /// which are invalid in arithmetic operations. These will be diagnosed
07085 /// appropriately, including whether or not the use is supported as an
07086 /// extension.
07087 ///
07088 /// \returns True when the operand is valid to use (even if as an extension).
07089 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
07090                                             Expr *Operand) {
07091   if (!Operand->getType()->isAnyPointerType()) return true;
07092 
07093   QualType PointeeTy = Operand->getType()->getPointeeType();
07094   if (PointeeTy->isVoidType()) {
07095     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
07096     return !S.getLangOpts().CPlusPlus;
07097   }
07098   if (PointeeTy->isFunctionType()) {
07099     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
07100     return !S.getLangOpts().CPlusPlus;
07101   }
07102 
07103   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
07104 
07105   return true;
07106 }
07107 
07108 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
07109 /// operands.
07110 ///
07111 /// This routine will diagnose any invalid arithmetic on pointer operands much
07112 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
07113 /// for emitting a single diagnostic even for operations where both LHS and RHS
07114 /// are (potentially problematic) pointers.
07115 ///
07116 /// \returns True when the operand is valid to use (even if as an extension).
07117 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
07118                                                 Expr *LHSExpr, Expr *RHSExpr) {
07119   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
07120   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
07121   if (!isLHSPointer && !isRHSPointer) return true;
07122 
07123   QualType LHSPointeeTy, RHSPointeeTy;
07124   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
07125   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
07126 
07127   // Check for arithmetic on pointers to incomplete types.
07128   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
07129   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
07130   if (isLHSVoidPtr || isRHSVoidPtr) {
07131     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
07132     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
07133     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
07134 
07135     return !S.getLangOpts().CPlusPlus;
07136   }
07137 
07138   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
07139   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
07140   if (isLHSFuncPtr || isRHSFuncPtr) {
07141     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
07142     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
07143                                                                 RHSExpr);
07144     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
07145 
07146     return !S.getLangOpts().CPlusPlus;
07147   }
07148 
07149   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
07150     return false;
07151   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
07152     return false;
07153 
07154   return true;
07155 }
07156 
07157 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
07158 /// literal.
07159 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
07160                                   Expr *LHSExpr, Expr *RHSExpr) {
07161   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
07162   Expr* IndexExpr = RHSExpr;
07163   if (!StrExpr) {
07164     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
07165     IndexExpr = LHSExpr;
07166   }
07167 
07168   bool IsStringPlusInt = StrExpr &&
07169       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
07170   if (!IsStringPlusInt)
07171     return;
07172 
07173   llvm::APSInt index;
07174   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
07175     unsigned StrLenWithNull = StrExpr->getLength() + 1;
07176     if (index.isNonNegative() &&
07177         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
07178                               index.isUnsigned()))
07179       return;
07180   }
07181 
07182   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
07183   Self.Diag(OpLoc, diag::warn_string_plus_int)
07184       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
07185 
07186   // Only print a fixit for "str" + int, not for int + "str".
07187   if (IndexExpr == RHSExpr) {
07188     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
07189     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
07190         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
07191         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
07192         << FixItHint::CreateInsertion(EndLoc, "]");
07193   } else
07194     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
07195 }
07196 
07197 /// \brief Emit a warning when adding a char literal to a string.
07198 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
07199                                    Expr *LHSExpr, Expr *RHSExpr) {
07200   const DeclRefExpr *StringRefExpr =
07201       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
07202   const CharacterLiteral *CharExpr =
07203       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
07204   if (!StringRefExpr) {
07205     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
07206     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
07207   }
07208 
07209   if (!CharExpr || !StringRefExpr)
07210     return;
07211 
07212   const QualType StringType = StringRefExpr->getType();
07213 
07214   // Return if not a PointerType.
07215   if (!StringType->isAnyPointerType())
07216     return;
07217 
07218   // Return if not a CharacterType.
07219   if (!StringType->getPointeeType()->isAnyCharacterType())
07220     return;
07221 
07222   ASTContext &Ctx = Self.getASTContext();
07223   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
07224 
07225   const QualType CharType = CharExpr->getType();
07226   if (!CharType->isAnyCharacterType() &&
07227       CharType->isIntegerType() &&
07228       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
07229     Self.Diag(OpLoc, diag::warn_string_plus_char)
07230         << DiagRange << Ctx.CharTy;
07231   } else {
07232     Self.Diag(OpLoc, diag::warn_string_plus_char)
07233         << DiagRange << CharExpr->getType();
07234   }
07235 
07236   // Only print a fixit for str + char, not for char + str.
07237   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
07238     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
07239     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
07240         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
07241         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
07242         << FixItHint::CreateInsertion(EndLoc, "]");
07243   } else {
07244     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
07245   }
07246 }
07247 
07248 /// \brief Emit error when two pointers are incompatible.
07249 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
07250                                            Expr *LHSExpr, Expr *RHSExpr) {
07251   assert(LHSExpr->getType()->isAnyPointerType());
07252   assert(RHSExpr->getType()->isAnyPointerType());
07253   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
07254     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
07255     << RHSExpr->getSourceRange();
07256 }
07257 
07258 QualType Sema::CheckAdditionOperands( // C99 6.5.6
07259     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
07260     QualType* CompLHSTy) {
07261   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
07262 
07263   if (LHS.get()->getType()->isVectorType() ||
07264       RHS.get()->getType()->isVectorType()) {
07265     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
07266     if (CompLHSTy) *CompLHSTy = compType;
07267     return compType;
07268   }
07269 
07270   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
07271   if (LHS.isInvalid() || RHS.isInvalid())
07272     return QualType();
07273 
07274   // Diagnose "string literal" '+' int and string '+' "char literal".
07275   if (Opc == BO_Add) {
07276     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
07277     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
07278   }
07279 
07280   // handle the common case first (both operands are arithmetic).
07281   if (!compType.isNull() && compType->isArithmeticType()) {
07282     if (CompLHSTy) *CompLHSTy = compType;
07283     return compType;
07284   }
07285 
07286   // Type-checking.  Ultimately the pointer's going to be in PExp;
07287   // note that we bias towards the LHS being the pointer.
07288   Expr *PExp = LHS.get(), *IExp = RHS.get();
07289 
07290   bool isObjCPointer;
07291   if (PExp->getType()->isPointerType()) {
07292     isObjCPointer = false;
07293   } else if (PExp->getType()->isObjCObjectPointerType()) {
07294     isObjCPointer = true;
07295   } else {
07296     std::swap(PExp, IExp);
07297     if (PExp->getType()->isPointerType()) {
07298       isObjCPointer = false;
07299     } else if (PExp->getType()->isObjCObjectPointerType()) {
07300       isObjCPointer = true;
07301     } else {
07302       return InvalidOperands(Loc, LHS, RHS);
07303     }
07304   }
07305   assert(PExp->getType()->isAnyPointerType());
07306 
07307   if (!IExp->getType()->isIntegerType())
07308     return InvalidOperands(Loc, LHS, RHS);
07309 
07310   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
07311     return QualType();
07312 
07313   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
07314     return QualType();
07315 
07316   // Check array bounds for pointer arithemtic
07317   CheckArrayAccess(PExp, IExp);
07318 
07319   if (CompLHSTy) {
07320     QualType LHSTy = Context.isPromotableBitField(LHS.get());
07321     if (LHSTy.isNull()) {
07322       LHSTy = LHS.get()->getType();
07323       if (LHSTy->isPromotableIntegerType())
07324         LHSTy = Context.getPromotedIntegerType(LHSTy);
07325     }
07326     *CompLHSTy = LHSTy;
07327   }
07328 
07329   return PExp->getType();
07330 }
07331 
07332 // C99 6.5.6
07333 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
07334                                         SourceLocation Loc,
07335                                         QualType* CompLHSTy) {
07336   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
07337 
07338   if (LHS.get()->getType()->isVectorType() ||
07339       RHS.get()->getType()->isVectorType()) {
07340     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
07341     if (CompLHSTy) *CompLHSTy = compType;
07342     return compType;
07343   }
07344 
07345   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
07346   if (LHS.isInvalid() || RHS.isInvalid())
07347     return QualType();
07348 
07349   // Enforce type constraints: C99 6.5.6p3.
07350 
07351   // Handle the common case first (both operands are arithmetic).
07352   if (!compType.isNull() && compType->isArithmeticType()) {
07353     if (CompLHSTy) *CompLHSTy = compType;
07354     return compType;
07355   }
07356 
07357   // Either ptr - int   or   ptr - ptr.
07358   if (LHS.get()->getType()->isAnyPointerType()) {
07359     QualType lpointee = LHS.get()->getType()->getPointeeType();
07360 
07361     // Diagnose bad cases where we step over interface counts.
07362     if (LHS.get()->getType()->isObjCObjectPointerType() &&
07363         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
07364       return QualType();
07365 
07366     // The result type of a pointer-int computation is the pointer type.
07367     if (RHS.get()->getType()->isIntegerType()) {
07368       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
07369         return QualType();
07370 
07371       // Check array bounds for pointer arithemtic
07372       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
07373                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
07374 
07375       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
07376       return LHS.get()->getType();
07377     }
07378 
07379     // Handle pointer-pointer subtractions.
07380     if (const PointerType *RHSPTy
07381           = RHS.get()->getType()->getAs<PointerType>()) {
07382       QualType rpointee = RHSPTy->getPointeeType();
07383 
07384       if (getLangOpts().CPlusPlus) {
07385         // Pointee types must be the same: C++ [expr.add]
07386         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
07387           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
07388         }
07389       } else {
07390         // Pointee types must be compatible C99 6.5.6p3
07391         if (!Context.typesAreCompatible(
07392                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
07393                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
07394           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
07395           return QualType();
07396         }
07397       }
07398 
07399       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
07400                                                LHS.get(), RHS.get()))
07401         return QualType();
07402 
07403       // The pointee type may have zero size.  As an extension, a structure or
07404       // union may have zero size or an array may have zero length.  In this
07405       // case subtraction does not make sense.
07406       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
07407         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
07408         if (ElementSize.isZero()) {
07409           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
07410             << rpointee.getUnqualifiedType()
07411             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
07412         }
07413       }
07414 
07415       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
07416       return Context.getPointerDiffType();
07417     }
07418   }
07419 
07420   return InvalidOperands(Loc, LHS, RHS);
07421 }
07422 
07423 static bool isScopedEnumerationType(QualType T) {
07424   if (const EnumType *ET = dyn_cast<EnumType>(T))
07425     return ET->getDecl()->isScoped();
07426   return false;
07427 }
07428 
07429 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
07430                                    SourceLocation Loc, unsigned Opc,
07431                                    QualType LHSType) {
07432   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
07433   // so skip remaining warnings as we don't want to modify values within Sema.
07434   if (S.getLangOpts().OpenCL)
07435     return;
07436 
07437   llvm::APSInt Right;
07438   // Check right/shifter operand
07439   if (RHS.get()->isValueDependent() ||
07440       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
07441     return;
07442 
07443   if (Right.isNegative()) {
07444     S.DiagRuntimeBehavior(Loc, RHS.get(),
07445                           S.PDiag(diag::warn_shift_negative)
07446                             << RHS.get()->getSourceRange());
07447     return;
07448   }
07449   llvm::APInt LeftBits(Right.getBitWidth(),
07450                        S.Context.getTypeSize(LHS.get()->getType()));
07451   if (Right.uge(LeftBits)) {
07452     S.DiagRuntimeBehavior(Loc, RHS.get(),
07453                           S.PDiag(diag::warn_shift_gt_typewidth)
07454                             << RHS.get()->getSourceRange());
07455     return;
07456   }
07457   if (Opc != BO_Shl)
07458     return;
07459 
07460   // When left shifting an ICE which is signed, we can check for overflow which
07461   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
07462   // integers have defined behavior modulo one more than the maximum value
07463   // representable in the result type, so never warn for those.
07464   llvm::APSInt Left;
07465   if (LHS.get()->isValueDependent() ||
07466       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
07467       LHSType->hasUnsignedIntegerRepresentation())
07468     return;
07469   llvm::APInt ResultBits =
07470       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
07471   if (LeftBits.uge(ResultBits))
07472     return;
07473   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
07474   Result = Result.shl(Right);
07475 
07476   // Print the bit representation of the signed integer as an unsigned
07477   // hexadecimal number.
07478   SmallString<40> HexResult;
07479   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
07480 
07481   // If we are only missing a sign bit, this is less likely to result in actual
07482   // bugs -- if the result is cast back to an unsigned type, it will have the
07483   // expected value. Thus we place this behind a different warning that can be
07484   // turned off separately if needed.
07485   if (LeftBits == ResultBits - 1) {
07486     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
07487         << HexResult.str() << LHSType
07488         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
07489     return;
07490   }
07491 
07492   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
07493     << HexResult.str() << Result.getMinSignedBits() << LHSType
07494     << Left.getBitWidth() << LHS.get()->getSourceRange()
07495     << RHS.get()->getSourceRange();
07496 }
07497 
07498 // C99 6.5.7
07499 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
07500                                   SourceLocation Loc, unsigned Opc,
07501                                   bool IsCompAssign) {
07502   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
07503 
07504   // Vector shifts promote their scalar inputs to vector type.
07505   if (LHS.get()->getType()->isVectorType() ||
07506       RHS.get()->getType()->isVectorType())
07507     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
07508 
07509   // Shifts don't perform usual arithmetic conversions, they just do integer
07510   // promotions on each operand. C99 6.5.7p3
07511 
07512   // For the LHS, do usual unary conversions, but then reset them away
07513   // if this is a compound assignment.
07514   ExprResult OldLHS = LHS;
07515   LHS = UsualUnaryConversions(LHS.get());
07516   if (LHS.isInvalid())
07517     return QualType();
07518   QualType LHSType = LHS.get()->getType();
07519   if (IsCompAssign) LHS = OldLHS;
07520 
07521   // The RHS is simpler.
07522   RHS = UsualUnaryConversions(RHS.get());
07523   if (RHS.isInvalid())
07524     return QualType();
07525   QualType RHSType = RHS.get()->getType();
07526 
07527   // C99 6.5.7p2: Each of the operands shall have integer type.
07528   if (!LHSType->hasIntegerRepresentation() ||
07529       !RHSType->hasIntegerRepresentation())
07530     return InvalidOperands(Loc, LHS, RHS);
07531 
07532   // C++0x: Don't allow scoped enums. FIXME: Use something better than
07533   // hasIntegerRepresentation() above instead of this.
07534   if (isScopedEnumerationType(LHSType) ||
07535       isScopedEnumerationType(RHSType)) {
07536     return InvalidOperands(Loc, LHS, RHS);
07537   }
07538   // Sanity-check shift operands
07539   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
07540 
07541   // "The type of the result is that of the promoted left operand."
07542   return LHSType;
07543 }
07544 
07545 static bool IsWithinTemplateSpecialization(Decl *D) {
07546   if (DeclContext *DC = D->getDeclContext()) {
07547     if (isa<ClassTemplateSpecializationDecl>(DC))
07548       return true;
07549     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
07550       return FD->isFunctionTemplateSpecialization();
07551   }
07552   return false;
07553 }
07554 
07555 /// If two different enums are compared, raise a warning.
07556 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
07557                                 Expr *RHS) {
07558   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
07559   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
07560 
07561   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
07562   if (!LHSEnumType)
07563     return;
07564   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
07565   if (!RHSEnumType)
07566     return;
07567 
07568   // Ignore anonymous enums.
07569   if (!LHSEnumType->getDecl()->getIdentifier())
07570     return;
07571   if (!RHSEnumType->getDecl()->getIdentifier())
07572     return;
07573 
07574   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
07575     return;
07576 
07577   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
07578       << LHSStrippedType << RHSStrippedType
07579       << LHS->getSourceRange() << RHS->getSourceRange();
07580 }
07581 
07582 /// \brief Diagnose bad pointer comparisons.
07583 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
07584                                               ExprResult &LHS, ExprResult &RHS,
07585                                               bool IsError) {
07586   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
07587                       : diag::ext_typecheck_comparison_of_distinct_pointers)
07588     << LHS.get()->getType() << RHS.get()->getType()
07589     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
07590 }
07591 
07592 /// \brief Returns false if the pointers are converted to a composite type,
07593 /// true otherwise.
07594 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
07595                                            ExprResult &LHS, ExprResult &RHS) {
07596   // C++ [expr.rel]p2:
07597   //   [...] Pointer conversions (4.10) and qualification
07598   //   conversions (4.4) are performed on pointer operands (or on
07599   //   a pointer operand and a null pointer constant) to bring
07600   //   them to their composite pointer type. [...]
07601   //
07602   // C++ [expr.eq]p1 uses the same notion for (in)equality
07603   // comparisons of pointers.
07604 
07605   // C++ [expr.eq]p2:
07606   //   In addition, pointers to members can be compared, or a pointer to
07607   //   member and a null pointer constant. Pointer to member conversions
07608   //   (4.11) and qualification conversions (4.4) are performed to bring
07609   //   them to a common type. If one operand is a null pointer constant,
07610   //   the common type is the type of the other operand. Otherwise, the
07611   //   common type is a pointer to member type similar (4.4) to the type
07612   //   of one of the operands, with a cv-qualification signature (4.4)
07613   //   that is the union of the cv-qualification signatures of the operand
07614   //   types.
07615 
07616   QualType LHSType = LHS.get()->getType();
07617   QualType RHSType = RHS.get()->getType();
07618   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
07619          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
07620 
07621   bool NonStandardCompositeType = false;
07622   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
07623   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
07624   if (T.isNull()) {
07625     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
07626     return true;
07627   }
07628 
07629   if (NonStandardCompositeType)
07630     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
07631       << LHSType << RHSType << T << LHS.get()->getSourceRange()
07632       << RHS.get()->getSourceRange();
07633 
07634   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
07635   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
07636   return false;
07637 }
07638 
07639 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
07640                                                     ExprResult &LHS,
07641                                                     ExprResult &RHS,
07642                                                     bool IsError) {
07643   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
07644                       : diag::ext_typecheck_comparison_of_fptr_to_void)
07645     << LHS.get()->getType() << RHS.get()->getType()
07646     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
07647 }
07648 
07649 static bool isObjCObjectLiteral(ExprResult &E) {
07650   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
07651   case Stmt::ObjCArrayLiteralClass:
07652   case Stmt::ObjCDictionaryLiteralClass:
07653   case Stmt::ObjCStringLiteralClass:
07654   case Stmt::ObjCBoxedExprClass:
07655     return true;
07656   default:
07657     // Note that ObjCBoolLiteral is NOT an object literal!
07658     return false;
07659   }
07660 }
07661 
07662 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
07663   const ObjCObjectPointerType *Type =
07664     LHS->getType()->getAs<ObjCObjectPointerType>();
07665 
07666   // If this is not actually an Objective-C object, bail out.
07667   if (!Type)
07668     return false;
07669 
07670   // Get the LHS object's interface type.
07671   QualType InterfaceType = Type->getPointeeType();
07672   if (const ObjCObjectType *iQFaceTy =
07673       InterfaceType->getAsObjCQualifiedInterfaceType())
07674     InterfaceType = iQFaceTy->getBaseType();
07675 
07676   // If the RHS isn't an Objective-C object, bail out.
07677   if (!RHS->getType()->isObjCObjectPointerType())
07678     return false;
07679 
07680   // Try to find the -isEqual: method.
07681   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
07682   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
07683                                                       InterfaceType,
07684                                                       /*instance=*/true);
07685   if (!Method) {
07686     if (Type->isObjCIdType()) {
07687       // For 'id', just check the global pool.
07688       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
07689                                                   /*receiverId=*/true,
07690                                                   /*warn=*/false);
07691     } else {
07692       // Check protocols.
07693       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
07694                                              /*instance=*/true);
07695     }
07696   }
07697 
07698   if (!Method)
07699     return false;
07700 
07701   QualType T = Method->parameters()[0]->getType();
07702   if (!T->isObjCObjectPointerType())
07703     return false;
07704 
07705   QualType R = Method->getReturnType();
07706   if (!R->isScalarType())
07707     return false;
07708 
07709   return true;
07710 }
07711 
07712 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
07713   FromE = FromE->IgnoreParenImpCasts();
07714   switch (FromE->getStmtClass()) {
07715     default:
07716       break;
07717     case Stmt::ObjCStringLiteralClass:
07718       // "string literal"
07719       return LK_String;
07720     case Stmt::ObjCArrayLiteralClass:
07721       // "array literal"
07722       return LK_Array;
07723     case Stmt::ObjCDictionaryLiteralClass:
07724       // "dictionary literal"
07725       return LK_Dictionary;
07726     case Stmt::BlockExprClass:
07727       return LK_Block;
07728     case Stmt::ObjCBoxedExprClass: {
07729       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
07730       switch (Inner->getStmtClass()) {
07731         case Stmt::IntegerLiteralClass:
07732         case Stmt::FloatingLiteralClass:
07733         case Stmt::CharacterLiteralClass:
07734         case Stmt::ObjCBoolLiteralExprClass:
07735         case Stmt::CXXBoolLiteralExprClass:
07736           // "numeric literal"
07737           return LK_Numeric;
07738         case Stmt::ImplicitCastExprClass: {
07739           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
07740           // Boolean literals can be represented by implicit casts.
07741           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
07742             return LK_Numeric;
07743           break;
07744         }
07745         default:
07746           break;
07747       }
07748       return LK_Boxed;
07749     }
07750   }
07751   return LK_None;
07752 }
07753 
07754 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
07755                                           ExprResult &LHS, ExprResult &RHS,
07756                                           BinaryOperator::Opcode Opc){
07757   Expr *Literal;
07758   Expr *Other;
07759   if (isObjCObjectLiteral(LHS)) {
07760     Literal = LHS.get();
07761     Other = RHS.get();
07762   } else {
07763     Literal = RHS.get();
07764     Other = LHS.get();
07765   }
07766 
07767   // Don't warn on comparisons against nil.
07768   Other = Other->IgnoreParenCasts();
07769   if (Other->isNullPointerConstant(S.getASTContext(),
07770                                    Expr::NPC_ValueDependentIsNotNull))
07771     return;
07772 
07773   // This should be kept in sync with warn_objc_literal_comparison.
07774   // LK_String should always be after the other literals, since it has its own
07775   // warning flag.
07776   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
07777   assert(LiteralKind != Sema::LK_Block);
07778   if (LiteralKind == Sema::LK_None) {
07779     llvm_unreachable("Unknown Objective-C object literal kind");
07780   }
07781 
07782   if (LiteralKind == Sema::LK_String)
07783     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
07784       << Literal->getSourceRange();
07785   else
07786     S.Diag(Loc, diag::warn_objc_literal_comparison)
07787       << LiteralKind << Literal->getSourceRange();
07788 
07789   if (BinaryOperator::isEqualityOp(Opc) &&
07790       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
07791     SourceLocation Start = LHS.get()->getLocStart();
07792     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
07793     CharSourceRange OpRange =
07794       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
07795 
07796     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
07797       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
07798       << FixItHint::CreateReplacement(OpRange, " isEqual:")
07799       << FixItHint::CreateInsertion(End, "]");
07800   }
07801 }
07802 
07803 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
07804                                                 ExprResult &RHS,
07805                                                 SourceLocation Loc,
07806                                                 unsigned OpaqueOpc) {
07807   // This checking requires bools.
07808   if (!S.getLangOpts().Bool) return;
07809 
07810   // Check that left hand side is !something.
07811   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
07812   if (!UO || UO->getOpcode() != UO_LNot) return;
07813 
07814   // Only check if the right hand side is non-bool arithmetic type.
07815   if (RHS.get()->getType()->isBooleanType()) return;
07816 
07817   // Make sure that the something in !something is not bool.
07818   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
07819   if (SubExpr->getType()->isBooleanType()) return;
07820 
07821   // Emit warning.
07822   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
07823       << Loc;
07824 
07825   // First note suggest !(x < y)
07826   SourceLocation FirstOpen = SubExpr->getLocStart();
07827   SourceLocation FirstClose = RHS.get()->getLocEnd();
07828   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
07829   if (FirstClose.isInvalid())
07830     FirstOpen = SourceLocation();
07831   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
07832       << FixItHint::CreateInsertion(FirstOpen, "(")
07833       << FixItHint::CreateInsertion(FirstClose, ")");
07834 
07835   // Second note suggests (!x) < y
07836   SourceLocation SecondOpen = LHS.get()->getLocStart();
07837   SourceLocation SecondClose = LHS.get()->getLocEnd();
07838   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
07839   if (SecondClose.isInvalid())
07840     SecondOpen = SourceLocation();
07841   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
07842       << FixItHint::CreateInsertion(SecondOpen, "(")
07843       << FixItHint::CreateInsertion(SecondClose, ")");
07844 }
07845 
07846 // Get the decl for a simple expression: a reference to a variable,
07847 // an implicit C++ field reference, or an implicit ObjC ivar reference.
07848 static ValueDecl *getCompareDecl(Expr *E) {
07849   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
07850     return DR->getDecl();
07851   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
07852     if (Ivar->isFreeIvar())
07853       return Ivar->getDecl();
07854   }
07855   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
07856     if (Mem->isImplicitAccess())
07857       return Mem->getMemberDecl();
07858   }
07859   return nullptr;
07860 }
07861 
07862 // C99 6.5.8, C++ [expr.rel]
07863 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
07864                                     SourceLocation Loc, unsigned OpaqueOpc,
07865                                     bool IsRelational) {
07866   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
07867 
07868   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
07869 
07870   // Handle vector comparisons separately.
07871   if (LHS.get()->getType()->isVectorType() ||
07872       RHS.get()->getType()->isVectorType())
07873     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
07874 
07875   QualType LHSType = LHS.get()->getType();
07876   QualType RHSType = RHS.get()->getType();
07877 
07878   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
07879   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
07880 
07881   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
07882   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
07883 
07884   if (!LHSType->hasFloatingRepresentation() &&
07885       !(LHSType->isBlockPointerType() && IsRelational) &&
07886       !LHS.get()->getLocStart().isMacroID() &&
07887       !RHS.get()->getLocStart().isMacroID() &&
07888       ActiveTemplateInstantiations.empty()) {
07889     // For non-floating point types, check for self-comparisons of the form
07890     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
07891     // often indicate logic errors in the program.
07892     //
07893     // NOTE: Don't warn about comparison expressions resulting from macro
07894     // expansion. Also don't warn about comparisons which are only self
07895     // comparisons within a template specialization. The warnings should catch
07896     // obvious cases in the definition of the template anyways. The idea is to
07897     // warn when the typed comparison operator will always evaluate to the same
07898     // result.
07899     ValueDecl *DL = getCompareDecl(LHSStripped);
07900     ValueDecl *DR = getCompareDecl(RHSStripped);
07901     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
07902       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
07903                           << 0 // self-
07904                           << (Opc == BO_EQ
07905                               || Opc == BO_LE
07906                               || Opc == BO_GE));
07907     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
07908                !DL->getType()->isReferenceType() &&
07909                !DR->getType()->isReferenceType()) {
07910         // what is it always going to eval to?
07911         char always_evals_to;
07912         switch(Opc) {
07913         case BO_EQ: // e.g. array1 == array2
07914           always_evals_to = 0; // false
07915           break;
07916         case BO_NE: // e.g. array1 != array2
07917           always_evals_to = 1; // true
07918           break;
07919         default:
07920           // best we can say is 'a constant'
07921           always_evals_to = 2; // e.g. array1 <= array2
07922           break;
07923         }
07924         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
07925                             << 1 // array
07926                             << always_evals_to);
07927     }
07928 
07929     if (isa<CastExpr>(LHSStripped))
07930       LHSStripped = LHSStripped->IgnoreParenCasts();
07931     if (isa<CastExpr>(RHSStripped))
07932       RHSStripped = RHSStripped->IgnoreParenCasts();
07933 
07934     // Warn about comparisons against a string constant (unless the other
07935     // operand is null), the user probably wants strcmp.
07936     Expr *literalString = nullptr;
07937     Expr *literalStringStripped = nullptr;
07938     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
07939         !RHSStripped->isNullPointerConstant(Context,
07940                                             Expr::NPC_ValueDependentIsNull)) {
07941       literalString = LHS.get();
07942       literalStringStripped = LHSStripped;
07943     } else if ((isa<StringLiteral>(RHSStripped) ||
07944                 isa<ObjCEncodeExpr>(RHSStripped)) &&
07945                !LHSStripped->isNullPointerConstant(Context,
07946                                             Expr::NPC_ValueDependentIsNull)) {
07947       literalString = RHS.get();
07948       literalStringStripped = RHSStripped;
07949     }
07950 
07951     if (literalString) {
07952       DiagRuntimeBehavior(Loc, nullptr,
07953         PDiag(diag::warn_stringcompare)
07954           << isa<ObjCEncodeExpr>(literalStringStripped)
07955           << literalString->getSourceRange());
07956     }
07957   }
07958 
07959   // C99 6.5.8p3 / C99 6.5.9p4
07960   UsualArithmeticConversions(LHS, RHS);
07961   if (LHS.isInvalid() || RHS.isInvalid())
07962     return QualType();
07963 
07964   LHSType = LHS.get()->getType();
07965   RHSType = RHS.get()->getType();
07966 
07967   // The result of comparisons is 'bool' in C++, 'int' in C.
07968   QualType ResultTy = Context.getLogicalOperationType();
07969 
07970   if (IsRelational) {
07971     if (LHSType->isRealType() && RHSType->isRealType())
07972       return ResultTy;
07973   } else {
07974     // Check for comparisons of floating point operands using != and ==.
07975     if (LHSType->hasFloatingRepresentation())
07976       CheckFloatComparison(Loc, LHS.get(), RHS.get());
07977 
07978     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
07979       return ResultTy;
07980   }
07981 
07982   const Expr::NullPointerConstantKind LHSNullKind =
07983       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
07984   const Expr::NullPointerConstantKind RHSNullKind =
07985       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
07986   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
07987   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
07988 
07989   if (!IsRelational && LHSIsNull != RHSIsNull) {
07990     bool IsEquality = Opc == BO_EQ;
07991     if (RHSIsNull)
07992       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
07993                                    RHS.get()->getSourceRange());
07994     else
07995       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
07996                                    LHS.get()->getSourceRange());
07997   }
07998 
07999   // All of the following pointer-related warnings are GCC extensions, except
08000   // when handling null pointer constants. 
08001   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
08002     QualType LCanPointeeTy =
08003       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
08004     QualType RCanPointeeTy =
08005       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
08006 
08007     if (getLangOpts().CPlusPlus) {
08008       if (LCanPointeeTy == RCanPointeeTy)
08009         return ResultTy;
08010       if (!IsRelational &&
08011           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
08012         // Valid unless comparison between non-null pointer and function pointer
08013         // This is a gcc extension compatibility comparison.
08014         // In a SFINAE context, we treat this as a hard error to maintain
08015         // conformance with the C++ standard.
08016         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
08017             && !LHSIsNull && !RHSIsNull) {
08018           diagnoseFunctionPointerToVoidComparison(
08019               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
08020           
08021           if (isSFINAEContext())
08022             return QualType();
08023           
08024           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
08025           return ResultTy;
08026         }
08027       }
08028 
08029       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
08030         return QualType();
08031       else
08032         return ResultTy;
08033     }
08034     // C99 6.5.9p2 and C99 6.5.8p2
08035     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
08036                                    RCanPointeeTy.getUnqualifiedType())) {
08037       // Valid unless a relational comparison of function pointers
08038       if (IsRelational && LCanPointeeTy->isFunctionType()) {
08039         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
08040           << LHSType << RHSType << LHS.get()->getSourceRange()
08041           << RHS.get()->getSourceRange();
08042       }
08043     } else if (!IsRelational &&
08044                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
08045       // Valid unless comparison between non-null pointer and function pointer
08046       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
08047           && !LHSIsNull && !RHSIsNull)
08048         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
08049                                                 /*isError*/false);
08050     } else {
08051       // Invalid
08052       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
08053     }
08054     if (LCanPointeeTy != RCanPointeeTy) {
08055       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
08056       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
08057       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
08058                                                : CK_BitCast;
08059       if (LHSIsNull && !RHSIsNull)
08060         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
08061       else
08062         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
08063     }
08064     return ResultTy;
08065   }
08066 
08067   if (getLangOpts().CPlusPlus) {
08068     // Comparison of nullptr_t with itself.
08069     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
08070       return ResultTy;
08071     
08072     // Comparison of pointers with null pointer constants and equality
08073     // comparisons of member pointers to null pointer constants.
08074     if (RHSIsNull &&
08075         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
08076          (!IsRelational && 
08077           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
08078       RHS = ImpCastExprToType(RHS.get(), LHSType, 
08079                         LHSType->isMemberPointerType()
08080                           ? CK_NullToMemberPointer
08081                           : CK_NullToPointer);
08082       return ResultTy;
08083     }
08084     if (LHSIsNull &&
08085         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
08086          (!IsRelational && 
08087           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
08088       LHS = ImpCastExprToType(LHS.get(), RHSType, 
08089                         RHSType->isMemberPointerType()
08090                           ? CK_NullToMemberPointer
08091                           : CK_NullToPointer);
08092       return ResultTy;
08093     }
08094 
08095     // Comparison of member pointers.
08096     if (!IsRelational &&
08097         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
08098       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
08099         return QualType();
08100       else
08101         return ResultTy;
08102     }
08103 
08104     // Handle scoped enumeration types specifically, since they don't promote
08105     // to integers.
08106     if (LHS.get()->getType()->isEnumeralType() &&
08107         Context.hasSameUnqualifiedType(LHS.get()->getType(),
08108                                        RHS.get()->getType()))
08109       return ResultTy;
08110   }
08111 
08112   // Handle block pointer types.
08113   if (!IsRelational && LHSType->isBlockPointerType() &&
08114       RHSType->isBlockPointerType()) {
08115     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
08116     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
08117 
08118     if (!LHSIsNull && !RHSIsNull &&
08119         !Context.typesAreCompatible(lpointee, rpointee)) {
08120       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
08121         << LHSType << RHSType << LHS.get()->getSourceRange()
08122         << RHS.get()->getSourceRange();
08123     }
08124     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
08125     return ResultTy;
08126   }
08127 
08128   // Allow block pointers to be compared with null pointer constants.
08129   if (!IsRelational
08130       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
08131           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
08132     if (!LHSIsNull && !RHSIsNull) {
08133       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
08134              ->getPointeeType()->isVoidType())
08135             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
08136                 ->getPointeeType()->isVoidType())))
08137         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
08138           << LHSType << RHSType << LHS.get()->getSourceRange()
08139           << RHS.get()->getSourceRange();
08140     }
08141     if (LHSIsNull && !RHSIsNull)
08142       LHS = ImpCastExprToType(LHS.get(), RHSType,
08143                               RHSType->isPointerType() ? CK_BitCast
08144                                 : CK_AnyPointerToBlockPointerCast);
08145     else
08146       RHS = ImpCastExprToType(RHS.get(), LHSType,
08147                               LHSType->isPointerType() ? CK_BitCast
08148                                 : CK_AnyPointerToBlockPointerCast);
08149     return ResultTy;
08150   }
08151 
08152   if (LHSType->isObjCObjectPointerType() ||
08153       RHSType->isObjCObjectPointerType()) {
08154     const PointerType *LPT = LHSType->getAs<PointerType>();
08155     const PointerType *RPT = RHSType->getAs<PointerType>();
08156     if (LPT || RPT) {
08157       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
08158       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
08159 
08160       if (!LPtrToVoid && !RPtrToVoid &&
08161           !Context.typesAreCompatible(LHSType, RHSType)) {
08162         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
08163                                           /*isError*/false);
08164       }
08165       if (LHSIsNull && !RHSIsNull) {
08166         Expr *E = LHS.get();
08167         if (getLangOpts().ObjCAutoRefCount)
08168           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
08169         LHS = ImpCastExprToType(E, RHSType,
08170                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
08171       }
08172       else {
08173         Expr *E = RHS.get();
08174         if (getLangOpts().ObjCAutoRefCount)
08175           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
08176                                  Opc);
08177         RHS = ImpCastExprToType(E, LHSType,
08178                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
08179       }
08180       return ResultTy;
08181     }
08182     if (LHSType->isObjCObjectPointerType() &&
08183         RHSType->isObjCObjectPointerType()) {
08184       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
08185         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
08186                                           /*isError*/false);
08187       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
08188         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
08189 
08190       if (LHSIsNull && !RHSIsNull)
08191         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
08192       else
08193         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
08194       return ResultTy;
08195     }
08196   }
08197   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
08198       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
08199     unsigned DiagID = 0;
08200     bool isError = false;
08201     if (LangOpts.DebuggerSupport) {
08202       // Under a debugger, allow the comparison of pointers to integers,
08203       // since users tend to want to compare addresses.
08204     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
08205         (RHSIsNull && RHSType->isIntegerType())) {
08206       if (IsRelational && !getLangOpts().CPlusPlus)
08207         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
08208     } else if (IsRelational && !getLangOpts().CPlusPlus)
08209       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
08210     else if (getLangOpts().CPlusPlus) {
08211       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
08212       isError = true;
08213     } else
08214       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
08215 
08216     if (DiagID) {
08217       Diag(Loc, DiagID)
08218         << LHSType << RHSType << LHS.get()->getSourceRange()
08219         << RHS.get()->getSourceRange();
08220       if (isError)
08221         return QualType();
08222     }
08223     
08224     if (LHSType->isIntegerType())
08225       LHS = ImpCastExprToType(LHS.get(), RHSType,
08226                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
08227     else
08228       RHS = ImpCastExprToType(RHS.get(), LHSType,
08229                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
08230     return ResultTy;
08231   }
08232   
08233   // Handle block pointers.
08234   if (!IsRelational && RHSIsNull
08235       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
08236     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
08237     return ResultTy;
08238   }
08239   if (!IsRelational && LHSIsNull
08240       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
08241     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
08242     return ResultTy;
08243   }
08244 
08245   return InvalidOperands(Loc, LHS, RHS);
08246 }
08247 
08248 
08249 // Return a signed type that is of identical size and number of elements.
08250 // For floating point vectors, return an integer type of identical size 
08251 // and number of elements.
08252 QualType Sema::GetSignedVectorType(QualType V) {
08253   const VectorType *VTy = V->getAs<VectorType>();
08254   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
08255   if (TypeSize == Context.getTypeSize(Context.CharTy))
08256     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
08257   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
08258     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
08259   else if (TypeSize == Context.getTypeSize(Context.IntTy))
08260     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
08261   else if (TypeSize == Context.getTypeSize(Context.LongTy))
08262     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
08263   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
08264          "Unhandled vector element size in vector compare");
08265   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
08266 }
08267 
08268 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
08269 /// operates on extended vector types.  Instead of producing an IntTy result,
08270 /// like a scalar comparison, a vector comparison produces a vector of integer
08271 /// types.
08272 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
08273                                           SourceLocation Loc,
08274                                           bool IsRelational) {
08275   // Check to make sure we're operating on vectors of the same type and width,
08276   // Allowing one side to be a scalar of element type.
08277   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
08278   if (vType.isNull())
08279     return vType;
08280 
08281   QualType LHSType = LHS.get()->getType();
08282 
08283   // If AltiVec, the comparison results in a numeric type, i.e.
08284   // bool for C++, int for C
08285   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
08286     return Context.getLogicalOperationType();
08287 
08288   // For non-floating point types, check for self-comparisons of the form
08289   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
08290   // often indicate logic errors in the program.
08291   if (!LHSType->hasFloatingRepresentation() &&
08292       ActiveTemplateInstantiations.empty()) {
08293     if (DeclRefExpr* DRL
08294           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
08295       if (DeclRefExpr* DRR
08296             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
08297         if (DRL->getDecl() == DRR->getDecl())
08298           DiagRuntimeBehavior(Loc, nullptr,
08299                               PDiag(diag::warn_comparison_always)
08300                                 << 0 // self-
08301                                 << 2 // "a constant"
08302                               );
08303   }
08304 
08305   // Check for comparisons of floating point operands using != and ==.
08306   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
08307     assert (RHS.get()->getType()->hasFloatingRepresentation());
08308     CheckFloatComparison(Loc, LHS.get(), RHS.get());
08309   }
08310   
08311   // Return a signed type for the vector.
08312   return GetSignedVectorType(LHSType);
08313 }
08314 
08315 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
08316                                           SourceLocation Loc) {
08317   // Ensure that either both operands are of the same vector type, or
08318   // one operand is of a vector type and the other is of its element type.
08319   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
08320   if (vType.isNull())
08321     return InvalidOperands(Loc, LHS, RHS);
08322   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
08323       vType->hasFloatingRepresentation())
08324     return InvalidOperands(Loc, LHS, RHS);
08325   
08326   return GetSignedVectorType(LHS.get()->getType());
08327 }
08328 
08329 inline QualType Sema::CheckBitwiseOperands(
08330   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
08331   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
08332 
08333   if (LHS.get()->getType()->isVectorType() ||
08334       RHS.get()->getType()->isVectorType()) {
08335     if (LHS.get()->getType()->hasIntegerRepresentation() &&
08336         RHS.get()->getType()->hasIntegerRepresentation())
08337       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
08338     
08339     return InvalidOperands(Loc, LHS, RHS);
08340   }
08341 
08342   ExprResult LHSResult = LHS, RHSResult = RHS;
08343   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
08344                                                  IsCompAssign);
08345   if (LHSResult.isInvalid() || RHSResult.isInvalid())
08346     return QualType();
08347   LHS = LHSResult.get();
08348   RHS = RHSResult.get();
08349 
08350   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
08351     return compType;
08352   return InvalidOperands(Loc, LHS, RHS);
08353 }
08354 
08355 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
08356   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
08357   
08358   // Check vector operands differently.
08359   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
08360     return CheckVectorLogicalOperands(LHS, RHS, Loc);
08361   
08362   // Diagnose cases where the user write a logical and/or but probably meant a
08363   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
08364   // is a constant.
08365   if (LHS.get()->getType()->isIntegerType() &&
08366       !LHS.get()->getType()->isBooleanType() &&
08367       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
08368       // Don't warn in macros or template instantiations.
08369       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
08370     // If the RHS can be constant folded, and if it constant folds to something
08371     // that isn't 0 or 1 (which indicate a potential logical operation that
08372     // happened to fold to true/false) then warn.
08373     // Parens on the RHS are ignored.
08374     llvm::APSInt Result;
08375     if (RHS.get()->EvaluateAsInt(Result, Context))
08376       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
08377            !RHS.get()->getExprLoc().isMacroID()) ||
08378           (Result != 0 && Result != 1)) {
08379         Diag(Loc, diag::warn_logical_instead_of_bitwise)
08380           << RHS.get()->getSourceRange()
08381           << (Opc == BO_LAnd ? "&&" : "||");
08382         // Suggest replacing the logical operator with the bitwise version
08383         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
08384             << (Opc == BO_LAnd ? "&" : "|")
08385             << FixItHint::CreateReplacement(SourceRange(
08386                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
08387                                                 getLangOpts())),
08388                                             Opc == BO_LAnd ? "&" : "|");
08389         if (Opc == BO_LAnd)
08390           // Suggest replacing "Foo() && kNonZero" with "Foo()"
08391           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
08392               << FixItHint::CreateRemoval(
08393                   SourceRange(
08394                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
08395                                                  0, getSourceManager(),
08396                                                  getLangOpts()),
08397                       RHS.get()->getLocEnd()));
08398       }
08399   }
08400 
08401   if (!Context.getLangOpts().CPlusPlus) {
08402     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
08403     // not operate on the built-in scalar and vector float types.
08404     if (Context.getLangOpts().OpenCL &&
08405         Context.getLangOpts().OpenCLVersion < 120) {
08406       if (LHS.get()->getType()->isFloatingType() ||
08407           RHS.get()->getType()->isFloatingType())
08408         return InvalidOperands(Loc, LHS, RHS);
08409     }
08410 
08411     LHS = UsualUnaryConversions(LHS.get());
08412     if (LHS.isInvalid())
08413       return QualType();
08414 
08415     RHS = UsualUnaryConversions(RHS.get());
08416     if (RHS.isInvalid())
08417       return QualType();
08418 
08419     if (!LHS.get()->getType()->isScalarType() ||
08420         !RHS.get()->getType()->isScalarType())
08421       return InvalidOperands(Loc, LHS, RHS);
08422 
08423     return Context.IntTy;
08424   }
08425 
08426   // The following is safe because we only use this method for
08427   // non-overloadable operands.
08428 
08429   // C++ [expr.log.and]p1
08430   // C++ [expr.log.or]p1
08431   // The operands are both contextually converted to type bool.
08432   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
08433   if (LHSRes.isInvalid())
08434     return InvalidOperands(Loc, LHS, RHS);
08435   LHS = LHSRes;
08436 
08437   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
08438   if (RHSRes.isInvalid())
08439     return InvalidOperands(Loc, LHS, RHS);
08440   RHS = RHSRes;
08441 
08442   // C++ [expr.log.and]p2
08443   // C++ [expr.log.or]p2
08444   // The result is a bool.
08445   return Context.BoolTy;
08446 }
08447 
08448 static bool IsReadonlyMessage(Expr *E, Sema &S) {
08449   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
08450   if (!ME) return false;
08451   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
08452   ObjCMessageExpr *Base =
08453     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
08454   if (!Base) return false;
08455   return Base->getMethodDecl() != nullptr;
08456 }
08457 
08458 /// Is the given expression (which must be 'const') a reference to a
08459 /// variable which was originally non-const, but which has become
08460 /// 'const' due to being captured within a block?
08461 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
08462 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
08463   assert(E->isLValue() && E->getType().isConstQualified());
08464   E = E->IgnoreParens();
08465 
08466   // Must be a reference to a declaration from an enclosing scope.
08467   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
08468   if (!DRE) return NCCK_None;
08469   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
08470 
08471   // The declaration must be a variable which is not declared 'const'.
08472   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
08473   if (!var) return NCCK_None;
08474   if (var->getType().isConstQualified()) return NCCK_None;
08475   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
08476 
08477   // Decide whether the first capture was for a block or a lambda.
08478   DeclContext *DC = S.CurContext, *Prev = nullptr;
08479   while (DC != var->getDeclContext()) {
08480     Prev = DC;
08481     DC = DC->getParent();
08482   }
08483   // Unless we have an init-capture, we've gone one step too far.
08484   if (!var->isInitCapture())
08485     DC = Prev;
08486   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
08487 }
08488 
08489 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
08490 /// emit an error and return true.  If so, return false.
08491 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
08492   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
08493   SourceLocation OrigLoc = Loc;
08494   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
08495                                                               &Loc);
08496   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
08497     IsLV = Expr::MLV_InvalidMessageExpression;
08498   if (IsLV == Expr::MLV_Valid)
08499     return false;
08500 
08501   unsigned Diag = 0;
08502   bool NeedType = false;
08503   switch (IsLV) { // C99 6.5.16p2
08504   case Expr::MLV_ConstQualified:
08505     Diag = diag::err_typecheck_assign_const;
08506 
08507     // Use a specialized diagnostic when we're assigning to an object
08508     // from an enclosing function or block.
08509     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
08510       if (NCCK == NCCK_Block)
08511         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
08512       else
08513         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
08514       break;
08515     }
08516 
08517     // In ARC, use some specialized diagnostics for occasions where we
08518     // infer 'const'.  These are always pseudo-strong variables.
08519     if (S.getLangOpts().ObjCAutoRefCount) {
08520       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
08521       if (declRef && isa<VarDecl>(declRef->getDecl())) {
08522         VarDecl *var = cast<VarDecl>(declRef->getDecl());
08523 
08524         // Use the normal diagnostic if it's pseudo-__strong but the
08525         // user actually wrote 'const'.
08526         if (var->isARCPseudoStrong() &&
08527             (!var->getTypeSourceInfo() ||
08528              !var->getTypeSourceInfo()->getType().isConstQualified())) {
08529           // There are two pseudo-strong cases:
08530           //  - self
08531           ObjCMethodDecl *method = S.getCurMethodDecl();
08532           if (method && var == method->getSelfDecl())
08533             Diag = method->isClassMethod()
08534               ? diag::err_typecheck_arc_assign_self_class_method
08535               : diag::err_typecheck_arc_assign_self;
08536 
08537           //  - fast enumeration variables
08538           else
08539             Diag = diag::err_typecheck_arr_assign_enumeration;
08540 
08541           SourceRange Assign;
08542           if (Loc != OrigLoc)
08543             Assign = SourceRange(OrigLoc, OrigLoc);
08544           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
08545           // We need to preserve the AST regardless, so migration tool 
08546           // can do its job.
08547           return false;
08548         }
08549       }
08550     }
08551 
08552     break;
08553   case Expr::MLV_ArrayType:
08554   case Expr::MLV_ArrayTemporary:
08555     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
08556     NeedType = true;
08557     break;
08558   case Expr::MLV_NotObjectType:
08559     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
08560     NeedType = true;
08561     break;
08562   case Expr::MLV_LValueCast:
08563     Diag = diag::err_typecheck_lvalue_casts_not_supported;
08564     break;
08565   case Expr::MLV_Valid:
08566     llvm_unreachable("did not take early return for MLV_Valid");
08567   case Expr::MLV_InvalidExpression:
08568   case Expr::MLV_MemberFunction:
08569   case Expr::MLV_ClassTemporary:
08570     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
08571     break;
08572   case Expr::MLV_IncompleteType:
08573   case Expr::MLV_IncompleteVoidType:
08574     return S.RequireCompleteType(Loc, E->getType(),
08575              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
08576   case Expr::MLV_DuplicateVectorComponents:
08577     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
08578     break;
08579   case Expr::MLV_NoSetterProperty:
08580     llvm_unreachable("readonly properties should be processed differently");
08581   case Expr::MLV_InvalidMessageExpression:
08582     Diag = diag::error_readonly_message_assignment;
08583     break;
08584   case Expr::MLV_SubObjCPropertySetting:
08585     Diag = diag::error_no_subobject_property_setting;
08586     break;
08587   }
08588 
08589   SourceRange Assign;
08590   if (Loc != OrigLoc)
08591     Assign = SourceRange(OrigLoc, OrigLoc);
08592   if (NeedType)
08593     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
08594   else
08595     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
08596   return true;
08597 }
08598 
08599 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
08600                                          SourceLocation Loc,
08601                                          Sema &Sema) {
08602   // C / C++ fields
08603   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
08604   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
08605   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
08606     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
08607       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
08608   }
08609 
08610   // Objective-C instance variables
08611   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
08612   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
08613   if (OL && OR && OL->getDecl() == OR->getDecl()) {
08614     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
08615     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
08616     if (RL && RR && RL->getDecl() == RR->getDecl())
08617       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
08618   }
08619 }
08620 
08621 // C99 6.5.16.1
08622 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
08623                                        SourceLocation Loc,
08624                                        QualType CompoundType) {
08625   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
08626 
08627   if (!getLangOpts().CPlusPlus) {
08628     // C cannot handle TypoExpr nodes on either side of n assignment because it
08629     // doesn't handle dependent types properly, so make sure any TypoExprs have
08630     // been dealt with before checking the operands.
08631     ExprResult Res = CorrectDelayedTyposInExpr(LHSExpr);
08632     Expr *NewLHS = Res.isInvalid() ? LHSExpr : Res.get();
08633     Res = CorrectDelayedTyposInExpr(RHS);
08634     if (!Res.isInvalid() && (Res.get() != RHS.get() || NewLHS != LHSExpr))
08635       return CheckAssignmentOperands(NewLHS, Res, Loc, CompoundType);
08636   }
08637 
08638   // Verify that LHS is a modifiable lvalue, and emit error if not.
08639   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
08640     return QualType();
08641 
08642   QualType LHSType = LHSExpr->getType();
08643   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
08644                                              CompoundType;
08645   AssignConvertType ConvTy;
08646   if (CompoundType.isNull()) {
08647     Expr *RHSCheck = RHS.get();
08648 
08649     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
08650 
08651     QualType LHSTy(LHSType);
08652     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
08653     if (RHS.isInvalid())
08654       return QualType();
08655     // Special case of NSObject attributes on c-style pointer types.
08656     if (ConvTy == IncompatiblePointer &&
08657         ((Context.isObjCNSObjectType(LHSType) &&
08658           RHSType->isObjCObjectPointerType()) ||
08659          (Context.isObjCNSObjectType(RHSType) &&
08660           LHSType->isObjCObjectPointerType())))
08661       ConvTy = Compatible;
08662 
08663     if (ConvTy == Compatible &&
08664         LHSType->isObjCObjectType())
08665         Diag(Loc, diag::err_objc_object_assignment)
08666           << LHSType;
08667 
08668     // If the RHS is a unary plus or minus, check to see if they = and + are
08669     // right next to each other.  If so, the user may have typo'd "x =+ 4"
08670     // instead of "x += 4".
08671     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
08672       RHSCheck = ICE->getSubExpr();
08673     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
08674       if ((UO->getOpcode() == UO_Plus ||
08675            UO->getOpcode() == UO_Minus) &&
08676           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
08677           // Only if the two operators are exactly adjacent.
08678           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
08679           // And there is a space or other character before the subexpr of the
08680           // unary +/-.  We don't want to warn on "x=-1".
08681           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
08682           UO->getSubExpr()->getLocStart().isFileID()) {
08683         Diag(Loc, diag::warn_not_compound_assign)
08684           << (UO->getOpcode() == UO_Plus ? "+" : "-")
08685           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
08686       }
08687     }
08688 
08689     if (ConvTy == Compatible) {
08690       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
08691         // Warn about retain cycles where a block captures the LHS, but
08692         // not if the LHS is a simple variable into which the block is
08693         // being stored...unless that variable can be captured by reference!
08694         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
08695         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
08696         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
08697           checkRetainCycles(LHSExpr, RHS.get());
08698 
08699         // It is safe to assign a weak reference into a strong variable.
08700         // Although this code can still have problems:
08701         //   id x = self.weakProp;
08702         //   id y = self.weakProp;
08703         // we do not warn to warn spuriously when 'x' and 'y' are on separate
08704         // paths through the function. This should be revisited if
08705         // -Wrepeated-use-of-weak is made flow-sensitive.
08706         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
08707                              RHS.get()->getLocStart()))
08708           getCurFunction()->markSafeWeakUse(RHS.get());
08709 
08710       } else if (getLangOpts().ObjCAutoRefCount) {
08711         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
08712       }
08713     }
08714   } else {
08715     // Compound assignment "x += y"
08716     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
08717   }
08718 
08719   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
08720                                RHS.get(), AA_Assigning))
08721     return QualType();
08722 
08723   CheckForNullPointerDereference(*this, LHSExpr);
08724 
08725   // C99 6.5.16p3: The type of an assignment expression is the type of the
08726   // left operand unless the left operand has qualified type, in which case
08727   // it is the unqualified version of the type of the left operand.
08728   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
08729   // is converted to the type of the assignment expression (above).
08730   // C++ 5.17p1: the type of the assignment expression is that of its left
08731   // operand.
08732   return (getLangOpts().CPlusPlus
08733           ? LHSType : LHSType.getUnqualifiedType());
08734 }
08735 
08736 // C99 6.5.17
08737 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
08738                                    SourceLocation Loc) {
08739   LHS = S.CheckPlaceholderExpr(LHS.get());
08740   RHS = S.CheckPlaceholderExpr(RHS.get());
08741   if (LHS.isInvalid() || RHS.isInvalid())
08742     return QualType();
08743 
08744   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
08745   // operands, but not unary promotions.
08746   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
08747 
08748   // So we treat the LHS as a ignored value, and in C++ we allow the
08749   // containing site to determine what should be done with the RHS.
08750   LHS = S.IgnoredValueConversions(LHS.get());
08751   if (LHS.isInvalid())
08752     return QualType();
08753 
08754   S.DiagnoseUnusedExprResult(LHS.get());
08755 
08756   if (!S.getLangOpts().CPlusPlus) {
08757     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
08758     if (RHS.isInvalid())
08759       return QualType();
08760     if (!RHS.get()->getType()->isVoidType())
08761       S.RequireCompleteType(Loc, RHS.get()->getType(),
08762                             diag::err_incomplete_type);
08763   }
08764 
08765   return RHS.get()->getType();
08766 }
08767 
08768 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
08769 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
08770 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
08771                                                ExprValueKind &VK,
08772                                                ExprObjectKind &OK,
08773                                                SourceLocation OpLoc,
08774                                                bool IsInc, bool IsPrefix) {
08775   if (Op->isTypeDependent())
08776     return S.Context.DependentTy;
08777 
08778   QualType ResType = Op->getType();
08779   // Atomic types can be used for increment / decrement where the non-atomic
08780   // versions can, so ignore the _Atomic() specifier for the purpose of
08781   // checking.
08782   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
08783     ResType = ResAtomicType->getValueType();
08784 
08785   assert(!ResType.isNull() && "no type for increment/decrement expression");
08786 
08787   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
08788     // Decrement of bool is not allowed.
08789     if (!IsInc) {
08790       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
08791       return QualType();
08792     }
08793     // Increment of bool sets it to true, but is deprecated.
08794     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
08795   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
08796     // Error on enum increments and decrements in C++ mode
08797     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
08798     return QualType();
08799   } else if (ResType->isRealType()) {
08800     // OK!
08801   } else if (ResType->isPointerType()) {
08802     // C99 6.5.2.4p2, 6.5.6p2
08803     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
08804       return QualType();
08805   } else if (ResType->isObjCObjectPointerType()) {
08806     // On modern runtimes, ObjC pointer arithmetic is forbidden.
08807     // Otherwise, we just need a complete type.
08808     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
08809         checkArithmeticOnObjCPointer(S, OpLoc, Op))
08810       return QualType();    
08811   } else if (ResType->isAnyComplexType()) {
08812     // C99 does not support ++/-- on complex types, we allow as an extension.
08813     S.Diag(OpLoc, diag::ext_integer_increment_complex)
08814       << ResType << Op->getSourceRange();
08815   } else if (ResType->isPlaceholderType()) {
08816     ExprResult PR = S.CheckPlaceholderExpr(Op);
08817     if (PR.isInvalid()) return QualType();
08818     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
08819                                           IsInc, IsPrefix);
08820   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
08821     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
08822   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
08823             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
08824     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
08825   } else {
08826     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
08827       << ResType << int(IsInc) << Op->getSourceRange();
08828     return QualType();
08829   }
08830   // At this point, we know we have a real, complex or pointer type.
08831   // Now make sure the operand is a modifiable lvalue.
08832   if (CheckForModifiableLvalue(Op, OpLoc, S))
08833     return QualType();
08834   // In C++, a prefix increment is the same type as the operand. Otherwise
08835   // (in C or with postfix), the increment is the unqualified type of the
08836   // operand.
08837   if (IsPrefix && S.getLangOpts().CPlusPlus) {
08838     VK = VK_LValue;
08839     OK = Op->getObjectKind();
08840     return ResType;
08841   } else {
08842     VK = VK_RValue;
08843     return ResType.getUnqualifiedType();
08844   }
08845 }
08846   
08847 
08848 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
08849 /// This routine allows us to typecheck complex/recursive expressions
08850 /// where the declaration is needed for type checking. We only need to
08851 /// handle cases when the expression references a function designator
08852 /// or is an lvalue. Here are some examples:
08853 ///  - &(x) => x
08854 ///  - &*****f => f for f a function designator.
08855 ///  - &s.xx => s
08856 ///  - &s.zz[1].yy -> s, if zz is an array
08857 ///  - *(x + 1) -> x, if x is an array
08858 ///  - &"123"[2] -> 0
08859 ///  - & __real__ x -> x
08860 static ValueDecl *getPrimaryDecl(Expr *E) {
08861   switch (E->getStmtClass()) {
08862   case Stmt::DeclRefExprClass:
08863     return cast<DeclRefExpr>(E)->getDecl();
08864   case Stmt::MemberExprClass:
08865     // If this is an arrow operator, the address is an offset from
08866     // the base's value, so the object the base refers to is
08867     // irrelevant.
08868     if (cast<MemberExpr>(E)->isArrow())
08869       return nullptr;
08870     // Otherwise, the expression refers to a part of the base
08871     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
08872   case Stmt::ArraySubscriptExprClass: {
08873     // FIXME: This code shouldn't be necessary!  We should catch the implicit
08874     // promotion of register arrays earlier.
08875     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
08876     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
08877       if (ICE->getSubExpr()->getType()->isArrayType())
08878         return getPrimaryDecl(ICE->getSubExpr());
08879     }
08880     return nullptr;
08881   }
08882   case Stmt::UnaryOperatorClass: {
08883     UnaryOperator *UO = cast<UnaryOperator>(E);
08884 
08885     switch(UO->getOpcode()) {
08886     case UO_Real:
08887     case UO_Imag:
08888     case UO_Extension:
08889       return getPrimaryDecl(UO->getSubExpr());
08890     default:
08891       return nullptr;
08892     }
08893   }
08894   case Stmt::ParenExprClass:
08895     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
08896   case Stmt::ImplicitCastExprClass:
08897     // If the result of an implicit cast is an l-value, we care about
08898     // the sub-expression; otherwise, the result here doesn't matter.
08899     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
08900   default:
08901     return nullptr;
08902   }
08903 }
08904 
08905 namespace {
08906   enum {
08907     AO_Bit_Field = 0,
08908     AO_Vector_Element = 1,
08909     AO_Property_Expansion = 2,
08910     AO_Register_Variable = 3,
08911     AO_No_Error = 4
08912   };
08913 }
08914 /// \brief Diagnose invalid operand for address of operations.
08915 ///
08916 /// \param Type The type of operand which cannot have its address taken.
08917 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
08918                                          Expr *E, unsigned Type) {
08919   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
08920 }
08921 
08922 /// CheckAddressOfOperand - The operand of & must be either a function
08923 /// designator or an lvalue designating an object. If it is an lvalue, the
08924 /// object cannot be declared with storage class register or be a bit field.
08925 /// Note: The usual conversions are *not* applied to the operand of the &
08926 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
08927 /// In C++, the operand might be an overloaded function name, in which case
08928 /// we allow the '&' but retain the overloaded-function type.
08929 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
08930   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
08931     if (PTy->getKind() == BuiltinType::Overload) {
08932       Expr *E = OrigOp.get()->IgnoreParens();
08933       if (!isa<OverloadExpr>(E)) {
08934         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
08935         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
08936           << OrigOp.get()->getSourceRange();
08937         return QualType();
08938       }
08939 
08940       OverloadExpr *Ovl = cast<OverloadExpr>(E);
08941       if (isa<UnresolvedMemberExpr>(Ovl))
08942         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
08943           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
08944             << OrigOp.get()->getSourceRange();
08945           return QualType();
08946         }
08947 
08948       return Context.OverloadTy;
08949     }
08950 
08951     if (PTy->getKind() == BuiltinType::UnknownAny)
08952       return Context.UnknownAnyTy;
08953 
08954     if (PTy->getKind() == BuiltinType::BoundMember) {
08955       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
08956         << OrigOp.get()->getSourceRange();
08957       return QualType();
08958     }
08959 
08960     OrigOp = CheckPlaceholderExpr(OrigOp.get());
08961     if (OrigOp.isInvalid()) return QualType();
08962   }
08963 
08964   if (OrigOp.get()->isTypeDependent())
08965     return Context.DependentTy;
08966 
08967   assert(!OrigOp.get()->getType()->isPlaceholderType());
08968 
08969   // Make sure to ignore parentheses in subsequent checks
08970   Expr *op = OrigOp.get()->IgnoreParens();
08971 
08972   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
08973   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
08974     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
08975     return QualType();
08976   }
08977 
08978   if (getLangOpts().C99) {
08979     // Implement C99-only parts of addressof rules.
08980     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
08981       if (uOp->getOpcode() == UO_Deref)
08982         // Per C99 6.5.3.2, the address of a deref always returns a valid result
08983         // (assuming the deref expression is valid).
08984         return uOp->getSubExpr()->getType();
08985     }
08986     // Technically, there should be a check for array subscript
08987     // expressions here, but the result of one is always an lvalue anyway.
08988   }
08989   ValueDecl *dcl = getPrimaryDecl(op);
08990   Expr::LValueClassification lval = op->ClassifyLValue(Context);
08991   unsigned AddressOfError = AO_No_Error;
08992 
08993   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
08994     bool sfinae = (bool)isSFINAEContext();
08995     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
08996                                   : diag::ext_typecheck_addrof_temporary)
08997       << op->getType() << op->getSourceRange();
08998     if (sfinae)
08999       return QualType();
09000     // Materialize the temporary as an lvalue so that we can take its address.
09001     OrigOp = op = new (Context)
09002         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
09003   } else if (isa<ObjCSelectorExpr>(op)) {
09004     return Context.getPointerType(op->getType());
09005   } else if (lval == Expr::LV_MemberFunction) {
09006     // If it's an instance method, make a member pointer.
09007     // The expression must have exactly the form &A::foo.
09008 
09009     // If the underlying expression isn't a decl ref, give up.
09010     if (!isa<DeclRefExpr>(op)) {
09011       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
09012         << OrigOp.get()->getSourceRange();
09013       return QualType();
09014     }
09015     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
09016     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
09017 
09018     // The id-expression was parenthesized.
09019     if (OrigOp.get() != DRE) {
09020       Diag(OpLoc, diag::err_parens_pointer_member_function)
09021         << OrigOp.get()->getSourceRange();
09022 
09023     // The method was named without a qualifier.
09024     } else if (!DRE->getQualifier()) {
09025       if (MD->getParent()->getName().empty())
09026         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
09027           << op->getSourceRange();
09028       else {
09029         SmallString<32> Str;
09030         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
09031         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
09032           << op->getSourceRange()
09033           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
09034       }
09035     }
09036 
09037     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
09038     if (isa<CXXDestructorDecl>(MD))
09039       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
09040 
09041     QualType MPTy = Context.getMemberPointerType(
09042         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
09043     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
09044       RequireCompleteType(OpLoc, MPTy, 0);
09045     return MPTy;
09046   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
09047     // C99 6.5.3.2p1
09048     // The operand must be either an l-value or a function designator
09049     if (!op->getType()->isFunctionType()) {
09050       // Use a special diagnostic for loads from property references.
09051       if (isa<PseudoObjectExpr>(op)) {
09052         AddressOfError = AO_Property_Expansion;
09053       } else {
09054         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
09055           << op->getType() << op->getSourceRange();
09056         return QualType();
09057       }
09058     }
09059   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
09060     // The operand cannot be a bit-field
09061     AddressOfError = AO_Bit_Field;
09062   } else if (op->getObjectKind() == OK_VectorComponent) {
09063     // The operand cannot be an element of a vector
09064     AddressOfError = AO_Vector_Element;
09065   } else if (dcl) { // C99 6.5.3.2p1
09066     // We have an lvalue with a decl. Make sure the decl is not declared
09067     // with the register storage-class specifier.
09068     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
09069       // in C++ it is not error to take address of a register
09070       // variable (c++03 7.1.1P3)
09071       if (vd->getStorageClass() == SC_Register &&
09072           !getLangOpts().CPlusPlus) {
09073         AddressOfError = AO_Register_Variable;
09074       }
09075     } else if (isa<FunctionTemplateDecl>(dcl)) {
09076       return Context.OverloadTy;
09077     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
09078       // Okay: we can take the address of a field.
09079       // Could be a pointer to member, though, if there is an explicit
09080       // scope qualifier for the class.
09081       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
09082         DeclContext *Ctx = dcl->getDeclContext();
09083         if (Ctx && Ctx->isRecord()) {
09084           if (dcl->getType()->isReferenceType()) {
09085             Diag(OpLoc,
09086                  diag::err_cannot_form_pointer_to_member_of_reference_type)
09087               << dcl->getDeclName() << dcl->getType();
09088             return QualType();
09089           }
09090 
09091           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
09092             Ctx = Ctx->getParent();
09093 
09094           QualType MPTy = Context.getMemberPointerType(
09095               op->getType(),
09096               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
09097           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
09098             RequireCompleteType(OpLoc, MPTy, 0);
09099           return MPTy;
09100         }
09101       }
09102     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
09103       llvm_unreachable("Unknown/unexpected decl type");
09104   }
09105 
09106   if (AddressOfError != AO_No_Error) {
09107     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
09108     return QualType();
09109   }
09110 
09111   if (lval == Expr::LV_IncompleteVoidType) {
09112     // Taking the address of a void variable is technically illegal, but we
09113     // allow it in cases which are otherwise valid.
09114     // Example: "extern void x; void* y = &x;".
09115     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
09116   }
09117 
09118   // If the operand has type "type", the result has type "pointer to type".
09119   if (op->getType()->isObjCObjectType())
09120     return Context.getObjCObjectPointerType(op->getType());
09121   return Context.getPointerType(op->getType());
09122 }
09123 
09124 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
09125 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
09126                                         SourceLocation OpLoc) {
09127   if (Op->isTypeDependent())
09128     return S.Context.DependentTy;
09129 
09130   ExprResult ConvResult = S.UsualUnaryConversions(Op);
09131   if (ConvResult.isInvalid())
09132     return QualType();
09133   Op = ConvResult.get();
09134   QualType OpTy = Op->getType();
09135   QualType Result;
09136 
09137   if (isa<CXXReinterpretCastExpr>(Op)) {
09138     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
09139     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
09140                                      Op->getSourceRange());
09141   }
09142 
09143   if (const PointerType *PT = OpTy->getAs<PointerType>())
09144     Result = PT->getPointeeType();
09145   else if (const ObjCObjectPointerType *OPT =
09146              OpTy->getAs<ObjCObjectPointerType>())
09147     Result = OPT->getPointeeType();
09148   else {
09149     ExprResult PR = S.CheckPlaceholderExpr(Op);
09150     if (PR.isInvalid()) return QualType();
09151     if (PR.get() != Op)
09152       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
09153   }
09154 
09155   if (Result.isNull()) {
09156     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
09157       << OpTy << Op->getSourceRange();
09158     return QualType();
09159   }
09160 
09161   // Note that per both C89 and C99, indirection is always legal, even if Result
09162   // is an incomplete type or void.  It would be possible to warn about
09163   // dereferencing a void pointer, but it's completely well-defined, and such a
09164   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
09165   // for pointers to 'void' but is fine for any other pointer type:
09166   //
09167   // C++ [expr.unary.op]p1:
09168   //   [...] the expression to which [the unary * operator] is applied shall
09169   //   be a pointer to an object type, or a pointer to a function type
09170   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
09171     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
09172       << OpTy << Op->getSourceRange();
09173 
09174   // Dereferences are usually l-values...
09175   VK = VK_LValue;
09176 
09177   // ...except that certain expressions are never l-values in C.
09178   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
09179     VK = VK_RValue;
09180   
09181   return Result;
09182 }
09183 
09184 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
09185   BinaryOperatorKind Opc;
09186   switch (Kind) {
09187   default: llvm_unreachable("Unknown binop!");
09188   case tok::periodstar:           Opc = BO_PtrMemD; break;
09189   case tok::arrowstar:            Opc = BO_PtrMemI; break;
09190   case tok::star:                 Opc = BO_Mul; break;
09191   case tok::slash:                Opc = BO_Div; break;
09192   case tok::percent:              Opc = BO_Rem; break;
09193   case tok::plus:                 Opc = BO_Add; break;
09194   case tok::minus:                Opc = BO_Sub; break;
09195   case tok::lessless:             Opc = BO_Shl; break;
09196   case tok::greatergreater:       Opc = BO_Shr; break;
09197   case tok::lessequal:            Opc = BO_LE; break;
09198   case tok::less:                 Opc = BO_LT; break;
09199   case tok::greaterequal:         Opc = BO_GE; break;
09200   case tok::greater:              Opc = BO_GT; break;
09201   case tok::exclaimequal:         Opc = BO_NE; break;
09202   case tok::equalequal:           Opc = BO_EQ; break;
09203   case tok::amp:                  Opc = BO_And; break;
09204   case tok::caret:                Opc = BO_Xor; break;
09205   case tok::pipe:                 Opc = BO_Or; break;
09206   case tok::ampamp:               Opc = BO_LAnd; break;
09207   case tok::pipepipe:             Opc = BO_LOr; break;
09208   case tok::equal:                Opc = BO_Assign; break;
09209   case tok::starequal:            Opc = BO_MulAssign; break;
09210   case tok::slashequal:           Opc = BO_DivAssign; break;
09211   case tok::percentequal:         Opc = BO_RemAssign; break;
09212   case tok::plusequal:            Opc = BO_AddAssign; break;
09213   case tok::minusequal:           Opc = BO_SubAssign; break;
09214   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
09215   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
09216   case tok::ampequal:             Opc = BO_AndAssign; break;
09217   case tok::caretequal:           Opc = BO_XorAssign; break;
09218   case tok::pipeequal:            Opc = BO_OrAssign; break;
09219   case tok::comma:                Opc = BO_Comma; break;
09220   }
09221   return Opc;
09222 }
09223 
09224 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
09225   tok::TokenKind Kind) {
09226   UnaryOperatorKind Opc;
09227   switch (Kind) {
09228   default: llvm_unreachable("Unknown unary op!");
09229   case tok::plusplus:     Opc = UO_PreInc; break;
09230   case tok::minusminus:   Opc = UO_PreDec; break;
09231   case tok::amp:          Opc = UO_AddrOf; break;
09232   case tok::star:         Opc = UO_Deref; break;
09233   case tok::plus:         Opc = UO_Plus; break;
09234   case tok::minus:        Opc = UO_Minus; break;
09235   case tok::tilde:        Opc = UO_Not; break;
09236   case tok::exclaim:      Opc = UO_LNot; break;
09237   case tok::kw___real:    Opc = UO_Real; break;
09238   case tok::kw___imag:    Opc = UO_Imag; break;
09239   case tok::kw___extension__: Opc = UO_Extension; break;
09240   }
09241   return Opc;
09242 }
09243 
09244 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
09245 /// This warning is only emitted for builtin assignment operations. It is also
09246 /// suppressed in the event of macro expansions.
09247 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
09248                                    SourceLocation OpLoc) {
09249   if (!S.ActiveTemplateInstantiations.empty())
09250     return;
09251   if (OpLoc.isInvalid() || OpLoc.isMacroID())
09252     return;
09253   LHSExpr = LHSExpr->IgnoreParenImpCasts();
09254   RHSExpr = RHSExpr->IgnoreParenImpCasts();
09255   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
09256   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
09257   if (!LHSDeclRef || !RHSDeclRef ||
09258       LHSDeclRef->getLocation().isMacroID() ||
09259       RHSDeclRef->getLocation().isMacroID())
09260     return;
09261   const ValueDecl *LHSDecl =
09262     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
09263   const ValueDecl *RHSDecl =
09264     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
09265   if (LHSDecl != RHSDecl)
09266     return;
09267   if (LHSDecl->getType().isVolatileQualified())
09268     return;
09269   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
09270     if (RefTy->getPointeeType().isVolatileQualified())
09271       return;
09272 
09273   S.Diag(OpLoc, diag::warn_self_assignment)
09274       << LHSDeclRef->getType()
09275       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
09276 }
09277 
09278 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
09279 /// is usually indicative of introspection within the Objective-C pointer.
09280 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
09281                                           SourceLocation OpLoc) {
09282   if (!S.getLangOpts().ObjC1)
09283     return;
09284 
09285   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
09286   const Expr *LHS = L.get();
09287   const Expr *RHS = R.get();
09288 
09289   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
09290     ObjCPointerExpr = LHS;
09291     OtherExpr = RHS;
09292   }
09293   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
09294     ObjCPointerExpr = RHS;
09295     OtherExpr = LHS;
09296   }
09297 
09298   // This warning is deliberately made very specific to reduce false
09299   // positives with logic that uses '&' for hashing.  This logic mainly
09300   // looks for code trying to introspect into tagged pointers, which
09301   // code should generally never do.
09302   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
09303     unsigned Diag = diag::warn_objc_pointer_masking;
09304     // Determine if we are introspecting the result of performSelectorXXX.
09305     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
09306     // Special case messages to -performSelector and friends, which
09307     // can return non-pointer values boxed in a pointer value.
09308     // Some clients may wish to silence warnings in this subcase.
09309     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
09310       Selector S = ME->getSelector();
09311       StringRef SelArg0 = S.getNameForSlot(0);
09312       if (SelArg0.startswith("performSelector"))
09313         Diag = diag::warn_objc_pointer_masking_performSelector;
09314     }
09315     
09316     S.Diag(OpLoc, Diag)
09317       << ObjCPointerExpr->getSourceRange();
09318   }
09319 }
09320 
09321 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
09322 /// operator @p Opc at location @c TokLoc. This routine only supports
09323 /// built-in operations; ActOnBinOp handles overloaded operators.
09324 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
09325                                     BinaryOperatorKind Opc,
09326                                     Expr *LHSExpr, Expr *RHSExpr) {
09327   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
09328     // The syntax only allows initializer lists on the RHS of assignment,
09329     // so we don't need to worry about accepting invalid code for
09330     // non-assignment operators.
09331     // C++11 5.17p9:
09332     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
09333     //   of x = {} is x = T().
09334     InitializationKind Kind =
09335         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
09336     InitializedEntity Entity =
09337         InitializedEntity::InitializeTemporary(LHSExpr->getType());
09338     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
09339     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
09340     if (Init.isInvalid())
09341       return Init;
09342     RHSExpr = Init.get();
09343   }
09344 
09345   ExprResult LHS = LHSExpr, RHS = RHSExpr;
09346   QualType ResultTy;     // Result type of the binary operator.
09347   // The following two variables are used for compound assignment operators
09348   QualType CompLHSTy;    // Type of LHS after promotions for computation
09349   QualType CompResultTy; // Type of computation result
09350   ExprValueKind VK = VK_RValue;
09351   ExprObjectKind OK = OK_Ordinary;
09352 
09353   switch (Opc) {
09354   case BO_Assign:
09355     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
09356     if (getLangOpts().CPlusPlus &&
09357         LHS.get()->getObjectKind() != OK_ObjCProperty) {
09358       VK = LHS.get()->getValueKind();
09359       OK = LHS.get()->getObjectKind();
09360     }
09361     if (!ResultTy.isNull())
09362       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
09363     break;
09364   case BO_PtrMemD:
09365   case BO_PtrMemI:
09366     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
09367                                             Opc == BO_PtrMemI);
09368     break;
09369   case BO_Mul:
09370   case BO_Div:
09371     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
09372                                            Opc == BO_Div);
09373     break;
09374   case BO_Rem:
09375     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
09376     break;
09377   case BO_Add:
09378     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
09379     break;
09380   case BO_Sub:
09381     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
09382     break;
09383   case BO_Shl:
09384   case BO_Shr:
09385     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
09386     break;
09387   case BO_LE:
09388   case BO_LT:
09389   case BO_GE:
09390   case BO_GT:
09391     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
09392     break;
09393   case BO_EQ:
09394   case BO_NE:
09395     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
09396     break;
09397   case BO_And:
09398     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
09399   case BO_Xor:
09400   case BO_Or:
09401     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
09402     break;
09403   case BO_LAnd:
09404   case BO_LOr:
09405     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
09406     break;
09407   case BO_MulAssign:
09408   case BO_DivAssign:
09409     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
09410                                                Opc == BO_DivAssign);
09411     CompLHSTy = CompResultTy;
09412     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09413       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09414     break;
09415   case BO_RemAssign:
09416     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
09417     CompLHSTy = CompResultTy;
09418     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09419       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09420     break;
09421   case BO_AddAssign:
09422     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
09423     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09424       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09425     break;
09426   case BO_SubAssign:
09427     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
09428     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09429       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09430     break;
09431   case BO_ShlAssign:
09432   case BO_ShrAssign:
09433     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
09434     CompLHSTy = CompResultTy;
09435     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09436       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09437     break;
09438   case BO_AndAssign:
09439   case BO_OrAssign: // fallthrough
09440     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
09441   case BO_XorAssign:
09442     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
09443     CompLHSTy = CompResultTy;
09444     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
09445       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
09446     break;
09447   case BO_Comma:
09448     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
09449     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
09450       VK = RHS.get()->getValueKind();
09451       OK = RHS.get()->getObjectKind();
09452     }
09453     break;
09454   }
09455   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
09456     return ExprError();
09457 
09458   // Check for array bounds violations for both sides of the BinaryOperator
09459   CheckArrayAccess(LHS.get());
09460   CheckArrayAccess(RHS.get());
09461 
09462   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
09463     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
09464                                                  &Context.Idents.get("object_setClass"),
09465                                                  SourceLocation(), LookupOrdinaryName);
09466     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
09467       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
09468       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
09469       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
09470       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
09471       FixItHint::CreateInsertion(RHSLocEnd, ")");
09472     }
09473     else
09474       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
09475   }
09476   else if (const ObjCIvarRefExpr *OIRE =
09477            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
09478     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
09479   
09480   if (CompResultTy.isNull())
09481     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
09482                                         OK, OpLoc, FPFeatures.fp_contract);
09483   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
09484       OK_ObjCProperty) {
09485     VK = VK_LValue;
09486     OK = LHS.get()->getObjectKind();
09487   }
09488   return new (Context) CompoundAssignOperator(
09489       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
09490       OpLoc, FPFeatures.fp_contract);
09491 }
09492 
09493 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
09494 /// operators are mixed in a way that suggests that the programmer forgot that
09495 /// comparison operators have higher precedence. The most typical example of
09496 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
09497 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
09498                                       SourceLocation OpLoc, Expr *LHSExpr,
09499                                       Expr *RHSExpr) {
09500   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
09501   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
09502 
09503   // Check that one of the sides is a comparison operator.
09504   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
09505   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
09506   if (!isLeftComp && !isRightComp)
09507     return;
09508 
09509   // Bitwise operations are sometimes used as eager logical ops.
09510   // Don't diagnose this.
09511   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
09512   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
09513   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
09514     return;
09515 
09516   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
09517                                                    OpLoc)
09518                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
09519   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
09520   SourceRange ParensRange = isLeftComp ?
09521       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
09522     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
09523 
09524   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
09525     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
09526   SuggestParentheses(Self, OpLoc,
09527     Self.PDiag(diag::note_precedence_silence) << OpStr,
09528     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
09529   SuggestParentheses(Self, OpLoc,
09530     Self.PDiag(diag::note_precedence_bitwise_first)
09531       << BinaryOperator::getOpcodeStr(Opc),
09532     ParensRange);
09533 }
09534 
09535 /// \brief It accepts a '&' expr that is inside a '|' one.
09536 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
09537 /// in parentheses.
09538 static void
09539 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
09540                                        BinaryOperator *Bop) {
09541   assert(Bop->getOpcode() == BO_And);
09542   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
09543       << Bop->getSourceRange() << OpLoc;
09544   SuggestParentheses(Self, Bop->getOperatorLoc(),
09545     Self.PDiag(diag::note_precedence_silence)
09546       << Bop->getOpcodeStr(),
09547     Bop->getSourceRange());
09548 }
09549 
09550 /// \brief It accepts a '&&' expr that is inside a '||' one.
09551 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
09552 /// in parentheses.
09553 static void
09554 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
09555                                        BinaryOperator *Bop) {
09556   assert(Bop->getOpcode() == BO_LAnd);
09557   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
09558       << Bop->getSourceRange() << OpLoc;
09559   SuggestParentheses(Self, Bop->getOperatorLoc(),
09560     Self.PDiag(diag::note_precedence_silence)
09561       << Bop->getOpcodeStr(),
09562     Bop->getSourceRange());
09563 }
09564 
09565 /// \brief Returns true if the given expression can be evaluated as a constant
09566 /// 'true'.
09567 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
09568   bool Res;
09569   return !E->isValueDependent() &&
09570          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
09571 }
09572 
09573 /// \brief Returns true if the given expression can be evaluated as a constant
09574 /// 'false'.
09575 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
09576   bool Res;
09577   return !E->isValueDependent() &&
09578          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
09579 }
09580 
09581 /// \brief Look for '&&' in the left hand of a '||' expr.
09582 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
09583                                              Expr *LHSExpr, Expr *RHSExpr) {
09584   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
09585     if (Bop->getOpcode() == BO_LAnd) {
09586       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
09587       if (EvaluatesAsFalse(S, RHSExpr))
09588         return;
09589       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
09590       if (!EvaluatesAsTrue(S, Bop->getLHS()))
09591         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
09592     } else if (Bop->getOpcode() == BO_LOr) {
09593       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
09594         // If it's "a || b && 1 || c" we didn't warn earlier for
09595         // "a || b && 1", but warn now.
09596         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
09597           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
09598       }
09599     }
09600   }
09601 }
09602 
09603 /// \brief Look for '&&' in the right hand of a '||' expr.
09604 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
09605                                              Expr *LHSExpr, Expr *RHSExpr) {
09606   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
09607     if (Bop->getOpcode() == BO_LAnd) {
09608       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
09609       if (EvaluatesAsFalse(S, LHSExpr))
09610         return;
09611       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
09612       if (!EvaluatesAsTrue(S, Bop->getRHS()))
09613         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
09614     }
09615   }
09616 }
09617 
09618 /// \brief Look for '&' in the left or right hand of a '|' expr.
09619 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
09620                                              Expr *OrArg) {
09621   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
09622     if (Bop->getOpcode() == BO_And)
09623       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
09624   }
09625 }
09626 
09627 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
09628                                     Expr *SubExpr, StringRef Shift) {
09629   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
09630     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
09631       StringRef Op = Bop->getOpcodeStr();
09632       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
09633           << Bop->getSourceRange() << OpLoc << Shift << Op;
09634       SuggestParentheses(S, Bop->getOperatorLoc(),
09635           S.PDiag(diag::note_precedence_silence) << Op,
09636           Bop->getSourceRange());
09637     }
09638   }
09639 }
09640 
09641 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
09642                                  Expr *LHSExpr, Expr *RHSExpr) {
09643   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
09644   if (!OCE)
09645     return;
09646 
09647   FunctionDecl *FD = OCE->getDirectCallee();
09648   if (!FD || !FD->isOverloadedOperator())
09649     return;
09650 
09651   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
09652   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
09653     return;
09654 
09655   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
09656       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
09657       << (Kind == OO_LessLess);
09658   SuggestParentheses(S, OCE->getOperatorLoc(),
09659                      S.PDiag(diag::note_precedence_silence)
09660                          << (Kind == OO_LessLess ? "<<" : ">>"),
09661                      OCE->getSourceRange());
09662   SuggestParentheses(S, OpLoc,
09663                      S.PDiag(diag::note_evaluate_comparison_first),
09664                      SourceRange(OCE->getArg(1)->getLocStart(),
09665                                  RHSExpr->getLocEnd()));
09666 }
09667 
09668 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
09669 /// precedence.
09670 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
09671                                     SourceLocation OpLoc, Expr *LHSExpr,
09672                                     Expr *RHSExpr){
09673   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
09674   if (BinaryOperator::isBitwiseOp(Opc))
09675     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
09676 
09677   // Diagnose "arg1 & arg2 | arg3"
09678   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
09679     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
09680     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
09681   }
09682 
09683   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
09684   // We don't warn for 'assert(a || b && "bad")' since this is safe.
09685   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
09686     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
09687     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
09688   }
09689 
09690   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
09691       || Opc == BO_Shr) {
09692     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
09693     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
09694     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
09695   }
09696 
09697   // Warn on overloaded shift operators and comparisons, such as:
09698   // cout << 5 == 4;
09699   if (BinaryOperator::isComparisonOp(Opc))
09700     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
09701 }
09702 
09703 // Binary Operators.  'Tok' is the token for the operator.
09704 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
09705                             tok::TokenKind Kind,
09706                             Expr *LHSExpr, Expr *RHSExpr) {
09707   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
09708   assert(LHSExpr && "ActOnBinOp(): missing left expression");
09709   assert(RHSExpr && "ActOnBinOp(): missing right expression");
09710 
09711   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
09712   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
09713 
09714   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
09715 }
09716 
09717 /// Build an overloaded binary operator expression in the given scope.
09718 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
09719                                        BinaryOperatorKind Opc,
09720                                        Expr *LHS, Expr *RHS) {
09721   // Find all of the overloaded operators visible from this
09722   // point. We perform both an operator-name lookup from the local
09723   // scope and an argument-dependent lookup based on the types of
09724   // the arguments.
09725   UnresolvedSet<16> Functions;
09726   OverloadedOperatorKind OverOp
09727     = BinaryOperator::getOverloadedOperator(Opc);
09728   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
09729     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
09730                                    RHS->getType(), Functions);
09731 
09732   // Build the (potentially-overloaded, potentially-dependent)
09733   // binary operation.
09734   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
09735 }
09736 
09737 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
09738                             BinaryOperatorKind Opc,
09739                             Expr *LHSExpr, Expr *RHSExpr) {
09740   // We want to end up calling one of checkPseudoObjectAssignment
09741   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
09742   // both expressions are overloadable or either is type-dependent),
09743   // or CreateBuiltinBinOp (in any other case).  We also want to get
09744   // any placeholder types out of the way.
09745 
09746   // Handle pseudo-objects in the LHS.
09747   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
09748     // Assignments with a pseudo-object l-value need special analysis.
09749     if (pty->getKind() == BuiltinType::PseudoObject &&
09750         BinaryOperator::isAssignmentOp(Opc))
09751       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
09752 
09753     // Don't resolve overloads if the other type is overloadable.
09754     if (pty->getKind() == BuiltinType::Overload) {
09755       // We can't actually test that if we still have a placeholder,
09756       // though.  Fortunately, none of the exceptions we see in that
09757       // code below are valid when the LHS is an overload set.  Note
09758       // that an overload set can be dependently-typed, but it never
09759       // instantiates to having an overloadable type.
09760       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
09761       if (resolvedRHS.isInvalid()) return ExprError();
09762       RHSExpr = resolvedRHS.get();
09763 
09764       if (RHSExpr->isTypeDependent() ||
09765           RHSExpr->getType()->isOverloadableType())
09766         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09767     }
09768         
09769     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
09770     if (LHS.isInvalid()) return ExprError();
09771     LHSExpr = LHS.get();
09772   }
09773 
09774   // Handle pseudo-objects in the RHS.
09775   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
09776     // An overload in the RHS can potentially be resolved by the type
09777     // being assigned to.
09778     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
09779       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
09780         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09781 
09782       if (LHSExpr->getType()->isOverloadableType())
09783         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09784 
09785       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
09786     }
09787 
09788     // Don't resolve overloads if the other type is overloadable.
09789     if (pty->getKind() == BuiltinType::Overload &&
09790         LHSExpr->getType()->isOverloadableType())
09791       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09792 
09793     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
09794     if (!resolvedRHS.isUsable()) return ExprError();
09795     RHSExpr = resolvedRHS.get();
09796   }
09797 
09798   if (getLangOpts().CPlusPlus) {
09799     // If either expression is type-dependent, always build an
09800     // overloaded op.
09801     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
09802       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09803 
09804     // Otherwise, build an overloaded op if either expression has an
09805     // overloadable type.
09806     if (LHSExpr->getType()->isOverloadableType() ||
09807         RHSExpr->getType()->isOverloadableType())
09808       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
09809   }
09810 
09811   // Build a built-in binary operation.
09812   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
09813 }
09814 
09815 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
09816                                       UnaryOperatorKind Opc,
09817                                       Expr *InputExpr) {
09818   ExprResult Input = InputExpr;
09819   ExprValueKind VK = VK_RValue;
09820   ExprObjectKind OK = OK_Ordinary;
09821   QualType resultType;
09822   switch (Opc) {
09823   case UO_PreInc:
09824   case UO_PreDec:
09825   case UO_PostInc:
09826   case UO_PostDec:
09827     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
09828                                                 OpLoc,
09829                                                 Opc == UO_PreInc ||
09830                                                 Opc == UO_PostInc,
09831                                                 Opc == UO_PreInc ||
09832                                                 Opc == UO_PreDec);
09833     break;
09834   case UO_AddrOf:
09835     resultType = CheckAddressOfOperand(Input, OpLoc);
09836     break;
09837   case UO_Deref: {
09838     Input = DefaultFunctionArrayLvalueConversion(Input.get());
09839     if (Input.isInvalid()) return ExprError();
09840     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
09841     break;
09842   }
09843   case UO_Plus:
09844   case UO_Minus:
09845     Input = UsualUnaryConversions(Input.get());
09846     if (Input.isInvalid()) return ExprError();
09847     resultType = Input.get()->getType();
09848     if (resultType->isDependentType())
09849       break;
09850     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
09851         resultType->isVectorType()) 
09852       break;
09853     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
09854              Opc == UO_Plus &&
09855              resultType->isPointerType())
09856       break;
09857 
09858     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09859       << resultType << Input.get()->getSourceRange());
09860 
09861   case UO_Not: // bitwise complement
09862     Input = UsualUnaryConversions(Input.get());
09863     if (Input.isInvalid())
09864       return ExprError();
09865     resultType = Input.get()->getType();
09866     if (resultType->isDependentType())
09867       break;
09868     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
09869     if (resultType->isComplexType() || resultType->isComplexIntegerType())
09870       // C99 does not support '~' for complex conjugation.
09871       Diag(OpLoc, diag::ext_integer_complement_complex)
09872           << resultType << Input.get()->getSourceRange();
09873     else if (resultType->hasIntegerRepresentation())
09874       break;
09875     else if (resultType->isExtVectorType()) {
09876       if (Context.getLangOpts().OpenCL) {
09877         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
09878         // on vector float types.
09879         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
09880         if (!T->isIntegerType())
09881           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09882                            << resultType << Input.get()->getSourceRange());
09883       }
09884       break;
09885     } else {
09886       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09887                        << resultType << Input.get()->getSourceRange());
09888     }
09889     break;
09890 
09891   case UO_LNot: // logical negation
09892     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
09893     Input = DefaultFunctionArrayLvalueConversion(Input.get());
09894     if (Input.isInvalid()) return ExprError();
09895     resultType = Input.get()->getType();
09896 
09897     // Though we still have to promote half FP to float...
09898     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
09899       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
09900       resultType = Context.FloatTy;
09901     }
09902 
09903     if (resultType->isDependentType())
09904       break;
09905     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
09906       // C99 6.5.3.3p1: ok, fallthrough;
09907       if (Context.getLangOpts().CPlusPlus) {
09908         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
09909         // operand contextually converted to bool.
09910         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
09911                                   ScalarTypeToBooleanCastKind(resultType));
09912       } else if (Context.getLangOpts().OpenCL &&
09913                  Context.getLangOpts().OpenCLVersion < 120) {
09914         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
09915         // operate on scalar float types.
09916         if (!resultType->isIntegerType())
09917           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09918                            << resultType << Input.get()->getSourceRange());
09919       }
09920     } else if (resultType->isExtVectorType()) {
09921       if (Context.getLangOpts().OpenCL &&
09922           Context.getLangOpts().OpenCLVersion < 120) {
09923         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
09924         // operate on vector float types.
09925         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
09926         if (!T->isIntegerType())
09927           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09928                            << resultType << Input.get()->getSourceRange());
09929       }
09930       // Vector logical not returns the signed variant of the operand type.
09931       resultType = GetSignedVectorType(resultType);
09932       break;
09933     } else {
09934       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
09935         << resultType << Input.get()->getSourceRange());
09936     }
09937     
09938     // LNot always has type int. C99 6.5.3.3p5.
09939     // In C++, it's bool. C++ 5.3.1p8
09940     resultType = Context.getLogicalOperationType();
09941     break;
09942   case UO_Real:
09943   case UO_Imag:
09944     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
09945     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
09946     // complex l-values to ordinary l-values and all other values to r-values.
09947     if (Input.isInvalid()) return ExprError();
09948     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
09949       if (Input.get()->getValueKind() != VK_RValue &&
09950           Input.get()->getObjectKind() == OK_Ordinary)
09951         VK = Input.get()->getValueKind();
09952     } else if (!getLangOpts().CPlusPlus) {
09953       // In C, a volatile scalar is read by __imag. In C++, it is not.
09954       Input = DefaultLvalueConversion(Input.get());
09955     }
09956     break;
09957   case UO_Extension:
09958     resultType = Input.get()->getType();
09959     VK = Input.get()->getValueKind();
09960     OK = Input.get()->getObjectKind();
09961     break;
09962   }
09963   if (resultType.isNull() || Input.isInvalid())
09964     return ExprError();
09965 
09966   // Check for array bounds violations in the operand of the UnaryOperator,
09967   // except for the '*' and '&' operators that have to be handled specially
09968   // by CheckArrayAccess (as there are special cases like &array[arraysize]
09969   // that are explicitly defined as valid by the standard).
09970   if (Opc != UO_AddrOf && Opc != UO_Deref)
09971     CheckArrayAccess(Input.get());
09972 
09973   return new (Context)
09974       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
09975 }
09976 
09977 /// \brief Determine whether the given expression is a qualified member
09978 /// access expression, of a form that could be turned into a pointer to member
09979 /// with the address-of operator.
09980 static bool isQualifiedMemberAccess(Expr *E) {
09981   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
09982     if (!DRE->getQualifier())
09983       return false;
09984     
09985     ValueDecl *VD = DRE->getDecl();
09986     if (!VD->isCXXClassMember())
09987       return false;
09988     
09989     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
09990       return true;
09991     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
09992       return Method->isInstance();
09993       
09994     return false;
09995   }
09996   
09997   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
09998     if (!ULE->getQualifier())
09999       return false;
10000     
10001     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10002                                            DEnd = ULE->decls_end();
10003          D != DEnd; ++D) {
10004       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10005         if (Method->isInstance())
10006           return true;
10007       } else {
10008         // Overload set does not contain methods.
10009         break;
10010       }
10011     }
10012     
10013     return false;
10014   }
10015   
10016   return false;
10017 }
10018 
10019 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10020                               UnaryOperatorKind Opc, Expr *Input) {
10021   // First things first: handle placeholders so that the
10022   // overloaded-operator check considers the right type.
10023   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10024     // Increment and decrement of pseudo-object references.
10025     if (pty->getKind() == BuiltinType::PseudoObject &&
10026         UnaryOperator::isIncrementDecrementOp(Opc))
10027       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10028 
10029     // extension is always a builtin operator.
10030     if (Opc == UO_Extension)
10031       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10032 
10033     // & gets special logic for several kinds of placeholder.
10034     // The builtin code knows what to do.
10035     if (Opc == UO_AddrOf &&
10036         (pty->getKind() == BuiltinType::Overload ||
10037          pty->getKind() == BuiltinType::UnknownAny ||
10038          pty->getKind() == BuiltinType::BoundMember))
10039       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10040 
10041     // Anything else needs to be handled now.
10042     ExprResult Result = CheckPlaceholderExpr(Input);
10043     if (Result.isInvalid()) return ExprError();
10044     Input = Result.get();
10045   }
10046 
10047   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10048       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10049       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10050     // Find all of the overloaded operators visible from this
10051     // point. We perform both an operator-name lookup from the local
10052     // scope and an argument-dependent lookup based on the types of
10053     // the arguments.
10054     UnresolvedSet<16> Functions;
10055     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10056     if (S && OverOp != OO_None)
10057       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10058                                    Functions);
10059 
10060     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10061   }
10062 
10063   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10064 }
10065 
10066 // Unary Operators.  'Tok' is the token for the operator.
10067 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10068                               tok::TokenKind Op, Expr *Input) {
10069   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10070 }
10071 
10072 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10073 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10074                                 LabelDecl *TheDecl) {
10075   TheDecl->markUsed(Context);
10076   // Create the AST node.  The address of a label always has type 'void*'.
10077   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10078                                      Context.getPointerType(Context.VoidTy));
10079 }
10080 
10081 /// Given the last statement in a statement-expression, check whether
10082 /// the result is a producing expression (like a call to an
10083 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10084 /// release out of the full-expression.  Otherwise, return null.
10085 /// Cannot fail.
10086 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10087   // Should always be wrapped with one of these.
10088   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10089   if (!cleanups) return nullptr;
10090 
10091   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10092   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10093     return nullptr;
10094 
10095   // Splice out the cast.  This shouldn't modify any interesting
10096   // features of the statement.
10097   Expr *producer = cast->getSubExpr();
10098   assert(producer->getType() == cast->getType());
10099   assert(producer->getValueKind() == cast->getValueKind());
10100   cleanups->setSubExpr(producer);
10101   return cleanups;
10102 }
10103 
10104 void Sema::ActOnStartStmtExpr() {
10105   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10106 }
10107 
10108 void Sema::ActOnStmtExprError() {
10109   // Note that function is also called by TreeTransform when leaving a
10110   // StmtExpr scope without rebuilding anything.
10111 
10112   DiscardCleanupsInEvaluationContext();
10113   PopExpressionEvaluationContext();
10114 }
10115 
10116 ExprResult
10117 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10118                     SourceLocation RPLoc) { // "({..})"
10119   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10120   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10121 
10122   if (hasAnyUnrecoverableErrorsInThisFunction())
10123     DiscardCleanupsInEvaluationContext();
10124   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10125   PopExpressionEvaluationContext();
10126 
10127   bool isFileScope
10128     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10129   if (isFileScope)
10130     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10131 
10132   // FIXME: there are a variety of strange constraints to enforce here, for
10133   // example, it is not possible to goto into a stmt expression apparently.
10134   // More semantic analysis is needed.
10135 
10136   // If there are sub-stmts in the compound stmt, take the type of the last one
10137   // as the type of the stmtexpr.
10138   QualType Ty = Context.VoidTy;
10139   bool StmtExprMayBindToTemp = false;
10140   if (!Compound->body_empty()) {
10141     Stmt *LastStmt = Compound->body_back();
10142     LabelStmt *LastLabelStmt = nullptr;
10143     // If LastStmt is a label, skip down through into the body.
10144     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10145       LastLabelStmt = Label;
10146       LastStmt = Label->getSubStmt();
10147     }
10148 
10149     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10150       // Do function/array conversion on the last expression, but not
10151       // lvalue-to-rvalue.  However, initialize an unqualified type.
10152       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10153       if (LastExpr.isInvalid())
10154         return ExprError();
10155       Ty = LastExpr.get()->getType().getUnqualifiedType();
10156 
10157       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10158         // In ARC, if the final expression ends in a consume, splice
10159         // the consume out and bind it later.  In the alternate case
10160         // (when dealing with a retainable type), the result
10161         // initialization will create a produce.  In both cases the
10162         // result will be +1, and we'll need to balance that out with
10163         // a bind.
10164         if (Expr *rebuiltLastStmt
10165               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10166           LastExpr = rebuiltLastStmt;
10167         } else {
10168           LastExpr = PerformCopyInitialization(
10169                             InitializedEntity::InitializeResult(LPLoc, 
10170                                                                 Ty,
10171                                                                 false),
10172                                                    SourceLocation(),
10173                                                LastExpr);
10174         }
10175 
10176         if (LastExpr.isInvalid())
10177           return ExprError();
10178         if (LastExpr.get() != nullptr) {
10179           if (!LastLabelStmt)
10180             Compound->setLastStmt(LastExpr.get());
10181           else
10182             LastLabelStmt->setSubStmt(LastExpr.get());
10183           StmtExprMayBindToTemp = true;
10184         }
10185       }
10186     }
10187   }
10188 
10189   // FIXME: Check that expression type is complete/non-abstract; statement
10190   // expressions are not lvalues.
10191   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10192   if (StmtExprMayBindToTemp)
10193     return MaybeBindToTemporary(ResStmtExpr);
10194   return ResStmtExpr;
10195 }
10196 
10197 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10198                                       TypeSourceInfo *TInfo,
10199                                       OffsetOfComponent *CompPtr,
10200                                       unsigned NumComponents,
10201                                       SourceLocation RParenLoc) {
10202   QualType ArgTy = TInfo->getType();
10203   bool Dependent = ArgTy->isDependentType();
10204   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10205   
10206   // We must have at least one component that refers to the type, and the first
10207   // one is known to be a field designator.  Verify that the ArgTy represents
10208   // a struct/union/class.
10209   if (!Dependent && !ArgTy->isRecordType())
10210     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
10211                        << ArgTy << TypeRange);
10212   
10213   // Type must be complete per C99 7.17p3 because a declaring a variable
10214   // with an incomplete type would be ill-formed.
10215   if (!Dependent 
10216       && RequireCompleteType(BuiltinLoc, ArgTy,
10217                              diag::err_offsetof_incomplete_type, TypeRange))
10218     return ExprError();
10219   
10220   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10221   // GCC extension, diagnose them.
10222   // FIXME: This diagnostic isn't actually visible because the location is in
10223   // a system header!
10224   if (NumComponents != 1)
10225     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10226       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10227   
10228   bool DidWarnAboutNonPOD = false;
10229   QualType CurrentType = ArgTy;
10230   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10231   SmallVector<OffsetOfNode, 4> Comps;
10232   SmallVector<Expr*, 4> Exprs;
10233   for (unsigned i = 0; i != NumComponents; ++i) {
10234     const OffsetOfComponent &OC = CompPtr[i];
10235     if (OC.isBrackets) {
10236       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10237       if (!CurrentType->isDependentType()) {
10238         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10239         if(!AT)
10240           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10241                            << CurrentType);
10242         CurrentType = AT->getElementType();
10243       } else
10244         CurrentType = Context.DependentTy;
10245       
10246       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10247       if (IdxRval.isInvalid())
10248         return ExprError();
10249       Expr *Idx = IdxRval.get();
10250 
10251       // The expression must be an integral expression.
10252       // FIXME: An integral constant expression?
10253       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10254           !Idx->getType()->isIntegerType())
10255         return ExprError(Diag(Idx->getLocStart(),
10256                               diag::err_typecheck_subscript_not_integer)
10257                          << Idx->getSourceRange());
10258 
10259       // Record this array index.
10260       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10261       Exprs.push_back(Idx);
10262       continue;
10263     }
10264     
10265     // Offset of a field.
10266     if (CurrentType->isDependentType()) {
10267       // We have the offset of a field, but we can't look into the dependent
10268       // type. Just record the identifier of the field.
10269       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10270       CurrentType = Context.DependentTy;
10271       continue;
10272     }
10273     
10274     // We need to have a complete type to look into.
10275     if (RequireCompleteType(OC.LocStart, CurrentType,
10276                             diag::err_offsetof_incomplete_type))
10277       return ExprError();
10278     
10279     // Look for the designated field.
10280     const RecordType *RC = CurrentType->getAs<RecordType>();
10281     if (!RC) 
10282       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10283                        << CurrentType);
10284     RecordDecl *RD = RC->getDecl();
10285     
10286     // C++ [lib.support.types]p5:
10287     //   The macro offsetof accepts a restricted set of type arguments in this
10288     //   International Standard. type shall be a POD structure or a POD union
10289     //   (clause 9).
10290     // C++11 [support.types]p4:
10291     //   If type is not a standard-layout class (Clause 9), the results are
10292     //   undefined.
10293     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10294       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10295       unsigned DiagID =
10296         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10297                             : diag::ext_offsetof_non_pod_type;
10298 
10299       if (!IsSafe && !DidWarnAboutNonPOD &&
10300           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10301                               PDiag(DiagID)
10302                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10303                               << CurrentType))
10304         DidWarnAboutNonPOD = true;
10305     }
10306     
10307     // Look for the field.
10308     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10309     LookupQualifiedName(R, RD);
10310     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10311     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10312     if (!MemberDecl) {
10313       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10314         MemberDecl = IndirectMemberDecl->getAnonField();
10315     }
10316 
10317     if (!MemberDecl)
10318       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10319                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
10320                                                               OC.LocEnd));
10321     
10322     // C99 7.17p3:
10323     //   (If the specified member is a bit-field, the behavior is undefined.)
10324     //
10325     // We diagnose this as an error.
10326     if (MemberDecl->isBitField()) {
10327       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10328         << MemberDecl->getDeclName()
10329         << SourceRange(BuiltinLoc, RParenLoc);
10330       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10331       return ExprError();
10332     }
10333 
10334     RecordDecl *Parent = MemberDecl->getParent();
10335     if (IndirectMemberDecl)
10336       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10337 
10338     // If the member was found in a base class, introduce OffsetOfNodes for
10339     // the base class indirections.
10340     CXXBasePaths Paths;
10341     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10342       if (Paths.getDetectedVirtual()) {
10343         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10344           << MemberDecl->getDeclName()
10345           << SourceRange(BuiltinLoc, RParenLoc);
10346         return ExprError();
10347       }
10348 
10349       CXXBasePath &Path = Paths.front();
10350       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10351            B != BEnd; ++B)
10352         Comps.push_back(OffsetOfNode(B->Base));
10353     }
10354 
10355     if (IndirectMemberDecl) {
10356       for (auto *FI : IndirectMemberDecl->chain()) {
10357         assert(isa<FieldDecl>(FI));
10358         Comps.push_back(OffsetOfNode(OC.LocStart,
10359                                      cast<FieldDecl>(FI), OC.LocEnd));
10360       }
10361     } else
10362       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10363 
10364     CurrentType = MemberDecl->getType().getNonReferenceType(); 
10365   }
10366   
10367   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10368                               Comps, Exprs, RParenLoc);
10369 }
10370 
10371 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10372                                       SourceLocation BuiltinLoc,
10373                                       SourceLocation TypeLoc,
10374                                       ParsedType ParsedArgTy,
10375                                       OffsetOfComponent *CompPtr,
10376                                       unsigned NumComponents,
10377                                       SourceLocation RParenLoc) {
10378   
10379   TypeSourceInfo *ArgTInfo;
10380   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10381   if (ArgTy.isNull())
10382     return ExprError();
10383 
10384   if (!ArgTInfo)
10385     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10386 
10387   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
10388                               RParenLoc);
10389 }
10390 
10391 
10392 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10393                                  Expr *CondExpr,
10394                                  Expr *LHSExpr, Expr *RHSExpr,
10395                                  SourceLocation RPLoc) {
10396   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10397 
10398   ExprValueKind VK = VK_RValue;
10399   ExprObjectKind OK = OK_Ordinary;
10400   QualType resType;
10401   bool ValueDependent = false;
10402   bool CondIsTrue = false;
10403   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10404     resType = Context.DependentTy;
10405     ValueDependent = true;
10406   } else {
10407     // The conditional expression is required to be a constant expression.
10408     llvm::APSInt condEval(32);
10409     ExprResult CondICE
10410       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10411           diag::err_typecheck_choose_expr_requires_constant, false);
10412     if (CondICE.isInvalid())
10413       return ExprError();
10414     CondExpr = CondICE.get();
10415     CondIsTrue = condEval.getZExtValue();
10416 
10417     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10418     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10419 
10420     resType = ActiveExpr->getType();
10421     ValueDependent = ActiveExpr->isValueDependent();
10422     VK = ActiveExpr->getValueKind();
10423     OK = ActiveExpr->getObjectKind();
10424   }
10425 
10426   return new (Context)
10427       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10428                  CondIsTrue, resType->isDependentType(), ValueDependent);
10429 }
10430 
10431 //===----------------------------------------------------------------------===//
10432 // Clang Extensions.
10433 //===----------------------------------------------------------------------===//
10434 
10435 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10436 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10437   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10438 
10439   if (LangOpts.CPlusPlus) {
10440     Decl *ManglingContextDecl;
10441     if (MangleNumberingContext *MCtx =
10442             getCurrentMangleNumberContext(Block->getDeclContext(),
10443                                           ManglingContextDecl)) {
10444       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10445       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10446     }
10447   }
10448 
10449   PushBlockScope(CurScope, Block);
10450   CurContext->addDecl(Block);
10451   if (CurScope)
10452     PushDeclContext(CurScope, Block);
10453   else
10454     CurContext = Block;
10455 
10456   getCurBlock()->HasImplicitReturnType = true;
10457 
10458   // Enter a new evaluation context to insulate the block from any
10459   // cleanups from the enclosing full-expression.
10460   PushExpressionEvaluationContext(PotentiallyEvaluated);  
10461 }
10462 
10463 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10464                                Scope *CurScope) {
10465   assert(ParamInfo.getIdentifier() == nullptr &&
10466          "block-id should have no identifier!");
10467   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10468   BlockScopeInfo *CurBlock = getCurBlock();
10469 
10470   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10471   QualType T = Sig->getType();
10472 
10473   // FIXME: We should allow unexpanded parameter packs here, but that would,
10474   // in turn, make the block expression contain unexpanded parameter packs.
10475   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10476     // Drop the parameters.
10477     FunctionProtoType::ExtProtoInfo EPI;
10478     EPI.HasTrailingReturn = false;
10479     EPI.TypeQuals |= DeclSpec::TQ_const;
10480     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10481     Sig = Context.getTrivialTypeSourceInfo(T);
10482   }
10483   
10484   // GetTypeForDeclarator always produces a function type for a block
10485   // literal signature.  Furthermore, it is always a FunctionProtoType
10486   // unless the function was written with a typedef.
10487   assert(T->isFunctionType() &&
10488          "GetTypeForDeclarator made a non-function block signature");
10489 
10490   // Look for an explicit signature in that function type.
10491   FunctionProtoTypeLoc ExplicitSignature;
10492 
10493   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10494   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10495 
10496     // Check whether that explicit signature was synthesized by
10497     // GetTypeForDeclarator.  If so, don't save that as part of the
10498     // written signature.
10499     if (ExplicitSignature.getLocalRangeBegin() ==
10500         ExplicitSignature.getLocalRangeEnd()) {
10501       // This would be much cheaper if we stored TypeLocs instead of
10502       // TypeSourceInfos.
10503       TypeLoc Result = ExplicitSignature.getReturnLoc();
10504       unsigned Size = Result.getFullDataSize();
10505       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10506       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10507 
10508       ExplicitSignature = FunctionProtoTypeLoc();
10509     }
10510   }
10511 
10512   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10513   CurBlock->FunctionType = T;
10514 
10515   const FunctionType *Fn = T->getAs<FunctionType>();
10516   QualType RetTy = Fn->getReturnType();
10517   bool isVariadic =
10518     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10519 
10520   CurBlock->TheDecl->setIsVariadic(isVariadic);
10521 
10522   // Context.DependentTy is used as a placeholder for a missing block
10523   // return type.  TODO:  what should we do with declarators like:
10524   //   ^ * { ... }
10525   // If the answer is "apply template argument deduction"....
10526   if (RetTy != Context.DependentTy) {
10527     CurBlock->ReturnType = RetTy;
10528     CurBlock->TheDecl->setBlockMissingReturnType(false);
10529     CurBlock->HasImplicitReturnType = false;
10530   }
10531 
10532   // Push block parameters from the declarator if we had them.
10533   SmallVector<ParmVarDecl*, 8> Params;
10534   if (ExplicitSignature) {
10535     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10536       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10537       if (Param->getIdentifier() == nullptr &&
10538           !Param->isImplicit() &&
10539           !Param->isInvalidDecl() &&
10540           !getLangOpts().CPlusPlus)
10541         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10542       Params.push_back(Param);
10543     }
10544 
10545   // Fake up parameter variables if we have a typedef, like
10546   //   ^ fntype { ... }
10547   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10548     for (const auto &I : Fn->param_types()) {
10549       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10550           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10551       Params.push_back(Param);
10552     }
10553   }
10554 
10555   // Set the parameters on the block decl.
10556   if (!Params.empty()) {
10557     CurBlock->TheDecl->setParams(Params);
10558     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10559                              CurBlock->TheDecl->param_end(),
10560                              /*CheckParameterNames=*/false);
10561   }
10562   
10563   // Finally we can process decl attributes.
10564   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10565 
10566   // Put the parameter variables in scope.
10567   for (auto AI : CurBlock->TheDecl->params()) {
10568     AI->setOwningFunction(CurBlock->TheDecl);
10569 
10570     // If this has an identifier, add it to the scope stack.
10571     if (AI->getIdentifier()) {
10572       CheckShadow(CurBlock->TheScope, AI);
10573 
10574       PushOnScopeChains(AI, CurBlock->TheScope);
10575     }
10576   }
10577 }
10578 
10579 /// ActOnBlockError - If there is an error parsing a block, this callback
10580 /// is invoked to pop the information about the block from the action impl.
10581 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10582   // Leave the expression-evaluation context.
10583   DiscardCleanupsInEvaluationContext();
10584   PopExpressionEvaluationContext();
10585 
10586   // Pop off CurBlock, handle nested blocks.
10587   PopDeclContext();
10588   PopFunctionScopeInfo();
10589 }
10590 
10591 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10592 /// literal was successfully completed.  ^(int x){...}
10593 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10594                                     Stmt *Body, Scope *CurScope) {
10595   // If blocks are disabled, emit an error.
10596   if (!LangOpts.Blocks)
10597     Diag(CaretLoc, diag::err_blocks_disable);
10598 
10599   // Leave the expression-evaluation context.
10600   if (hasAnyUnrecoverableErrorsInThisFunction())
10601     DiscardCleanupsInEvaluationContext();
10602   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10603   PopExpressionEvaluationContext();
10604 
10605   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10606 
10607   if (BSI->HasImplicitReturnType)
10608     deduceClosureReturnType(*BSI);
10609 
10610   PopDeclContext();
10611 
10612   QualType RetTy = Context.VoidTy;
10613   if (!BSI->ReturnType.isNull())
10614     RetTy = BSI->ReturnType;
10615 
10616   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10617   QualType BlockTy;
10618 
10619   // Set the captured variables on the block.
10620   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10621   SmallVector<BlockDecl::Capture, 4> Captures;
10622   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10623     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10624     if (Cap.isThisCapture())
10625       continue;
10626     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10627                               Cap.isNested(), Cap.getInitExpr());
10628     Captures.push_back(NewCap);
10629   }
10630   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10631                             BSI->CXXThisCaptureIndex != 0);
10632 
10633   // If the user wrote a function type in some form, try to use that.
10634   if (!BSI->FunctionType.isNull()) {
10635     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10636 
10637     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10638     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10639     
10640     // Turn protoless block types into nullary block types.
10641     if (isa<FunctionNoProtoType>(FTy)) {
10642       FunctionProtoType::ExtProtoInfo EPI;
10643       EPI.ExtInfo = Ext;
10644       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10645 
10646     // Otherwise, if we don't need to change anything about the function type,
10647     // preserve its sugar structure.
10648     } else if (FTy->getReturnType() == RetTy &&
10649                (!NoReturn || FTy->getNoReturnAttr())) {
10650       BlockTy = BSI->FunctionType;
10651 
10652     // Otherwise, make the minimal modifications to the function type.
10653     } else {
10654       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10655       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10656       EPI.TypeQuals = 0; // FIXME: silently?
10657       EPI.ExtInfo = Ext;
10658       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10659     }
10660 
10661   // If we don't have a function type, just build one from nothing.
10662   } else {
10663     FunctionProtoType::ExtProtoInfo EPI;
10664     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10665     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10666   }
10667 
10668   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10669                            BSI->TheDecl->param_end());
10670   BlockTy = Context.getBlockPointerType(BlockTy);
10671 
10672   // If needed, diagnose invalid gotos and switches in the block.
10673   if (getCurFunction()->NeedsScopeChecking() &&
10674       !PP.isCodeCompletionEnabled())
10675     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10676 
10677   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10678 
10679   // Try to apply the named return value optimization. We have to check again
10680   // if we can do this, though, because blocks keep return statements around
10681   // to deduce an implicit return type.
10682   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10683       !BSI->TheDecl->isDependentContext())
10684     computeNRVO(Body, BSI);
10685   
10686   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10687   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10688   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10689 
10690   // If the block isn't obviously global, i.e. it captures anything at
10691   // all, then we need to do a few things in the surrounding context:
10692   if (Result->getBlockDecl()->hasCaptures()) {
10693     // First, this expression has a new cleanup object.
10694     ExprCleanupObjects.push_back(Result->getBlockDecl());
10695     ExprNeedsCleanups = true;
10696 
10697     // It also gets a branch-protected scope if any of the captured
10698     // variables needs destruction.
10699     for (const auto &CI : Result->getBlockDecl()->captures()) {
10700       const VarDecl *var = CI.getVariable();
10701       if (var->getType().isDestructedType() != QualType::DK_none) {
10702         getCurFunction()->setHasBranchProtectedScope();
10703         break;
10704       }
10705     }
10706   }
10707 
10708   return Result;
10709 }
10710 
10711 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10712                                         Expr *E, ParsedType Ty,
10713                                         SourceLocation RPLoc) {
10714   TypeSourceInfo *TInfo;
10715   GetTypeFromParser(Ty, &TInfo);
10716   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10717 }
10718 
10719 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10720                                 Expr *E, TypeSourceInfo *TInfo,
10721                                 SourceLocation RPLoc) {
10722   Expr *OrigExpr = E;
10723 
10724   // Get the va_list type
10725   QualType VaListType = Context.getBuiltinVaListType();
10726   if (VaListType->isArrayType()) {
10727     // Deal with implicit array decay; for example, on x86-64,
10728     // va_list is an array, but it's supposed to decay to
10729     // a pointer for va_arg.
10730     VaListType = Context.getArrayDecayedType(VaListType);
10731     // Make sure the input expression also decays appropriately.
10732     ExprResult Result = UsualUnaryConversions(E);
10733     if (Result.isInvalid())
10734       return ExprError();
10735     E = Result.get();
10736   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10737     // If va_list is a record type and we are compiling in C++ mode,
10738     // check the argument using reference binding.
10739     InitializedEntity Entity
10740       = InitializedEntity::InitializeParameter(Context,
10741           Context.getLValueReferenceType(VaListType), false);
10742     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10743     if (Init.isInvalid())
10744       return ExprError();
10745     E = Init.getAs<Expr>();
10746   } else {
10747     // Otherwise, the va_list argument must be an l-value because
10748     // it is modified by va_arg.
10749     if (!E->isTypeDependent() &&
10750         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10751       return ExprError();
10752   }
10753 
10754   if (!E->isTypeDependent() &&
10755       !Context.hasSameType(VaListType, E->getType())) {
10756     return ExprError(Diag(E->getLocStart(),
10757                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10758       << OrigExpr->getType() << E->getSourceRange());
10759   }
10760 
10761   if (!TInfo->getType()->isDependentType()) {
10762     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10763                             diag::err_second_parameter_to_va_arg_incomplete,
10764                             TInfo->getTypeLoc()))
10765       return ExprError();
10766 
10767     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10768                                TInfo->getType(),
10769                                diag::err_second_parameter_to_va_arg_abstract,
10770                                TInfo->getTypeLoc()))
10771       return ExprError();
10772 
10773     if (!TInfo->getType().isPODType(Context)) {
10774       Diag(TInfo->getTypeLoc().getBeginLoc(),
10775            TInfo->getType()->isObjCLifetimeType()
10776              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10777              : diag::warn_second_parameter_to_va_arg_not_pod)
10778         << TInfo->getType()
10779         << TInfo->getTypeLoc().getSourceRange();
10780     }
10781 
10782     // Check for va_arg where arguments of the given type will be promoted
10783     // (i.e. this va_arg is guaranteed to have undefined behavior).
10784     QualType PromoteType;
10785     if (TInfo->getType()->isPromotableIntegerType()) {
10786       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10787       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10788         PromoteType = QualType();
10789     }
10790     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10791       PromoteType = Context.DoubleTy;
10792     if (!PromoteType.isNull())
10793       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10794                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10795                           << TInfo->getType()
10796                           << PromoteType
10797                           << TInfo->getTypeLoc().getSourceRange());
10798   }
10799 
10800   QualType T = TInfo->getType().getNonLValueExprType(Context);
10801   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10802 }
10803 
10804 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10805   // The type of __null will be int or long, depending on the size of
10806   // pointers on the target.
10807   QualType Ty;
10808   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10809   if (pw == Context.getTargetInfo().getIntWidth())
10810     Ty = Context.IntTy;
10811   else if (pw == Context.getTargetInfo().getLongWidth())
10812     Ty = Context.LongTy;
10813   else if (pw == Context.getTargetInfo().getLongLongWidth())
10814     Ty = Context.LongLongTy;
10815   else {
10816     llvm_unreachable("I don't know size of pointer!");
10817   }
10818 
10819   return new (Context) GNUNullExpr(Ty, TokenLoc);
10820 }
10821 
10822 bool
10823 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10824   if (!getLangOpts().ObjC1)
10825     return false;
10826 
10827   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10828   if (!PT)
10829     return false;
10830 
10831   if (!PT->isObjCIdType()) {
10832     // Check if the destination is the 'NSString' interface.
10833     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10834     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10835       return false;
10836   }
10837   
10838   // Ignore any parens, implicit casts (should only be
10839   // array-to-pointer decays), and not-so-opaque values.  The last is
10840   // important for making this trigger for property assignments.
10841   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10842   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10843     if (OV->getSourceExpr())
10844       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10845 
10846   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10847   if (!SL || !SL->isAscii())
10848     return false;
10849   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10850     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10851   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10852   return true;
10853 }
10854 
10855 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10856                                     SourceLocation Loc,
10857                                     QualType DstType, QualType SrcType,
10858                                     Expr *SrcExpr, AssignmentAction Action,
10859                                     bool *Complained) {
10860   if (Complained)
10861     *Complained = false;
10862 
10863   // Decode the result (notice that AST's are still created for extensions).
10864   bool CheckInferredResultType = false;
10865   bool isInvalid = false;
10866   unsigned DiagKind = 0;
10867   FixItHint Hint;
10868   ConversionFixItGenerator ConvHints;
10869   bool MayHaveConvFixit = false;
10870   bool MayHaveFunctionDiff = false;
10871   const ObjCInterfaceDecl *IFace = nullptr;
10872   const ObjCProtocolDecl *PDecl = nullptr;
10873 
10874   switch (ConvTy) {
10875   case Compatible:
10876       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10877       return false;
10878 
10879   case PointerToInt:
10880     DiagKind = diag::ext_typecheck_convert_pointer_int;
10881     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10882     MayHaveConvFixit = true;
10883     break;
10884   case IntToPointer:
10885     DiagKind = diag::ext_typecheck_convert_int_pointer;
10886     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10887     MayHaveConvFixit = true;
10888     break;
10889   case IncompatiblePointer:
10890       DiagKind =
10891         (Action == AA_Passing_CFAudited ?
10892           diag::err_arc_typecheck_convert_incompatible_pointer :
10893           diag::ext_typecheck_convert_incompatible_pointer);
10894     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10895       SrcType->isObjCObjectPointerType();
10896     if (Hint.isNull() && !CheckInferredResultType) {
10897       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10898     }
10899     else if (CheckInferredResultType) {
10900       SrcType = SrcType.getUnqualifiedType();
10901       DstType = DstType.getUnqualifiedType();
10902     }
10903     MayHaveConvFixit = true;
10904     break;
10905   case IncompatiblePointerSign:
10906     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10907     break;
10908   case FunctionVoidPointer:
10909     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10910     break;
10911   case IncompatiblePointerDiscardsQualifiers: {
10912     // Perform array-to-pointer decay if necessary.
10913     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10914 
10915     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10916     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10917     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10918       DiagKind = diag::err_typecheck_incompatible_address_space;
10919       break;
10920 
10921 
10922     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10923       DiagKind = diag::err_typecheck_incompatible_ownership;
10924       break;
10925     }
10926 
10927     llvm_unreachable("unknown error case for discarding qualifiers!");
10928     // fallthrough
10929   }
10930   case CompatiblePointerDiscardsQualifiers:
10931     // If the qualifiers lost were because we were applying the
10932     // (deprecated) C++ conversion from a string literal to a char*
10933     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10934     // Ideally, this check would be performed in
10935     // checkPointerTypesForAssignment. However, that would require a
10936     // bit of refactoring (so that the second argument is an
10937     // expression, rather than a type), which should be done as part
10938     // of a larger effort to fix checkPointerTypesForAssignment for
10939     // C++ semantics.
10940     if (getLangOpts().CPlusPlus &&
10941         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10942       return false;
10943     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10944     break;
10945   case IncompatibleNestedPointerQualifiers:
10946     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10947     break;
10948   case IntToBlockPointer:
10949     DiagKind = diag::err_int_to_block_pointer;
10950     break;
10951   case IncompatibleBlockPointer:
10952     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10953     break;
10954   case IncompatibleObjCQualifiedId: {
10955     if (SrcType->isObjCQualifiedIdType()) {
10956       const ObjCObjectPointerType *srcOPT =
10957                 SrcType->getAs<ObjCObjectPointerType>();
10958       for (auto *srcProto : srcOPT->quals()) {
10959         PDecl = srcProto;
10960         break;
10961       }
10962       if (const ObjCInterfaceType *IFaceT =
10963             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10964         IFace = IFaceT->getDecl();
10965     }
10966     else if (DstType->isObjCQualifiedIdType()) {
10967       const ObjCObjectPointerType *dstOPT =
10968         DstType->getAs<ObjCObjectPointerType>();
10969       for (auto *dstProto : dstOPT->quals()) {
10970         PDecl = dstProto;
10971         break;
10972       }
10973       if (const ObjCInterfaceType *IFaceT =
10974             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10975         IFace = IFaceT->getDecl();
10976     }
10977     DiagKind = diag::warn_incompatible_qualified_id;
10978     break;
10979   }
10980   case IncompatibleVectors:
10981     DiagKind = diag::warn_incompatible_vectors;
10982     break;
10983   case IncompatibleObjCWeakRef:
10984     DiagKind = diag::err_arc_weak_unavailable_assign;
10985     break;
10986   case Incompatible:
10987     DiagKind = diag::err_typecheck_convert_incompatible;
10988     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10989     MayHaveConvFixit = true;
10990     isInvalid = true;
10991     MayHaveFunctionDiff = true;
10992     break;
10993   }
10994 
10995   QualType FirstType, SecondType;
10996   switch (Action) {
10997   case AA_Assigning:
10998   case AA_Initializing:
10999     // The destination type comes first.
11000     FirstType = DstType;
11001     SecondType = SrcType;
11002     break;
11003 
11004   case AA_Returning:
11005   case AA_Passing:
11006   case AA_Passing_CFAudited:
11007   case AA_Converting:
11008   case AA_Sending:
11009   case AA_Casting:
11010     // The source type comes first.
11011     FirstType = SrcType;
11012     SecondType = DstType;
11013     break;
11014   }
11015 
11016   PartialDiagnostic FDiag = PDiag(DiagKind);
11017   if (Action == AA_Passing_CFAudited)
11018     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11019   else
11020     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11021 
11022   // If we can fix the conversion, suggest the FixIts.
11023   assert(ConvHints.isNull() || Hint.isNull());
11024   if (!ConvHints.isNull()) {
11025     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11026          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11027       FDiag << *HI;
11028   } else {
11029     FDiag << Hint;
11030   }
11031   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11032 
11033   if (MayHaveFunctionDiff)
11034     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11035 
11036   Diag(Loc, FDiag);
11037   if (DiagKind == diag::warn_incompatible_qualified_id &&
11038       PDecl && IFace && !IFace->hasDefinition())
11039       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11040         << IFace->getName() << PDecl->getName();
11041     
11042   if (SecondType == Context.OverloadTy)
11043     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11044                               FirstType);
11045 
11046   if (CheckInferredResultType)
11047     EmitRelatedResultTypeNote(SrcExpr);
11048 
11049   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11050     EmitRelatedResultTypeNoteForReturn(DstType);
11051   
11052   if (Complained)
11053     *Complained = true;
11054   return isInvalid;
11055 }
11056 
11057 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11058                                                  llvm::APSInt *Result) {
11059   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11060   public:
11061     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11062       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11063     }
11064   } Diagnoser;
11065   
11066   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11067 }
11068 
11069 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11070                                                  llvm::APSInt *Result,
11071                                                  unsigned DiagID,
11072                                                  bool AllowFold) {
11073   class IDDiagnoser : public VerifyICEDiagnoser {
11074     unsigned DiagID;
11075     
11076   public:
11077     IDDiagnoser(unsigned DiagID)
11078       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11079     
11080     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11081       S.Diag(Loc, DiagID) << SR;
11082     }
11083   } Diagnoser(DiagID);
11084   
11085   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11086 }
11087 
11088 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11089                                             SourceRange SR) {
11090   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11091 }
11092 
11093 ExprResult
11094 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11095                                       VerifyICEDiagnoser &Diagnoser,
11096                                       bool AllowFold) {
11097   SourceLocation DiagLoc = E->getLocStart();
11098 
11099   if (getLangOpts().CPlusPlus11) {
11100     // C++11 [expr.const]p5:
11101     //   If an expression of literal class type is used in a context where an
11102     //   integral constant expression is required, then that class type shall
11103     //   have a single non-explicit conversion function to an integral or
11104     //   unscoped enumeration type
11105     ExprResult Converted;
11106     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11107     public:
11108       CXX11ConvertDiagnoser(bool Silent)
11109           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11110                                 Silent, true) {}
11111 
11112       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11113                                            QualType T) override {
11114         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11115       }
11116 
11117       SemaDiagnosticBuilder diagnoseIncomplete(
11118           Sema &S, SourceLocation Loc, QualType T) override {
11119         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11120       }
11121 
11122       SemaDiagnosticBuilder diagnoseExplicitConv(
11123           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11124         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11125       }
11126 
11127       SemaDiagnosticBuilder noteExplicitConv(
11128           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11129         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11130                  << ConvTy->isEnumeralType() << ConvTy;
11131       }
11132 
11133       SemaDiagnosticBuilder diagnoseAmbiguous(
11134           Sema &S, SourceLocation Loc, QualType T) override {
11135         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11136       }
11137 
11138       SemaDiagnosticBuilder noteAmbiguous(
11139           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11140         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11141                  << ConvTy->isEnumeralType() << ConvTy;
11142       }
11143 
11144       SemaDiagnosticBuilder diagnoseConversion(
11145           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11146         llvm_unreachable("conversion functions are permitted");
11147       }
11148     } ConvertDiagnoser(Diagnoser.Suppress);
11149 
11150     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11151                                                     ConvertDiagnoser);
11152     if (Converted.isInvalid())
11153       return Converted;
11154     E = Converted.get();
11155     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11156       return ExprError();
11157   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11158     // An ICE must be of integral or unscoped enumeration type.
11159     if (!Diagnoser.Suppress)
11160       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11161     return ExprError();
11162   }
11163 
11164   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11165   // in the non-ICE case.
11166   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11167     if (Result)
11168       *Result = E->EvaluateKnownConstInt(Context);
11169     return E;
11170   }
11171 
11172   Expr::EvalResult EvalResult;
11173   SmallVector<PartialDiagnosticAt, 8> Notes;
11174   EvalResult.Diag = &Notes;
11175 
11176   // Try to evaluate the expression, and produce diagnostics explaining why it's
11177   // not a constant expression as a side-effect.
11178   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11179                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11180 
11181   // In C++11, we can rely on diagnostics being produced for any expression
11182   // which is not a constant expression. If no diagnostics were produced, then
11183   // this is a constant expression.
11184   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11185     if (Result)
11186       *Result = EvalResult.Val.getInt();
11187     return E;
11188   }
11189 
11190   // If our only note is the usual "invalid subexpression" note, just point
11191   // the caret at its location rather than producing an essentially
11192   // redundant note.
11193   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11194         diag::note_invalid_subexpr_in_const_expr) {
11195     DiagLoc = Notes[0].first;
11196     Notes.clear();
11197   }
11198 
11199   if (!Folded || !AllowFold) {
11200     if (!Diagnoser.Suppress) {
11201       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11202       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11203         Diag(Notes[I].first, Notes[I].second);
11204     }
11205 
11206     return ExprError();
11207   }
11208 
11209   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11210   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11211     Diag(Notes[I].first, Notes[I].second);
11212 
11213   if (Result)
11214     *Result = EvalResult.Val.getInt();
11215   return E;
11216 }
11217 
11218 namespace {
11219   // Handle the case where we conclude a expression which we speculatively
11220   // considered to be unevaluated is actually evaluated.
11221   class TransformToPE : public TreeTransform<TransformToPE> {
11222     typedef TreeTransform<TransformToPE> BaseTransform;
11223 
11224   public:
11225     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11226 
11227     // Make sure we redo semantic analysis
11228     bool AlwaysRebuild() { return true; }
11229 
11230     // Make sure we handle LabelStmts correctly.
11231     // FIXME: This does the right thing, but maybe we need a more general
11232     // fix to TreeTransform?
11233     StmtResult TransformLabelStmt(LabelStmt *S) {
11234       S->getDecl()->setStmt(nullptr);
11235       return BaseTransform::TransformLabelStmt(S);
11236     }
11237 
11238     // We need to special-case DeclRefExprs referring to FieldDecls which
11239     // are not part of a member pointer formation; normal TreeTransforming
11240     // doesn't catch this case because of the way we represent them in the AST.
11241     // FIXME: This is a bit ugly; is it really the best way to handle this
11242     // case?
11243     //
11244     // Error on DeclRefExprs referring to FieldDecls.
11245     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11246       if (isa<FieldDecl>(E->getDecl()) &&
11247           !SemaRef.isUnevaluatedContext())
11248         return SemaRef.Diag(E->getLocation(),
11249                             diag::err_invalid_non_static_member_use)
11250             << E->getDecl() << E->getSourceRange();
11251 
11252       return BaseTransform::TransformDeclRefExpr(E);
11253     }
11254 
11255     // Exception: filter out member pointer formation
11256     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11257       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11258         return E;
11259 
11260       return BaseTransform::TransformUnaryOperator(E);
11261     }
11262 
11263     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11264       // Lambdas never need to be transformed.
11265       return E;
11266     }
11267   };
11268 }
11269 
11270 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11271   assert(isUnevaluatedContext() &&
11272          "Should only transform unevaluated expressions");
11273   ExprEvalContexts.back().Context =
11274       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11275   if (isUnevaluatedContext())
11276     return E;
11277   return TransformToPE(*this).TransformExpr(E);
11278 }
11279 
11280 void
11281 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11282                                       Decl *LambdaContextDecl,
11283                                       bool IsDecltype) {
11284   ExprEvalContexts.push_back(
11285              ExpressionEvaluationContextRecord(NewContext,
11286                                                ExprCleanupObjects.size(),
11287                                                ExprNeedsCleanups,
11288                                                LambdaContextDecl,
11289                                                IsDecltype));
11290   ExprNeedsCleanups = false;
11291   if (!MaybeODRUseExprs.empty())
11292     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11293 }
11294 
11295 void
11296 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11297                                       ReuseLambdaContextDecl_t,
11298                                       bool IsDecltype) {
11299   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11300   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11301 }
11302 
11303 void Sema::PopExpressionEvaluationContext() {
11304   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11305   unsigned NumTypos = Rec.NumTypos;
11306 
11307   if (!Rec.Lambdas.empty()) {
11308     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11309       unsigned D;
11310       if (Rec.isUnevaluated()) {
11311         // C++11 [expr.prim.lambda]p2:
11312         //   A lambda-expression shall not appear in an unevaluated operand
11313         //   (Clause 5).
11314         D = diag::err_lambda_unevaluated_operand;
11315       } else {
11316         // C++1y [expr.const]p2:
11317         //   A conditional-expression e is a core constant expression unless the
11318         //   evaluation of e, following the rules of the abstract machine, would
11319         //   evaluate [...] a lambda-expression.
11320         D = diag::err_lambda_in_constant_expression;
11321       }
11322       for (const auto *L : Rec.Lambdas)
11323         Diag(L->getLocStart(), D);
11324     } else {
11325       // Mark the capture expressions odr-used. This was deferred
11326       // during lambda expression creation.
11327       for (auto *Lambda : Rec.Lambdas) {
11328         for (auto *C : Lambda->capture_inits())
11329           MarkDeclarationsReferencedInExpr(C);
11330       }
11331     }
11332   }
11333 
11334   // When are coming out of an unevaluated context, clear out any
11335   // temporaries that we may have created as part of the evaluation of
11336   // the expression in that context: they aren't relevant because they
11337   // will never be constructed.
11338   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11339     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11340                              ExprCleanupObjects.end());
11341     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11342     CleanupVarDeclMarking();
11343     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11344   // Otherwise, merge the contexts together.
11345   } else {
11346     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11347     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11348                             Rec.SavedMaybeODRUseExprs.end());
11349   }
11350 
11351   // Pop the current expression evaluation context off the stack.
11352   ExprEvalContexts.pop_back();
11353 
11354   if (!ExprEvalContexts.empty())
11355     ExprEvalContexts.back().NumTypos += NumTypos;
11356   else
11357     assert(NumTypos == 0 && "There are outstanding typos after popping the "
11358                             "last ExpressionEvaluationContextRecord");
11359 }
11360 
11361 void Sema::DiscardCleanupsInEvaluationContext() {
11362   ExprCleanupObjects.erase(
11363          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11364          ExprCleanupObjects.end());
11365   ExprNeedsCleanups = false;
11366   MaybeODRUseExprs.clear();
11367 }
11368 
11369 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11370   if (!E->getType()->isVariablyModifiedType())
11371     return E;
11372   return TransformToPotentiallyEvaluated(E);
11373 }
11374 
11375 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11376   // Do not mark anything as "used" within a dependent context; wait for
11377   // an instantiation.
11378   if (SemaRef.CurContext->isDependentContext())
11379     return false;
11380 
11381   switch (SemaRef.ExprEvalContexts.back().Context) {
11382     case Sema::Unevaluated:
11383     case Sema::UnevaluatedAbstract:
11384       // We are in an expression that is not potentially evaluated; do nothing.
11385       // (Depending on how you read the standard, we actually do need to do
11386       // something here for null pointer constants, but the standard's
11387       // definition of a null pointer constant is completely crazy.)
11388       return false;
11389 
11390     case Sema::ConstantEvaluated:
11391     case Sema::PotentiallyEvaluated:
11392       // We are in a potentially evaluated expression (or a constant-expression
11393       // in C++03); we need to do implicit template instantiation, implicitly
11394       // define class members, and mark most declarations as used.
11395       return true;
11396 
11397     case Sema::PotentiallyEvaluatedIfUsed:
11398       // Referenced declarations will only be used if the construct in the
11399       // containing expression is used.
11400       return false;
11401   }
11402   llvm_unreachable("Invalid context");
11403 }
11404 
11405 /// \brief Mark a function referenced, and check whether it is odr-used
11406 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11407 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
11408                                   bool OdrUse) {
11409   assert(Func && "No function?");
11410 
11411   Func->setReferenced();
11412 
11413   // C++11 [basic.def.odr]p3:
11414   //   A function whose name appears as a potentially-evaluated expression is
11415   //   odr-used if it is the unique lookup result or the selected member of a
11416   //   set of overloaded functions [...].
11417   //
11418   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11419   // can just check that here. Skip the rest of this function if we've already
11420   // marked the function as used.
11421   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11422     // C++11 [temp.inst]p3:
11423     //   Unless a function template specialization has been explicitly
11424     //   instantiated or explicitly specialized, the function template
11425     //   specialization is implicitly instantiated when the specialization is
11426     //   referenced in a context that requires a function definition to exist.
11427     //
11428     // We consider constexpr function templates to be referenced in a context
11429     // that requires a definition to exist whenever they are referenced.
11430     //
11431     // FIXME: This instantiates constexpr functions too frequently. If this is
11432     // really an unevaluated context (and we're not just in the definition of a
11433     // function template or overload resolution or other cases which we
11434     // incorrectly consider to be unevaluated contexts), and we're not in a
11435     // subexpression which we actually need to evaluate (for instance, a
11436     // template argument, array bound or an expression in a braced-init-list),
11437     // we are not permitted to instantiate this constexpr function definition.
11438     //
11439     // FIXME: This also implicitly defines special members too frequently. They
11440     // are only supposed to be implicitly defined if they are odr-used, but they
11441     // are not odr-used from constant expressions in unevaluated contexts.
11442     // However, they cannot be referenced if they are deleted, and they are
11443     // deleted whenever the implicit definition of the special member would
11444     // fail.
11445     if (!Func->isConstexpr() || Func->getBody())
11446       return;
11447     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11448     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11449       return;
11450   }
11451 
11452   // Note that this declaration has been used.
11453   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11454     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11455     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11456       if (Constructor->isDefaultConstructor()) {
11457         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11458           return;
11459         DefineImplicitDefaultConstructor(Loc, Constructor);
11460       } else if (Constructor->isCopyConstructor()) {
11461         DefineImplicitCopyConstructor(Loc, Constructor);
11462       } else if (Constructor->isMoveConstructor()) {
11463         DefineImplicitMoveConstructor(Loc, Constructor);
11464       }
11465     } else if (Constructor->getInheritedConstructor()) {
11466       DefineInheritingConstructor(Loc, Constructor);
11467     }
11468   } else if (CXXDestructorDecl *Destructor =
11469                  dyn_cast<CXXDestructorDecl>(Func)) {
11470     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11471     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11472       DefineImplicitDestructor(Loc, Destructor);
11473     if (Destructor->isVirtual())
11474       MarkVTableUsed(Loc, Destructor->getParent());
11475   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11476     if (MethodDecl->isOverloadedOperator() &&
11477         MethodDecl->getOverloadedOperator() == OO_Equal) {
11478       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11479       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11480         if (MethodDecl->isCopyAssignmentOperator())
11481           DefineImplicitCopyAssignment(Loc, MethodDecl);
11482         else
11483           DefineImplicitMoveAssignment(Loc, MethodDecl);
11484       }
11485     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11486                MethodDecl->getParent()->isLambda()) {
11487       CXXConversionDecl *Conversion =
11488           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11489       if (Conversion->isLambdaToBlockPointerConversion())
11490         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11491       else
11492         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11493     } else if (MethodDecl->isVirtual())
11494       MarkVTableUsed(Loc, MethodDecl->getParent());
11495   }
11496 
11497   // Recursive functions should be marked when used from another function.
11498   // FIXME: Is this really right?
11499   if (CurContext == Func) return;
11500 
11501   // Resolve the exception specification for any function which is
11502   // used: CodeGen will need it.
11503   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11504   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11505     ResolveExceptionSpec(Loc, FPT);
11506 
11507   if (!OdrUse) return;
11508 
11509   // Implicit instantiation of function templates and member functions of
11510   // class templates.
11511   if (Func->isImplicitlyInstantiable()) {
11512     bool AlreadyInstantiated = false;
11513     SourceLocation PointOfInstantiation = Loc;
11514     if (FunctionTemplateSpecializationInfo *SpecInfo
11515                               = Func->getTemplateSpecializationInfo()) {
11516       if (SpecInfo->getPointOfInstantiation().isInvalid())
11517         SpecInfo->setPointOfInstantiation(Loc);
11518       else if (SpecInfo->getTemplateSpecializationKind()
11519                  == TSK_ImplicitInstantiation) {
11520         AlreadyInstantiated = true;
11521         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11522       }
11523     } else if (MemberSpecializationInfo *MSInfo
11524                                 = Func->getMemberSpecializationInfo()) {
11525       if (MSInfo->getPointOfInstantiation().isInvalid())
11526         MSInfo->setPointOfInstantiation(Loc);
11527       else if (MSInfo->getTemplateSpecializationKind()
11528                  == TSK_ImplicitInstantiation) {
11529         AlreadyInstantiated = true;
11530         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11531       }
11532     }
11533 
11534     if (!AlreadyInstantiated || Func->isConstexpr()) {
11535       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11536           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11537           ActiveTemplateInstantiations.size())
11538         PendingLocalImplicitInstantiations.push_back(
11539             std::make_pair(Func, PointOfInstantiation));
11540       else if (Func->isConstexpr())
11541         // Do not defer instantiations of constexpr functions, to avoid the
11542         // expression evaluator needing to call back into Sema if it sees a
11543         // call to such a function.
11544         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11545       else {
11546         PendingInstantiations.push_back(std::make_pair(Func,
11547                                                        PointOfInstantiation));
11548         // Notify the consumer that a function was implicitly instantiated.
11549         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11550       }
11551     }
11552   } else {
11553     // Walk redefinitions, as some of them may be instantiable.
11554     for (auto i : Func->redecls()) {
11555       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11556         MarkFunctionReferenced(Loc, i);
11557     }
11558   }
11559 
11560   // Keep track of used but undefined functions.
11561   if (!Func->isDefined()) {
11562     if (mightHaveNonExternalLinkage(Func))
11563       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11564     else if (Func->getMostRecentDecl()->isInlined() &&
11565              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11566              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11567       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11568   }
11569 
11570   // Normally the most current decl is marked used while processing the use and
11571   // any subsequent decls are marked used by decl merging. This fails with
11572   // template instantiation since marking can happen at the end of the file
11573   // and, because of the two phase lookup, this function is called with at
11574   // decl in the middle of a decl chain. We loop to maintain the invariant
11575   // that once a decl is used, all decls after it are also used.
11576   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11577     F->markUsed(Context);
11578     if (F == Func)
11579       break;
11580   }
11581 }
11582 
11583 static void
11584 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11585                                    VarDecl *var, DeclContext *DC) {
11586   DeclContext *VarDC = var->getDeclContext();
11587 
11588   //  If the parameter still belongs to the translation unit, then
11589   //  we're actually just using one parameter in the declaration of
11590   //  the next.
11591   if (isa<ParmVarDecl>(var) &&
11592       isa<TranslationUnitDecl>(VarDC))
11593     return;
11594 
11595   // For C code, don't diagnose about capture if we're not actually in code
11596   // right now; it's impossible to write a non-constant expression outside of
11597   // function context, so we'll get other (more useful) diagnostics later.
11598   //
11599   // For C++, things get a bit more nasty... it would be nice to suppress this
11600   // diagnostic for certain cases like using a local variable in an array bound
11601   // for a member of a local class, but the correct predicate is not obvious.
11602   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11603     return;
11604 
11605   if (isa<CXXMethodDecl>(VarDC) &&
11606       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11607     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11608       << var->getIdentifier();
11609   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11610     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11611       << var->getIdentifier() << fn->getDeclName();
11612   } else if (isa<BlockDecl>(VarDC)) {
11613     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11614       << var->getIdentifier();
11615   } else {
11616     // FIXME: Is there any other context where a local variable can be
11617     // declared?
11618     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11619       << var->getIdentifier();
11620   }
11621 
11622   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11623       << var->getIdentifier();
11624 
11625   // FIXME: Add additional diagnostic info about class etc. which prevents
11626   // capture.
11627 }
11628 
11629  
11630 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
11631                                       bool &SubCapturesAreNested,
11632                                       QualType &CaptureType, 
11633                                       QualType &DeclRefType) {
11634    // Check whether we've already captured it.
11635   if (CSI->CaptureMap.count(Var)) {
11636     // If we found a capture, any subcaptures are nested.
11637     SubCapturesAreNested = true;
11638       
11639     // Retrieve the capture type for this variable.
11640     CaptureType = CSI->getCapture(Var).getCaptureType();
11641       
11642     // Compute the type of an expression that refers to this variable.
11643     DeclRefType = CaptureType.getNonReferenceType();
11644       
11645     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11646     if (Cap.isCopyCapture() &&
11647         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11648       DeclRefType.addConst();
11649     return true;
11650   }
11651   return false;
11652 }
11653 
11654 // Only block literals, captured statements, and lambda expressions can
11655 // capture; other scopes don't work.
11656 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
11657                                  SourceLocation Loc, 
11658                                  const bool Diagnose, Sema &S) {
11659   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11660     return getLambdaAwareParentOfDeclContext(DC);
11661   else {
11662     if (Diagnose)
11663        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11664   }
11665   return nullptr;
11666 }
11667 
11668 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
11669 // certain types of variables (unnamed, variably modified types etc.)
11670 // so check for eligibility.
11671 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
11672                                  SourceLocation Loc, 
11673                                  const bool Diagnose, Sema &S) {
11674 
11675   bool IsBlock = isa<BlockScopeInfo>(CSI);
11676   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11677 
11678   // Lambdas are not allowed to capture unnamed variables
11679   // (e.g. anonymous unions).
11680   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11681   // assuming that's the intent.
11682   if (IsLambda && !Var->getDeclName()) {
11683     if (Diagnose) {
11684       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11685       S.Diag(Var->getLocation(), diag::note_declared_at);
11686     }
11687     return false;
11688   }
11689 
11690   // Prohibit variably-modified types in blocks; they're difficult to deal with.
11691   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
11692     if (Diagnose) {
11693       S.Diag(Loc, diag::err_ref_vm_type);
11694       S.Diag(Var->getLocation(), diag::note_previous_decl) 
11695         << Var->getDeclName();
11696     }
11697     return false;
11698   }
11699   // Prohibit structs with flexible array members too.
11700   // We cannot capture what is in the tail end of the struct.
11701   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11702     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11703       if (Diagnose) {
11704         if (IsBlock)
11705           S.Diag(Loc, diag::err_ref_flexarray_type);
11706         else
11707           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11708             << Var->getDeclName();
11709         S.Diag(Var->getLocation(), diag::note_previous_decl)
11710           << Var->getDeclName();
11711       }
11712       return false;
11713     }
11714   }
11715   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11716   // Lambdas and captured statements are not allowed to capture __block
11717   // variables; they don't support the expected semantics.
11718   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11719     if (Diagnose) {
11720       S.Diag(Loc, diag::err_capture_block_variable)
11721         << Var->getDeclName() << !IsLambda;
11722       S.Diag(Var->getLocation(), diag::note_previous_decl)
11723         << Var->getDeclName();
11724     }
11725     return false;
11726   }
11727 
11728   return true;
11729 }
11730 
11731 // Returns true if the capture by block was successful.
11732 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
11733                                  SourceLocation Loc, 
11734                                  const bool BuildAndDiagnose, 
11735                                  QualType &CaptureType,
11736                                  QualType &DeclRefType, 
11737                                  const bool Nested,
11738                                  Sema &S) {
11739   Expr *CopyExpr = nullptr;
11740   bool ByRef = false;
11741       
11742   // Blocks are not allowed to capture arrays.
11743   if (CaptureType->isArrayType()) {
11744     if (BuildAndDiagnose) {
11745       S.Diag(Loc, diag::err_ref_array_type);
11746       S.Diag(Var->getLocation(), diag::note_previous_decl) 
11747       << Var->getDeclName();
11748     }
11749     return false;
11750   }
11751 
11752   // Forbid the block-capture of autoreleasing variables.
11753   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11754     if (BuildAndDiagnose) {
11755       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11756         << /*block*/ 0;
11757       S.Diag(Var->getLocation(), diag::note_previous_decl)
11758         << Var->getDeclName();
11759     }
11760     return false;
11761   }
11762   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11763   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11764     // Block capture by reference does not change the capture or
11765     // declaration reference types.
11766     ByRef = true;
11767   } else {
11768     // Block capture by copy introduces 'const'.
11769     CaptureType = CaptureType.getNonReferenceType().withConst();
11770     DeclRefType = CaptureType;
11771                 
11772     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11773       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11774         // The capture logic needs the destructor, so make sure we mark it.
11775         // Usually this is unnecessary because most local variables have
11776         // their destructors marked at declaration time, but parameters are
11777         // an exception because it's technically only the call site that
11778         // actually requires the destructor.
11779         if (isa<ParmVarDecl>(Var))
11780           S.FinalizeVarWithDestructor(Var, Record);
11781 
11782         // Enter a new evaluation context to insulate the copy
11783         // full-expression.
11784         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11785 
11786         // According to the blocks spec, the capture of a variable from
11787         // the stack requires a const copy constructor.  This is not true
11788         // of the copy/move done to move a __block variable to the heap.
11789         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11790                                                   DeclRefType.withConst(), 
11791                                                   VK_LValue, Loc);
11792             
11793         ExprResult Result
11794           = S.PerformCopyInitialization(
11795               InitializedEntity::InitializeBlock(Var->getLocation(),
11796                                                   CaptureType, false),
11797               Loc, DeclRef);
11798             
11799         // Build a full-expression copy expression if initialization
11800         // succeeded and used a non-trivial constructor.  Recover from
11801         // errors by pretending that the copy isn't necessary.
11802         if (!Result.isInvalid() &&
11803             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11804                 ->isTrivial()) {
11805           Result = S.MaybeCreateExprWithCleanups(Result);
11806           CopyExpr = Result.get();
11807         }
11808       }
11809     }
11810   }
11811 
11812   // Actually capture the variable.
11813   if (BuildAndDiagnose)
11814     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
11815                     SourceLocation(), CaptureType, CopyExpr);
11816 
11817   return true;
11818 
11819 }
11820 
11821 
11822 /// \brief Capture the given variable in the captured region.
11823 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11824                                     VarDecl *Var, 
11825                                     SourceLocation Loc, 
11826                                     const bool BuildAndDiagnose, 
11827                                     QualType &CaptureType,
11828                                     QualType &DeclRefType, 
11829                                     const bool RefersToEnclosingLocal,
11830                                     Sema &S) {
11831   
11832   // By default, capture variables by reference.
11833   bool ByRef = true;
11834   // Using an LValue reference type is consistent with Lambdas (see below).
11835   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11836   Expr *CopyExpr = nullptr;
11837   if (BuildAndDiagnose) {
11838     // The current implementation assumes that all variables are captured
11839     // by references. Since there is no capture by copy, no expression
11840     // evaluation will be needed.
11841     RecordDecl *RD = RSI->TheRecordDecl;
11842 
11843     FieldDecl *Field
11844       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11845                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11846                           nullptr, false, ICIS_NoInit);
11847     Field->setImplicit(true);
11848     Field->setAccess(AS_private);
11849     RD->addDecl(Field);
11850  
11851     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11852                                             DeclRefType, VK_LValue, Loc);
11853     Var->setReferenced(true);
11854     Var->markUsed(S.Context);
11855   }
11856 
11857   // Actually capture the variable.
11858   if (BuildAndDiagnose)
11859     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11860                     SourceLocation(), CaptureType, CopyExpr);
11861   
11862   
11863   return true;
11864 }
11865 
11866 /// \brief Create a field within the lambda class for the variable
11867 ///  being captured.  Handle Array captures.  
11868 static ExprResult addAsFieldToClosureType(Sema &S, 
11869                                  LambdaScopeInfo *LSI,
11870                                   VarDecl *Var, QualType FieldType, 
11871                                   QualType DeclRefType,
11872                                   SourceLocation Loc,
11873                                   bool RefersToEnclosingLocal) {
11874   CXXRecordDecl *Lambda = LSI->Lambda;
11875 
11876   // Build the non-static data member.
11877   FieldDecl *Field
11878     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11879                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11880                         nullptr, false, ICIS_NoInit);
11881   Field->setImplicit(true);
11882   Field->setAccess(AS_private);
11883   Lambda->addDecl(Field);
11884 
11885   // C++11 [expr.prim.lambda]p21:
11886   //   When the lambda-expression is evaluated, the entities that
11887   //   are captured by copy are used to direct-initialize each
11888   //   corresponding non-static data member of the resulting closure
11889   //   object. (For array members, the array elements are
11890   //   direct-initialized in increasing subscript order.) These
11891   //   initializations are performed in the (unspecified) order in
11892   //   which the non-static data members are declared.
11893       
11894   // Introduce a new evaluation context for the initialization, so
11895   // that temporaries introduced as part of the capture are retained
11896   // to be re-"exported" from the lambda expression itself.
11897   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11898 
11899   // C++ [expr.prim.labda]p12:
11900   //   An entity captured by a lambda-expression is odr-used (3.2) in
11901   //   the scope containing the lambda-expression.
11902   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 
11903                                           DeclRefType, VK_LValue, Loc);
11904   Var->setReferenced(true);
11905   Var->markUsed(S.Context);
11906 
11907   // When the field has array type, create index variables for each
11908   // dimension of the array. We use these index variables to subscript
11909   // the source array, and other clients (e.g., CodeGen) will perform
11910   // the necessary iteration with these index variables.
11911   SmallVector<VarDecl *, 4> IndexVariables;
11912   QualType BaseType = FieldType;
11913   QualType SizeType = S.Context.getSizeType();
11914   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11915   while (const ConstantArrayType *Array
11916                         = S.Context.getAsConstantArrayType(BaseType)) {
11917     // Create the iteration variable for this array index.
11918     IdentifierInfo *IterationVarName = nullptr;
11919     {
11920       SmallString<8> Str;
11921       llvm::raw_svector_ostream OS(Str);
11922       OS << "__i" << IndexVariables.size();
11923       IterationVarName = &S.Context.Idents.get(OS.str());
11924     }
11925     VarDecl *IterationVar
11926       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11927                         IterationVarName, SizeType,
11928                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11929                         SC_None);
11930     IndexVariables.push_back(IterationVar);
11931     LSI->ArrayIndexVars.push_back(IterationVar);
11932     
11933     // Create a reference to the iteration variable.
11934     ExprResult IterationVarRef
11935       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11936     assert(!IterationVarRef.isInvalid() &&
11937            "Reference to invented variable cannot fail!");
11938     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11939     assert(!IterationVarRef.isInvalid() &&
11940            "Conversion of invented variable cannot fail!");
11941     
11942     // Subscript the array with this iteration variable.
11943     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11944                              Ref, Loc, IterationVarRef.get(), Loc);
11945     if (Subscript.isInvalid()) {
11946       S.CleanupVarDeclMarking();
11947       S.DiscardCleanupsInEvaluationContext();
11948       return ExprError();
11949     }
11950 
11951     Ref = Subscript.get();
11952     BaseType = Array->getElementType();
11953   }
11954 
11955   // Construct the entity that we will be initializing. For an array, this
11956   // will be first element in the array, which may require several levels
11957   // of array-subscript entities. 
11958   SmallVector<InitializedEntity, 4> Entities;
11959   Entities.reserve(1 + IndexVariables.size());
11960   Entities.push_back(
11961     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 
11962         Field->getType(), Loc));
11963   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11964     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11965                                                             0,
11966                                                             Entities.back()));
11967 
11968   InitializationKind InitKind
11969     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11970   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11971   ExprResult Result(true);
11972   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11973     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11974 
11975   // If this initialization requires any cleanups (e.g., due to a
11976   // default argument to a copy constructor), note that for the
11977   // lambda.
11978   if (S.ExprNeedsCleanups)
11979     LSI->ExprNeedsCleanups = true;
11980 
11981   // Exit the expression evaluation context used for the capture.
11982   S.CleanupVarDeclMarking();
11983   S.DiscardCleanupsInEvaluationContext();
11984   return Result;
11985 }
11986 
11987 
11988 
11989 /// \brief Capture the given variable in the lambda.
11990 static bool captureInLambda(LambdaScopeInfo *LSI,
11991                             VarDecl *Var, 
11992                             SourceLocation Loc, 
11993                             const bool BuildAndDiagnose, 
11994                             QualType &CaptureType,
11995                             QualType &DeclRefType, 
11996                             const bool RefersToEnclosingLocal,
11997                             const Sema::TryCaptureKind Kind, 
11998                             SourceLocation EllipsisLoc,
11999                             const bool IsTopScope,
12000                             Sema &S) {
12001 
12002   // Determine whether we are capturing by reference or by value.
12003   bool ByRef = false;
12004   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12005     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12006   } else {
12007     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12008   }
12009     
12010   // Compute the type of the field that will capture this variable.
12011   if (ByRef) {
12012     // C++11 [expr.prim.lambda]p15:
12013     //   An entity is captured by reference if it is implicitly or
12014     //   explicitly captured but not captured by copy. It is
12015     //   unspecified whether additional unnamed non-static data
12016     //   members are declared in the closure type for entities
12017     //   captured by reference.
12018     //
12019     // FIXME: It is not clear whether we want to build an lvalue reference
12020     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12021     // to do the former, while EDG does the latter. Core issue 1249 will 
12022     // clarify, but for now we follow GCC because it's a more permissive and
12023     // easily defensible position.
12024     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12025   } else {
12026     // C++11 [expr.prim.lambda]p14:
12027     //   For each entity captured by copy, an unnamed non-static
12028     //   data member is declared in the closure type. The
12029     //   declaration order of these members is unspecified. The type
12030     //   of such a data member is the type of the corresponding
12031     //   captured entity if the entity is not a reference to an
12032     //   object, or the referenced type otherwise. [Note: If the
12033     //   captured entity is a reference to a function, the
12034     //   corresponding data member is also a reference to a
12035     //   function. - end note ]
12036     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12037       if (!RefType->getPointeeType()->isFunctionType())
12038         CaptureType = RefType->getPointeeType();
12039     }
12040 
12041     // Forbid the lambda copy-capture of autoreleasing variables.
12042     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12043       if (BuildAndDiagnose) {
12044         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12045         S.Diag(Var->getLocation(), diag::note_previous_decl)
12046           << Var->getDeclName();
12047       }
12048       return false;
12049     }
12050 
12051     // Make sure that by-copy captures are of a complete and non-abstract type.
12052     if (BuildAndDiagnose) {
12053       if (!CaptureType->isDependentType() &&
12054           S.RequireCompleteType(Loc, CaptureType,
12055                                 diag::err_capture_of_incomplete_type,
12056                                 Var->getDeclName()))
12057         return false;
12058 
12059       if (S.RequireNonAbstractType(Loc, CaptureType,
12060                                    diag::err_capture_of_abstract_type))
12061         return false;
12062     }
12063   }
12064 
12065   // Capture this variable in the lambda.
12066   Expr *CopyExpr = nullptr;
12067   if (BuildAndDiagnose) {
12068     ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 
12069                                         CaptureType, DeclRefType, Loc,
12070                                         RefersToEnclosingLocal);
12071     if (!Result.isInvalid())
12072       CopyExpr = Result.get();
12073   }
12074     
12075   // Compute the type of a reference to this captured variable.
12076   if (ByRef)
12077     DeclRefType = CaptureType.getNonReferenceType();
12078   else {
12079     // C++ [expr.prim.lambda]p5:
12080     //   The closure type for a lambda-expression has a public inline 
12081     //   function call operator [...]. This function call operator is 
12082     //   declared const (9.3.1) if and only if the lambda-expression’s 
12083     //   parameter-declaration-clause is not followed by mutable.
12084     DeclRefType = CaptureType.getNonReferenceType();
12085     if (!LSI->Mutable && !CaptureType->isReferenceType())
12086       DeclRefType.addConst();      
12087   }
12088     
12089   // Add the capture.
12090   if (BuildAndDiagnose)
12091     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 
12092                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12093       
12094   return true;
12095 }
12096 
12097 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 
12098                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12099                               bool BuildAndDiagnose, 
12100                               QualType &CaptureType,
12101                               QualType &DeclRefType,
12102                             const unsigned *const FunctionScopeIndexToStopAt) {
12103   bool Nested = false;
12104   
12105   DeclContext *DC = CurContext;
12106   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
12107       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
12108   // We need to sync up the Declaration Context with the
12109   // FunctionScopeIndexToStopAt
12110   if (FunctionScopeIndexToStopAt) {
12111     unsigned FSIndex = FunctionScopes.size() - 1;
12112     while (FSIndex != MaxFunctionScopesIndex) {
12113       DC = getLambdaAwareParentOfDeclContext(DC);
12114       --FSIndex;
12115     }
12116   }
12117 
12118   
12119   // If the variable is declared in the current context (and is not an 
12120   // init-capture), there is no need to capture it.
12121   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12122   if (!Var->hasLocalStorage()) return true;
12123 
12124   // Walk up the stack to determine whether we can capture the variable,
12125   // performing the "simple" checks that don't depend on type. We stop when
12126   // we've either hit the declared scope of the variable or find an existing
12127   // capture of that variable.  We start from the innermost capturing-entity
12128   // (the DC) and ensure that all intervening capturing-entities 
12129   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12130   // declcontext can either capture the variable or have already captured
12131   // the variable.
12132   CaptureType = Var->getType();
12133   DeclRefType = CaptureType.getNonReferenceType();
12134   bool Explicit = (Kind != TryCapture_Implicit);
12135   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12136   do {
12137     // Only block literals, captured statements, and lambda expressions can
12138     // capture; other scopes don't work.
12139     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
12140                                                               ExprLoc, 
12141                                                               BuildAndDiagnose,
12142                                                               *this);
12143     if (!ParentDC) return true;
12144     
12145     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12146     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12147 
12148 
12149     // Check whether we've already captured it.
12150     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
12151                                              DeclRefType)) 
12152       break;
12153     // If we are instantiating a generic lambda call operator body, 
12154     // we do not want to capture new variables.  What was captured
12155     // during either a lambdas transformation or initial parsing
12156     // should be used. 
12157     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12158       if (BuildAndDiagnose) {
12159         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
12160         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12161           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12162           Diag(Var->getLocation(), diag::note_previous_decl) 
12163              << Var->getDeclName();
12164           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
12165         } else
12166           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12167       }
12168       return true;
12169     }
12170     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
12171     // certain types of variables (unnamed, variably modified types etc.)
12172     // so check for eligibility.
12173     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12174        return true;
12175 
12176     // Try to capture variable-length arrays types.
12177     if (Var->getType()->isVariablyModifiedType()) {
12178       // We're going to walk down into the type and look for VLA
12179       // expressions.
12180       QualType QTy = Var->getType();
12181       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12182         QTy = PVD->getOriginalType();
12183       do {
12184         const Type *Ty = QTy.getTypePtr();
12185         switch (Ty->getTypeClass()) {
12186 #define TYPE(Class, Base)
12187 #define ABSTRACT_TYPE(Class, Base)
12188 #define NON_CANONICAL_TYPE(Class, Base)
12189 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12190 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12191 #include "clang/AST/TypeNodes.def"
12192           QTy = QualType();
12193           break;
12194         // These types are never variably-modified.
12195         case Type::Builtin:
12196         case Type::Complex:
12197         case Type::Vector:
12198         case Type::ExtVector:
12199         case Type::Record:
12200         case Type::Enum:
12201         case Type::Elaborated:
12202         case Type::TemplateSpecialization:
12203         case Type::ObjCObject:
12204         case Type::ObjCInterface:
12205         case Type::ObjCObjectPointer:
12206           llvm_unreachable("type class is never variably-modified!");
12207         case Type::Adjusted:
12208           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12209           break;
12210         case Type::Decayed:
12211           QTy = cast<DecayedType>(Ty)->getPointeeType();
12212           break;
12213         case Type::Pointer:
12214           QTy = cast<PointerType>(Ty)->getPointeeType();
12215           break;
12216         case Type::BlockPointer:
12217           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12218           break;
12219         case Type::LValueReference:
12220         case Type::RValueReference:
12221           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12222           break;
12223         case Type::MemberPointer:
12224           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12225           break;
12226         case Type::ConstantArray:
12227         case Type::IncompleteArray:
12228           // Losing element qualification here is fine.
12229           QTy = cast<ArrayType>(Ty)->getElementType();
12230           break;
12231         case Type::VariableArray: {
12232           // Losing element qualification here is fine.
12233           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12234 
12235           // Unknown size indication requires no size computation.
12236           // Otherwise, evaluate and record it.
12237           if (auto Size = VAT->getSizeExpr()) {
12238             if (!CSI->isVLATypeCaptured(VAT)) {
12239               RecordDecl *CapRecord = nullptr;
12240               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12241                 CapRecord = LSI->Lambda;
12242               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12243                 CapRecord = CRSI->TheRecordDecl;
12244               }
12245               if (CapRecord) {
12246                 auto ExprLoc = Size->getExprLoc();
12247                 auto SizeType = Context.getSizeType();
12248                 // Build the non-static data member.
12249                 auto Field = FieldDecl::Create(
12250                     Context, CapRecord, ExprLoc, ExprLoc,
12251                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12252                     /*BW*/ nullptr, /*Mutable*/ false,
12253                     /*InitStyle*/ ICIS_NoInit);
12254                 Field->setImplicit(true);
12255                 Field->setAccess(AS_private);
12256                 Field->setCapturedVLAType(VAT);
12257                 CapRecord->addDecl(Field);
12258 
12259                 CSI->addVLATypeCapture(ExprLoc, SizeType);
12260               }
12261             }
12262           }
12263           QTy = VAT->getElementType();
12264           break;
12265         }
12266         case Type::FunctionProto:
12267         case Type::FunctionNoProto:
12268           QTy = cast<FunctionType>(Ty)->getReturnType();
12269           break;
12270         case Type::Paren:
12271         case Type::TypeOf:
12272         case Type::UnaryTransform:
12273         case Type::Attributed:
12274         case Type::SubstTemplateTypeParm:
12275         case Type::PackExpansion:
12276           // Keep walking after single level desugaring.
12277           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12278           break;
12279         case Type::Typedef:
12280           QTy = cast<TypedefType>(Ty)->desugar();
12281           break;
12282         case Type::Decltype:
12283           QTy = cast<DecltypeType>(Ty)->desugar();
12284           break;
12285         case Type::Auto:
12286           QTy = cast<AutoType>(Ty)->getDeducedType();
12287           break;
12288         case Type::TypeOfExpr:
12289           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12290           break;
12291         case Type::Atomic:
12292           QTy = cast<AtomicType>(Ty)->getValueType();
12293           break;
12294         }
12295       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12296     }
12297 
12298     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12299       // No capture-default, and this is not an explicit capture 
12300       // so cannot capture this variable.  
12301       if (BuildAndDiagnose) {
12302         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12303         Diag(Var->getLocation(), diag::note_previous_decl) 
12304           << Var->getDeclName();
12305         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12306              diag::note_lambda_decl);
12307         // FIXME: If we error out because an outer lambda can not implicitly
12308         // capture a variable that an inner lambda explicitly captures, we
12309         // should have the inner lambda do the explicit capture - because
12310         // it makes for cleaner diagnostics later.  This would purely be done
12311         // so that the diagnostic does not misleadingly claim that a variable 
12312         // can not be captured by a lambda implicitly even though it is captured 
12313         // explicitly.  Suggestion:
12314         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
12315         //    at the function head
12316         //  - cache the StartingDeclContext - this must be a lambda 
12317         //  - captureInLambda in the innermost lambda the variable.
12318       }
12319       return true;
12320     }
12321 
12322     FunctionScopesIndex--;
12323     DC = ParentDC;
12324     Explicit = false;
12325   } while (!Var->getDeclContext()->Equals(DC));
12326 
12327   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12328   // computing the type of the capture at each step, checking type-specific 
12329   // requirements, and adding captures if requested. 
12330   // If the variable had already been captured previously, we start capturing 
12331   // at the lambda nested within that one.   
12332   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
12333        ++I) {
12334     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12335     
12336     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12337       if (!captureInBlock(BSI, Var, ExprLoc, 
12338                           BuildAndDiagnose, CaptureType, 
12339                           DeclRefType, Nested, *this))
12340         return true;
12341       Nested = true;
12342     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12343       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
12344                                    BuildAndDiagnose, CaptureType, 
12345                                    DeclRefType, Nested, *this))
12346         return true;
12347       Nested = true;
12348     } else {
12349       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12350       if (!captureInLambda(LSI, Var, ExprLoc, 
12351                            BuildAndDiagnose, CaptureType, 
12352                            DeclRefType, Nested, Kind, EllipsisLoc, 
12353                             /*IsTopScope*/I == N - 1, *this))
12354         return true;
12355       Nested = true;
12356     }
12357   }
12358   return false;
12359 }
12360 
12361 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12362                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
12363   QualType CaptureType;
12364   QualType DeclRefType;
12365   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12366                             /*BuildAndDiagnose=*/true, CaptureType,
12367                             DeclRefType, nullptr);
12368 }
12369 
12370 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12371   QualType CaptureType;
12372   QualType DeclRefType;
12373   
12374   // Determine whether we can capture this variable.
12375   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12376                          /*BuildAndDiagnose=*/false, CaptureType, 
12377                          DeclRefType, nullptr))
12378     return QualType();
12379 
12380   return DeclRefType;
12381 }
12382 
12383 
12384 
12385 // If either the type of the variable or the initializer is dependent, 
12386 // return false. Otherwise, determine whether the variable is a constant
12387 // expression. Use this if you need to know if a variable that might or
12388 // might not be dependent is truly a constant expression.
12389 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
12390     ASTContext &Context) {
12391  
12392   if (Var->getType()->isDependentType()) 
12393     return false;
12394   const VarDecl *DefVD = nullptr;
12395   Var->getAnyInitializer(DefVD);
12396   if (!DefVD) 
12397     return false;
12398   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12399   Expr *Init = cast<Expr>(Eval->Value);
12400   if (Init->isValueDependent()) 
12401     return false;
12402   return IsVariableAConstantExpression(Var, Context); 
12403 }
12404 
12405 
12406 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12407   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
12408   // an object that satisfies the requirements for appearing in a
12409   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12410   // is immediately applied."  This function handles the lvalue-to-rvalue
12411   // conversion part.
12412   MaybeODRUseExprs.erase(E->IgnoreParens());
12413   
12414   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12415   // to a variable that is a constant expression, and if so, identify it as
12416   // a reference to a variable that does not involve an odr-use of that 
12417   // variable. 
12418   if (LambdaScopeInfo *LSI = getCurLambda()) {
12419     Expr *SansParensExpr = E->IgnoreParens();
12420     VarDecl *Var = nullptr;
12421     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
12422       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12423     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12424       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12425     
12426     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
12427       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
12428   }
12429 }
12430 
12431 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12432   if (!Res.isUsable())
12433     return Res;
12434 
12435   // If a constant-expression is a reference to a variable where we delay
12436   // deciding whether it is an odr-use, just assume we will apply the
12437   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12438   // (a non-type template argument), we have special handling anyway.
12439   UpdateMarkingForLValueToRValue(Res.get());
12440   return Res;
12441 }
12442 
12443 void Sema::CleanupVarDeclMarking() {
12444   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12445                                         e = MaybeODRUseExprs.end();
12446        i != e; ++i) {
12447     VarDecl *Var;
12448     SourceLocation Loc;
12449     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12450       Var = cast<VarDecl>(DRE->getDecl());
12451       Loc = DRE->getLocation();
12452     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12453       Var = cast<VarDecl>(ME->getMemberDecl());
12454       Loc = ME->getMemberLoc();
12455     } else {
12456       llvm_unreachable("Unexpected expression");
12457     }
12458 
12459     MarkVarDeclODRUsed(Var, Loc, *this,
12460                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12461   }
12462 
12463   MaybeODRUseExprs.clear();
12464 }
12465 
12466 
12467 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12468                                     VarDecl *Var, Expr *E) {
12469   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12470          "Invalid Expr argument to DoMarkVarDeclReferenced");
12471   Var->setReferenced();
12472 
12473   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12474   bool MarkODRUsed = true;
12475 
12476   // If the context is not potentially evaluated, this is not an odr-use and
12477   // does not trigger instantiation.
12478   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12479     if (SemaRef.isUnevaluatedContext())
12480       return;
12481 
12482     // If we don't yet know whether this context is going to end up being an
12483     // evaluated context, and we're referencing a variable from an enclosing
12484     // scope, add a potential capture.
12485     //
12486     // FIXME: Is this necessary? These contexts are only used for default
12487     // arguments, where local variables can't be used.
12488     const bool RefersToEnclosingScope =
12489         (SemaRef.CurContext != Var->getDeclContext() &&
12490          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
12491     if (RefersToEnclosingScope) {
12492       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12493         // If a variable could potentially be odr-used, defer marking it so
12494         // until we finish analyzing the full expression for any
12495         // lvalue-to-rvalue
12496         // or discarded value conversions that would obviate odr-use.
12497         // Add it to the list of potential captures that will be analyzed
12498         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12499         // unless the variable is a reference that was initialized by a constant
12500         // expression (this will never need to be captured or odr-used).
12501         assert(E && "Capture variable should be used in an expression.");
12502         if (!Var->getType()->isReferenceType() ||
12503             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12504           LSI->addPotentialCapture(E->IgnoreParens());
12505       }
12506     }
12507 
12508     if (!isTemplateInstantiation(TSK))
12509       return;
12510 
12511     // Instantiate, but do not mark as odr-used, variable templates.
12512     MarkODRUsed = false;
12513   }
12514 
12515   VarTemplateSpecializationDecl *VarSpec =
12516       dyn_cast<VarTemplateSpecializationDecl>(Var);
12517   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12518          "Can't instantiate a partial template specialization.");
12519 
12520   // Perform implicit instantiation of static data members, static data member
12521   // templates of class templates, and variable template specializations. Delay
12522   // instantiations of variable templates, except for those that could be used
12523   // in a constant expression.
12524   if (isTemplateInstantiation(TSK)) {
12525     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12526 
12527     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12528       if (Var->getPointOfInstantiation().isInvalid()) {
12529         // This is a modification of an existing AST node. Notify listeners.
12530         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12531           L->StaticDataMemberInstantiated(Var);
12532       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12533         // Don't bother trying to instantiate it again, unless we might need
12534         // its initializer before we get to the end of the TU.
12535         TryInstantiating = false;
12536     }
12537 
12538     if (Var->getPointOfInstantiation().isInvalid())
12539       Var->setTemplateSpecializationKind(TSK, Loc);
12540 
12541     if (TryInstantiating) {
12542       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12543       bool InstantiationDependent = false;
12544       bool IsNonDependent =
12545           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12546                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12547                   : true;
12548 
12549       // Do not instantiate specializations that are still type-dependent.
12550       if (IsNonDependent) {
12551         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12552           // Do not defer instantiations of variables which could be used in a
12553           // constant expression.
12554           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12555         } else {
12556           SemaRef.PendingInstantiations
12557               .push_back(std::make_pair(Var, PointOfInstantiation));
12558         }
12559       }
12560     }
12561   }
12562 
12563   if(!MarkODRUsed) return;
12564 
12565   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12566   // the requirements for appearing in a constant expression (5.19) and, if
12567   // it is an object, the lvalue-to-rvalue conversion (4.1)
12568   // is immediately applied."  We check the first part here, and
12569   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12570   // Note that we use the C++11 definition everywhere because nothing in
12571   // C++03 depends on whether we get the C++03 version correct. The second
12572   // part does not apply to references, since they are not objects.
12573   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12574     // A reference initialized by a constant expression can never be
12575     // odr-used, so simply ignore it.
12576     if (!Var->getType()->isReferenceType())
12577       SemaRef.MaybeODRUseExprs.insert(E);
12578   } else
12579     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12580                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12581 }
12582 
12583 /// \brief Mark a variable referenced, and check whether it is odr-used
12584 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12585 /// used directly for normal expressions referring to VarDecl.
12586 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12587   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12588 }
12589 
12590 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12591                                Decl *D, Expr *E, bool OdrUse) {
12592   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12593     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12594     return;
12595   }
12596 
12597   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12598 
12599   // If this is a call to a method via a cast, also mark the method in the
12600   // derived class used in case codegen can devirtualize the call.
12601   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12602   if (!ME)
12603     return;
12604   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12605   if (!MD)
12606     return;
12607   // Only attempt to devirtualize if this is truly a virtual call.
12608   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
12609   if (!IsVirtualCall)
12610     return;
12611   const Expr *Base = ME->getBase();
12612   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12613   if (!MostDerivedClassDecl)
12614     return;
12615   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12616   if (!DM || DM->isPure())
12617     return;
12618   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12619 } 
12620 
12621 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12622 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12623   // TODO: update this with DR# once a defect report is filed.
12624   // C++11 defect. The address of a pure member should not be an ODR use, even
12625   // if it's a qualified reference.
12626   bool OdrUse = true;
12627   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12628     if (Method->isVirtual())
12629       OdrUse = false;
12630   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12631 }
12632 
12633 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12634 void Sema::MarkMemberReferenced(MemberExpr *E) {
12635   // C++11 [basic.def.odr]p2:
12636   //   A non-overloaded function whose name appears as a potentially-evaluated
12637   //   expression or a member of a set of candidate functions, if selected by
12638   //   overload resolution when referred to from a potentially-evaluated
12639   //   expression, is odr-used, unless it is a pure virtual function and its
12640   //   name is not explicitly qualified.
12641   bool OdrUse = true;
12642   if (!E->hasQualifier()) {
12643     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12644       if (Method->isPure())
12645         OdrUse = false;
12646   }
12647   SourceLocation Loc = E->getMemberLoc().isValid() ?
12648                             E->getMemberLoc() : E->getLocStart();
12649   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12650 }
12651 
12652 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12653 /// marks the declaration referenced, and performs odr-use checking for
12654 /// functions and variables. This method should not be used when building a
12655 /// normal expression which refers to a variable.
12656 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12657   if (OdrUse) {
12658     if (auto *VD = dyn_cast<VarDecl>(D)) {
12659       MarkVariableReferenced(Loc, VD);
12660       return;
12661     }
12662   }
12663   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12664     MarkFunctionReferenced(Loc, FD, OdrUse);
12665     return;
12666   }
12667   D->setReferenced();
12668 }
12669 
12670 namespace {
12671   // Mark all of the declarations referenced
12672   // FIXME: Not fully implemented yet! We need to have a better understanding
12673   // of when we're entering
12674   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12675     Sema &S;
12676     SourceLocation Loc;
12677 
12678   public:
12679     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12680 
12681     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12682 
12683     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12684     bool TraverseRecordType(RecordType *T);
12685   };
12686 }
12687 
12688 bool MarkReferencedDecls::TraverseTemplateArgument(
12689     const TemplateArgument &Arg) {
12690   if (Arg.getKind() == TemplateArgument::Declaration) {
12691     if (Decl *D = Arg.getAsDecl())
12692       S.MarkAnyDeclReferenced(Loc, D, true);
12693   }
12694 
12695   return Inherited::TraverseTemplateArgument(Arg);
12696 }
12697 
12698 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12699   if (ClassTemplateSpecializationDecl *Spec
12700                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12701     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12702     return TraverseTemplateArguments(Args.data(), Args.size());
12703   }
12704 
12705   return true;
12706 }
12707 
12708 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12709   MarkReferencedDecls Marker(*this, Loc);
12710   Marker.TraverseType(Context.getCanonicalType(T));
12711 }
12712 
12713 namespace {
12714   /// \brief Helper class that marks all of the declarations referenced by
12715   /// potentially-evaluated subexpressions as "referenced".
12716   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12717     Sema &S;
12718     bool SkipLocalVariables;
12719     
12720   public:
12721     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12722     
12723     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
12724       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12725     
12726     void VisitDeclRefExpr(DeclRefExpr *E) {
12727       // If we were asked not to visit local variables, don't.
12728       if (SkipLocalVariables) {
12729         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12730           if (VD->hasLocalStorage())
12731             return;
12732       }
12733       
12734       S.MarkDeclRefReferenced(E);
12735     }
12736 
12737     void VisitMemberExpr(MemberExpr *E) {
12738       S.MarkMemberReferenced(E);
12739       Inherited::VisitMemberExpr(E);
12740     }
12741     
12742     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12743       S.MarkFunctionReferenced(E->getLocStart(),
12744             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12745       Visit(E->getSubExpr());
12746     }
12747     
12748     void VisitCXXNewExpr(CXXNewExpr *E) {
12749       if (E->getOperatorNew())
12750         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12751       if (E->getOperatorDelete())
12752         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12753       Inherited::VisitCXXNewExpr(E);
12754     }
12755 
12756     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12757       if (E->getOperatorDelete())
12758         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12759       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12760       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12761         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12762         S.MarkFunctionReferenced(E->getLocStart(), 
12763                                     S.LookupDestructor(Record));
12764       }
12765       
12766       Inherited::VisitCXXDeleteExpr(E);
12767     }
12768     
12769     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12770       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12771       Inherited::VisitCXXConstructExpr(E);
12772     }
12773     
12774     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12775       Visit(E->getExpr());
12776     }
12777 
12778     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12779       Inherited::VisitImplicitCastExpr(E);
12780 
12781       if (E->getCastKind() == CK_LValueToRValue)
12782         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12783     }
12784   };
12785 }
12786 
12787 /// \brief Mark any declarations that appear within this expression or any
12788 /// potentially-evaluated subexpressions as "referenced".
12789 ///
12790 /// \param SkipLocalVariables If true, don't mark local variables as 
12791 /// 'referenced'.
12792 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
12793                                             bool SkipLocalVariables) {
12794   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12795 }
12796 
12797 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12798 /// of the program being compiled.
12799 ///
12800 /// This routine emits the given diagnostic when the code currently being
12801 /// type-checked is "potentially evaluated", meaning that there is a
12802 /// possibility that the code will actually be executable. Code in sizeof()
12803 /// expressions, code used only during overload resolution, etc., are not
12804 /// potentially evaluated. This routine will suppress such diagnostics or,
12805 /// in the absolutely nutty case of potentially potentially evaluated
12806 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12807 /// later.
12808 ///
12809 /// This routine should be used for all diagnostics that describe the run-time
12810 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12811 /// Failure to do so will likely result in spurious diagnostics or failures
12812 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12813 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12814                                const PartialDiagnostic &PD) {
12815   switch (ExprEvalContexts.back().Context) {
12816   case Unevaluated:
12817   case UnevaluatedAbstract:
12818     // The argument will never be evaluated, so don't complain.
12819     break;
12820 
12821   case ConstantEvaluated:
12822     // Relevant diagnostics should be produced by constant evaluation.
12823     break;
12824 
12825   case PotentiallyEvaluated:
12826   case PotentiallyEvaluatedIfUsed:
12827     if (Statement && getCurFunctionOrMethodDecl()) {
12828       FunctionScopes.back()->PossiblyUnreachableDiags.
12829         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12830     }
12831     else
12832       Diag(Loc, PD);
12833       
12834     return true;
12835   }
12836 
12837   return false;
12838 }
12839 
12840 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12841                                CallExpr *CE, FunctionDecl *FD) {
12842   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12843     return false;
12844 
12845   // If we're inside a decltype's expression, don't check for a valid return
12846   // type or construct temporaries until we know whether this is the last call.
12847   if (ExprEvalContexts.back().IsDecltype) {
12848     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12849     return false;
12850   }
12851 
12852   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12853     FunctionDecl *FD;
12854     CallExpr *CE;
12855     
12856   public:
12857     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12858       : FD(FD), CE(CE) { }
12859 
12860     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12861       if (!FD) {
12862         S.Diag(Loc, diag::err_call_incomplete_return)
12863           << T << CE->getSourceRange();
12864         return;
12865       }
12866       
12867       S.Diag(Loc, diag::err_call_function_incomplete_return)
12868         << CE->getSourceRange() << FD->getDeclName() << T;
12869       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12870           << FD->getDeclName();
12871     }
12872   } Diagnoser(FD, CE);
12873   
12874   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12875     return true;
12876 
12877   return false;
12878 }
12879 
12880 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12881 // will prevent this condition from triggering, which is what we want.
12882 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12883   SourceLocation Loc;
12884 
12885   unsigned diagnostic = diag::warn_condition_is_assignment;
12886   bool IsOrAssign = false;
12887 
12888   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12889     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12890       return;
12891 
12892     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12893 
12894     // Greylist some idioms by putting them into a warning subcategory.
12895     if (ObjCMessageExpr *ME
12896           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12897       Selector Sel = ME->getSelector();
12898 
12899       // self = [<foo> init...]
12900       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12901         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12902 
12903       // <foo> = [<bar> nextObject]
12904       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12905         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12906     }
12907 
12908     Loc = Op->getOperatorLoc();
12909   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12910     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12911       return;
12912 
12913     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12914     Loc = Op->getOperatorLoc();
12915   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12916     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12917   else {
12918     // Not an assignment.
12919     return;
12920   }
12921 
12922   Diag(Loc, diagnostic) << E->getSourceRange();
12923 
12924   SourceLocation Open = E->getLocStart();
12925   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12926   Diag(Loc, diag::note_condition_assign_silence)
12927         << FixItHint::CreateInsertion(Open, "(")
12928         << FixItHint::CreateInsertion(Close, ")");
12929 
12930   if (IsOrAssign)
12931     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12932       << FixItHint::CreateReplacement(Loc, "!=");
12933   else
12934     Diag(Loc, diag::note_condition_assign_to_comparison)
12935       << FixItHint::CreateReplacement(Loc, "==");
12936 }
12937 
12938 /// \brief Redundant parentheses over an equality comparison can indicate
12939 /// that the user intended an assignment used as condition.
12940 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12941   // Don't warn if the parens came from a macro.
12942   SourceLocation parenLoc = ParenE->getLocStart();
12943   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12944     return;
12945   // Don't warn for dependent expressions.
12946   if (ParenE->isTypeDependent())
12947     return;
12948 
12949   Expr *E = ParenE->IgnoreParens();
12950 
12951   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12952     if (opE->getOpcode() == BO_EQ &&
12953         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12954                                                            == Expr::MLV_Valid) {
12955       SourceLocation Loc = opE->getOperatorLoc();
12956       
12957       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12958       SourceRange ParenERange = ParenE->getSourceRange();
12959       Diag(Loc, diag::note_equality_comparison_silence)
12960         << FixItHint::CreateRemoval(ParenERange.getBegin())
12961         << FixItHint::CreateRemoval(ParenERange.getEnd());
12962       Diag(Loc, diag::note_equality_comparison_to_assign)
12963         << FixItHint::CreateReplacement(Loc, "=");
12964     }
12965 }
12966 
12967 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12968   DiagnoseAssignmentAsCondition(E);
12969   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12970     DiagnoseEqualityWithExtraParens(parenE);
12971 
12972   ExprResult result = CheckPlaceholderExpr(E);
12973   if (result.isInvalid()) return ExprError();
12974   E = result.get();
12975 
12976   if (!E->isTypeDependent()) {
12977     if (getLangOpts().CPlusPlus)
12978       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12979 
12980     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12981     if (ERes.isInvalid())
12982       return ExprError();
12983     E = ERes.get();
12984 
12985     QualType T = E->getType();
12986     if (!T->isScalarType()) { // C99 6.8.4.1p1
12987       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12988         << T << E->getSourceRange();
12989       return ExprError();
12990     }
12991     CheckBoolLikeConversion(E, Loc);
12992   }
12993 
12994   return E;
12995 }
12996 
12997 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12998                                        Expr *SubExpr) {
12999   if (!SubExpr)
13000     return ExprError();
13001 
13002   return CheckBooleanCondition(SubExpr, Loc);
13003 }
13004 
13005 namespace {
13006   /// A visitor for rebuilding a call to an __unknown_any expression
13007   /// to have an appropriate type.
13008   struct RebuildUnknownAnyFunction
13009     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13010 
13011     Sema &S;
13012 
13013     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13014 
13015     ExprResult VisitStmt(Stmt *S) {
13016       llvm_unreachable("unexpected statement!");
13017     }
13018 
13019     ExprResult VisitExpr(Expr *E) {
13020       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13021         << E->getSourceRange();
13022       return ExprError();
13023     }
13024 
13025     /// Rebuild an expression which simply semantically wraps another
13026     /// expression which it shares the type and value kind of.
13027     template <class T> ExprResult rebuildSugarExpr(T *E) {
13028       ExprResult SubResult = Visit(E->getSubExpr());
13029       if (SubResult.isInvalid()) return ExprError();
13030 
13031       Expr *SubExpr = SubResult.get();
13032       E->setSubExpr(SubExpr);
13033       E->setType(SubExpr->getType());
13034       E->setValueKind(SubExpr->getValueKind());
13035       assert(E->getObjectKind() == OK_Ordinary);
13036       return E;
13037     }
13038 
13039     ExprResult VisitParenExpr(ParenExpr *E) {
13040       return rebuildSugarExpr(E);
13041     }
13042 
13043     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13044       return rebuildSugarExpr(E);
13045     }
13046 
13047     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13048       ExprResult SubResult = Visit(E->getSubExpr());
13049       if (SubResult.isInvalid()) return ExprError();
13050 
13051       Expr *SubExpr = SubResult.get();
13052       E->setSubExpr(SubExpr);
13053       E->setType(S.Context.getPointerType(SubExpr->getType()));
13054       assert(E->getValueKind() == VK_RValue);
13055       assert(E->getObjectKind() == OK_Ordinary);
13056       return E;
13057     }
13058 
13059     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13060       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13061 
13062       E->setType(VD->getType());
13063 
13064       assert(E->getValueKind() == VK_RValue);
13065       if (S.getLangOpts().CPlusPlus &&
13066           !(isa<CXXMethodDecl>(VD) &&
13067             cast<CXXMethodDecl>(VD)->isInstance()))
13068         E->setValueKind(VK_LValue);
13069 
13070       return E;
13071     }
13072 
13073     ExprResult VisitMemberExpr(MemberExpr *E) {
13074       return resolveDecl(E, E->getMemberDecl());
13075     }
13076 
13077     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13078       return resolveDecl(E, E->getDecl());
13079     }
13080   };
13081 }
13082 
13083 /// Given a function expression of unknown-any type, try to rebuild it
13084 /// to have a function type.
13085 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13086   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13087   if (Result.isInvalid()) return ExprError();
13088   return S.DefaultFunctionArrayConversion(Result.get());
13089 }
13090 
13091 namespace {
13092   /// A visitor for rebuilding an expression of type __unknown_anytype
13093   /// into one which resolves the type directly on the referring
13094   /// expression.  Strict preservation of the original source
13095   /// structure is not a goal.
13096   struct RebuildUnknownAnyExpr
13097     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13098 
13099     Sema &S;
13100 
13101     /// The current destination type.
13102     QualType DestType;
13103 
13104     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13105       : S(S), DestType(CastType) {}
13106 
13107     ExprResult VisitStmt(Stmt *S) {
13108       llvm_unreachable("unexpected statement!");
13109     }
13110 
13111     ExprResult VisitExpr(Expr *E) {
13112       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13113         << E->getSourceRange();
13114       return ExprError();
13115     }
13116 
13117     ExprResult VisitCallExpr(CallExpr *E);
13118     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13119 
13120     /// Rebuild an expression which simply semantically wraps another
13121     /// expression which it shares the type and value kind of.
13122     template <class T> ExprResult rebuildSugarExpr(T *E) {
13123       ExprResult SubResult = Visit(E->getSubExpr());
13124       if (SubResult.isInvalid()) return ExprError();
13125       Expr *SubExpr = SubResult.get();
13126       E->setSubExpr(SubExpr);
13127       E->setType(SubExpr->getType());
13128       E->setValueKind(SubExpr->getValueKind());
13129       assert(E->getObjectKind() == OK_Ordinary);
13130       return E;
13131     }
13132 
13133     ExprResult VisitParenExpr(ParenExpr *E) {
13134       return rebuildSugarExpr(E);
13135     }
13136 
13137     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13138       return rebuildSugarExpr(E);
13139     }
13140 
13141     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13142       const PointerType *Ptr = DestType->getAs<PointerType>();
13143       if (!Ptr) {
13144         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13145           << E->getSourceRange();
13146         return ExprError();
13147       }
13148       assert(E->getValueKind() == VK_RValue);
13149       assert(E->getObjectKind() == OK_Ordinary);
13150       E->setType(DestType);
13151 
13152       // Build the sub-expression as if it were an object of the pointee type.
13153       DestType = Ptr->getPointeeType();
13154       ExprResult SubResult = Visit(E->getSubExpr());
13155       if (SubResult.isInvalid()) return ExprError();
13156       E->setSubExpr(SubResult.get());
13157       return E;
13158     }
13159 
13160     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13161 
13162     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13163 
13164     ExprResult VisitMemberExpr(MemberExpr *E) {
13165       return resolveDecl(E, E->getMemberDecl());
13166     }
13167 
13168     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13169       return resolveDecl(E, E->getDecl());
13170     }
13171   };
13172 }
13173 
13174 /// Rebuilds a call expression which yielded __unknown_anytype.
13175 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13176   Expr *CalleeExpr = E->getCallee();
13177 
13178   enum FnKind {
13179     FK_MemberFunction,
13180     FK_FunctionPointer,
13181     FK_BlockPointer
13182   };
13183 
13184   FnKind Kind;
13185   QualType CalleeType = CalleeExpr->getType();
13186   if (CalleeType == S.Context.BoundMemberTy) {
13187     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13188     Kind = FK_MemberFunction;
13189     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13190   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13191     CalleeType = Ptr->getPointeeType();
13192     Kind = FK_FunctionPointer;
13193   } else {
13194     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13195     Kind = FK_BlockPointer;
13196   }
13197   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13198 
13199   // Verify that this is a legal result type of a function.
13200   if (DestType->isArrayType() || DestType->isFunctionType()) {
13201     unsigned diagID = diag::err_func_returning_array_function;
13202     if (Kind == FK_BlockPointer)
13203       diagID = diag::err_block_returning_array_function;
13204 
13205     S.Diag(E->getExprLoc(), diagID)
13206       << DestType->isFunctionType() << DestType;
13207     return ExprError();
13208   }
13209 
13210   // Otherwise, go ahead and set DestType as the call's result.
13211   E->setType(DestType.getNonLValueExprType(S.Context));
13212   E->setValueKind(Expr::getValueKindForType(DestType));
13213   assert(E->getObjectKind() == OK_Ordinary);
13214 
13215   // Rebuild the function type, replacing the result type with DestType.
13216   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13217   if (Proto) {
13218     // __unknown_anytype(...) is a special case used by the debugger when
13219     // it has no idea what a function's signature is.
13220     //
13221     // We want to build this call essentially under the K&R
13222     // unprototyped rules, but making a FunctionNoProtoType in C++
13223     // would foul up all sorts of assumptions.  However, we cannot
13224     // simply pass all arguments as variadic arguments, nor can we
13225     // portably just call the function under a non-variadic type; see
13226     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13227     // However, it turns out that in practice it is generally safe to
13228     // call a function declared as "A foo(B,C,D);" under the prototype
13229     // "A foo(B,C,D,...);".  The only known exception is with the
13230     // Windows ABI, where any variadic function is implicitly cdecl
13231     // regardless of its normal CC.  Therefore we change the parameter
13232     // types to match the types of the arguments.
13233     //
13234     // This is a hack, but it is far superior to moving the
13235     // corresponding target-specific code from IR-gen to Sema/AST.
13236 
13237     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13238     SmallVector<QualType, 8> ArgTypes;
13239     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13240       ArgTypes.reserve(E->getNumArgs());
13241       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13242         Expr *Arg = E->getArg(i);
13243         QualType ArgType = Arg->getType();
13244         if (E->isLValue()) {
13245           ArgType = S.Context.getLValueReferenceType(ArgType);
13246         } else if (E->isXValue()) {
13247           ArgType = S.Context.getRValueReferenceType(ArgType);
13248         }
13249         ArgTypes.push_back(ArgType);
13250       }
13251       ParamTypes = ArgTypes;
13252     }
13253     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13254                                          Proto->getExtProtoInfo());
13255   } else {
13256     DestType = S.Context.getFunctionNoProtoType(DestType,
13257                                                 FnType->getExtInfo());
13258   }
13259 
13260   // Rebuild the appropriate pointer-to-function type.
13261   switch (Kind) { 
13262   case FK_MemberFunction:
13263     // Nothing to do.
13264     break;
13265 
13266   case FK_FunctionPointer:
13267     DestType = S.Context.getPointerType(DestType);
13268     break;
13269 
13270   case FK_BlockPointer:
13271     DestType = S.Context.getBlockPointerType(DestType);
13272     break;
13273   }
13274 
13275   // Finally, we can recurse.
13276   ExprResult CalleeResult = Visit(CalleeExpr);
13277   if (!CalleeResult.isUsable()) return ExprError();
13278   E->setCallee(CalleeResult.get());
13279 
13280   // Bind a temporary if necessary.
13281   return S.MaybeBindToTemporary(E);
13282 }
13283 
13284 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13285   // Verify that this is a legal result type of a call.
13286   if (DestType->isArrayType() || DestType->isFunctionType()) {
13287     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13288       << DestType->isFunctionType() << DestType;
13289     return ExprError();
13290   }
13291 
13292   // Rewrite the method result type if available.
13293   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13294     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13295     Method->setReturnType(DestType);
13296   }
13297 
13298   // Change the type of the message.
13299   E->setType(DestType.getNonReferenceType());
13300   E->setValueKind(Expr::getValueKindForType(DestType));
13301 
13302   return S.MaybeBindToTemporary(E);
13303 }
13304 
13305 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13306   // The only case we should ever see here is a function-to-pointer decay.
13307   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13308     assert(E->getValueKind() == VK_RValue);
13309     assert(E->getObjectKind() == OK_Ordinary);
13310   
13311     E->setType(DestType);
13312   
13313     // Rebuild the sub-expression as the pointee (function) type.
13314     DestType = DestType->castAs<PointerType>()->getPointeeType();
13315   
13316     ExprResult Result = Visit(E->getSubExpr());
13317     if (!Result.isUsable()) return ExprError();
13318   
13319     E->setSubExpr(Result.get());
13320     return E;
13321   } else if (E->getCastKind() == CK_LValueToRValue) {
13322     assert(E->getValueKind() == VK_RValue);
13323     assert(E->getObjectKind() == OK_Ordinary);
13324 
13325     assert(isa<BlockPointerType>(E->getType()));
13326 
13327     E->setType(DestType);
13328 
13329     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13330     DestType = S.Context.getLValueReferenceType(DestType);
13331 
13332     ExprResult Result = Visit(E->getSubExpr());
13333     if (!Result.isUsable()) return ExprError();
13334 
13335     E->setSubExpr(Result.get());
13336     return E;
13337   } else {
13338     llvm_unreachable("Unhandled cast type!");
13339   }
13340 }
13341 
13342 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13343   ExprValueKind ValueKind = VK_LValue;
13344   QualType Type = DestType;
13345 
13346   // We know how to make this work for certain kinds of decls:
13347 
13348   //  - functions
13349   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13350     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13351       DestType = Ptr->getPointeeType();
13352       ExprResult Result = resolveDecl(E, VD);
13353       if (Result.isInvalid()) return ExprError();
13354       return S.ImpCastExprToType(Result.get(), Type,
13355                                  CK_FunctionToPointerDecay, VK_RValue);
13356     }
13357 
13358     if (!Type->isFunctionType()) {
13359       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13360         << VD << E->getSourceRange();
13361       return ExprError();
13362     }
13363     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
13364       // We must match the FunctionDecl's type to the hack introduced in
13365       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
13366       // type. See the lengthy commentary in that routine.
13367       QualType FDT = FD->getType();
13368       const FunctionType *FnType = FDT->castAs<FunctionType>();
13369       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
13370       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13371       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
13372         SourceLocation Loc = FD->getLocation();
13373         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
13374                                       FD->getDeclContext(),
13375                                       Loc, Loc, FD->getNameInfo().getName(),
13376                                       DestType, FD->getTypeSourceInfo(),
13377                                       SC_None, false/*isInlineSpecified*/,
13378                                       FD->hasPrototype(),
13379                                       false/*isConstexprSpecified*/);
13380           
13381         if (FD->getQualifier())
13382           NewFD->setQualifierInfo(FD->getQualifierLoc());
13383 
13384         SmallVector<ParmVarDecl*, 16> Params;
13385         for (const auto &AI : FT->param_types()) {
13386           ParmVarDecl *Param =
13387             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
13388           Param->setScopeInfo(0, Params.size());
13389           Params.push_back(Param);
13390         }
13391         NewFD->setParams(Params);
13392         DRE->setDecl(NewFD);
13393         VD = DRE->getDecl();
13394       }
13395     }
13396 
13397     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13398       if (MD->isInstance()) {
13399         ValueKind = VK_RValue;
13400         Type = S.Context.BoundMemberTy;
13401       }
13402 
13403     // Function references aren't l-values in C.
13404     if (!S.getLangOpts().CPlusPlus)
13405       ValueKind = VK_RValue;
13406 
13407   //  - variables
13408   } else if (isa<VarDecl>(VD)) {
13409     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13410       Type = RefTy->getPointeeType();
13411     } else if (Type->isFunctionType()) {
13412       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13413         << VD << E->getSourceRange();
13414       return ExprError();
13415     }
13416 
13417   //  - nothing else
13418   } else {
13419     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13420       << VD << E->getSourceRange();
13421     return ExprError();
13422   }
13423 
13424   // Modifying the declaration like this is friendly to IR-gen but
13425   // also really dangerous.
13426   VD->setType(DestType);
13427   E->setType(Type);
13428   E->setValueKind(ValueKind);
13429   return E;
13430 }
13431 
13432 /// Check a cast of an unknown-any type.  We intentionally only
13433 /// trigger this for C-style casts.
13434 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13435                                      Expr *CastExpr, CastKind &CastKind,
13436                                      ExprValueKind &VK, CXXCastPath &Path) {
13437   // Rewrite the casted expression from scratch.
13438   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13439   if (!result.isUsable()) return ExprError();
13440 
13441   CastExpr = result.get();
13442   VK = CastExpr->getValueKind();
13443   CastKind = CK_NoOp;
13444 
13445   return CastExpr;
13446 }
13447 
13448 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13449   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13450 }
13451 
13452 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13453                                     Expr *arg, QualType &paramType) {
13454   // If the syntactic form of the argument is not an explicit cast of
13455   // any sort, just do default argument promotion.
13456   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13457   if (!castArg) {
13458     ExprResult result = DefaultArgumentPromotion(arg);
13459     if (result.isInvalid()) return ExprError();
13460     paramType = result.get()->getType();
13461     return result;
13462   }
13463 
13464   // Otherwise, use the type that was written in the explicit cast.
13465   assert(!arg->hasPlaceholderType());
13466   paramType = castArg->getTypeAsWritten();
13467 
13468   // Copy-initialize a parameter of that type.
13469   InitializedEntity entity =
13470     InitializedEntity::InitializeParameter(Context, paramType,
13471                                            /*consumed*/ false);
13472   return PerformCopyInitialization(entity, callLoc, arg);
13473 }
13474 
13475 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13476   Expr *orig = E;
13477   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13478   while (true) {
13479     E = E->IgnoreParenImpCasts();
13480     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13481       E = call->getCallee();
13482       diagID = diag::err_uncasted_call_of_unknown_any;
13483     } else {
13484       break;
13485     }
13486   }
13487 
13488   SourceLocation loc;
13489   NamedDecl *d;
13490   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13491     loc = ref->getLocation();
13492     d = ref->getDecl();
13493   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13494     loc = mem->getMemberLoc();
13495     d = mem->getMemberDecl();
13496   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13497     diagID = diag::err_uncasted_call_of_unknown_any;
13498     loc = msg->getSelectorStartLoc();
13499     d = msg->getMethodDecl();
13500     if (!d) {
13501       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13502         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13503         << orig->getSourceRange();
13504       return ExprError();
13505     }
13506   } else {
13507     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13508       << E->getSourceRange();
13509     return ExprError();
13510   }
13511 
13512   S.Diag(loc, diagID) << d << orig->getSourceRange();
13513 
13514   // Never recoverable.
13515   return ExprError();
13516 }
13517 
13518 /// Check for operands with placeholder types and complain if found.
13519 /// Returns true if there was an error and no recovery was possible.
13520 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13521   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13522   if (!placeholderType) return E;
13523 
13524   switch (placeholderType->getKind()) {
13525 
13526   // Overloaded expressions.
13527   case BuiltinType::Overload: {
13528     // Try to resolve a single function template specialization.
13529     // This is obligatory.
13530     ExprResult result = E;
13531     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13532       return result;
13533 
13534     // If that failed, try to recover with a call.
13535     } else {
13536       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13537                            /*complain*/ true);
13538       return result;
13539     }
13540   }
13541 
13542   // Bound member functions.
13543   case BuiltinType::BoundMember: {
13544     ExprResult result = E;
13545     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13546                          /*complain*/ true);
13547     return result;
13548   }
13549 
13550   // ARC unbridged casts.
13551   case BuiltinType::ARCUnbridgedCast: {
13552     Expr *realCast = stripARCUnbridgedCast(E);
13553     diagnoseARCUnbridgedCast(realCast);
13554     return realCast;
13555   }
13556 
13557   // Expressions of unknown type.
13558   case BuiltinType::UnknownAny:
13559     return diagnoseUnknownAnyExpr(*this, E);
13560 
13561   // Pseudo-objects.
13562   case BuiltinType::PseudoObject:
13563     return checkPseudoObjectRValue(E);
13564 
13565   case BuiltinType::BuiltinFn: {
13566     // Accept __noop without parens by implicitly converting it to a call expr.
13567     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13568     if (DRE) {
13569       auto *FD = cast<FunctionDecl>(DRE->getDecl());
13570       if (FD->getBuiltinID() == Builtin::BI__noop) {
13571         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13572                               CK_BuiltinFnToFnPtr).get();
13573         return new (Context) CallExpr(Context, E, None, Context.IntTy,
13574                                       VK_RValue, SourceLocation());
13575       }
13576     }
13577 
13578     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13579     return ExprError();
13580   }
13581 
13582   // Everything else should be impossible.
13583 #define BUILTIN_TYPE(Id, SingletonId) \
13584   case BuiltinType::Id:
13585 #define PLACEHOLDER_TYPE(Id, SingletonId)
13586 #include "clang/AST/BuiltinTypes.def"
13587     break;
13588   }
13589 
13590   llvm_unreachable("invalid placeholder type!");
13591 }
13592 
13593 bool Sema::CheckCaseExpression(Expr *E) {
13594   if (E->isTypeDependent())
13595     return true;
13596   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13597     return E->getType()->isIntegralOrEnumerationType();
13598   return false;
13599 }
13600 
13601 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13602 ExprResult
13603 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13604   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13605          "Unknown Objective-C Boolean value!");
13606   QualType BoolT = Context.ObjCBuiltinBoolTy;
13607   if (!Context.getBOOLDecl()) {
13608     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13609                         Sema::LookupOrdinaryName);
13610     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13611       NamedDecl *ND = Result.getFoundDecl();
13612       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
13613         Context.setBOOLDecl(TD);
13614     }
13615   }
13616   if (Context.getBOOLDecl())
13617     BoolT = Context.getBOOLType();
13618   return new (Context)
13619       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13620 }