1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109 
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122 
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130 
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137 
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142 
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158 
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161 
162   return Result;
163 }
164 
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173 
174     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178 
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187 
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192 
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196 
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198 
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203 
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209 
210     return;
211   }
212 
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216 
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220 
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230 
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247 
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256 
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260 
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272 
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276 
277   S.MaybeSuggestAddingStaticToDecl(Current);
278 
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282 
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285 
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293 
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316 
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323 
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329 
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
337         << D->getDeclName() << cast<VarDecl>(D)->getType();
338     }
339     return true;
340   }
341 
342   // See if this is a deleted function.
343   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
344     if (FD->isDeleted()) {
345       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
346       if (Ctor && Ctor->isInheritingConstructor())
347         Diag(Loc, diag::err_deleted_inherited_ctor_use)
348             << Ctor->getParent()
349             << Ctor->getInheritedConstructor().getConstructor()->getParent();
350       else
351         Diag(Loc, diag::err_deleted_function_use);
352       NoteDeletedFunction(FD);
353       return true;
354     }
355 
356     // If the function has a deduced return type, and we can't deduce it,
357     // then we can't use it either.
358     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
359         DeduceReturnType(FD, Loc))
360       return true;
361 
362     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
363       return true;
364 
365     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
366       return true;
367   }
368 
369   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
370   // Only the variables omp_in and omp_out are allowed in the combiner.
371   // Only the variables omp_priv and omp_orig are allowed in the
372   // initializer-clause.
373   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
374   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
375       isa<VarDecl>(D)) {
376     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
377         << getCurFunction()->HasOMPDeclareReductionCombiner;
378     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
379     return true;
380   }
381 
382   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
383                              ObjCPropertyAccess);
384 
385   DiagnoseUnusedOfDecl(*this, D, Loc);
386 
387   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
388 
389   return false;
390 }
391 
392 /// \brief Retrieve the message suffix that should be added to a
393 /// diagnostic complaining about the given function being deleted or
394 /// unavailable.
395 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
396   std::string Message;
397   if (FD->getAvailability(&Message))
398     return ": " + Message;
399 
400   return std::string();
401 }
402 
403 /// DiagnoseSentinelCalls - This routine checks whether a call or
404 /// message-send is to a declaration with the sentinel attribute, and
405 /// if so, it checks that the requirements of the sentinel are
406 /// satisfied.
407 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
408                                  ArrayRef<Expr *> Args) {
409   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
410   if (!attr)
411     return;
412 
413   // The number of formal parameters of the declaration.
414   unsigned numFormalParams;
415 
416   // The kind of declaration.  This is also an index into a %select in
417   // the diagnostic.
418   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
419 
420   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
421     numFormalParams = MD->param_size();
422     calleeType = CT_Method;
423   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
424     numFormalParams = FD->param_size();
425     calleeType = CT_Function;
426   } else if (isa<VarDecl>(D)) {
427     QualType type = cast<ValueDecl>(D)->getType();
428     const FunctionType *fn = nullptr;
429     if (const PointerType *ptr = type->getAs<PointerType>()) {
430       fn = ptr->getPointeeType()->getAs<FunctionType>();
431       if (!fn) return;
432       calleeType = CT_Function;
433     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
434       fn = ptr->getPointeeType()->castAs<FunctionType>();
435       calleeType = CT_Block;
436     } else {
437       return;
438     }
439 
440     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
441       numFormalParams = proto->getNumParams();
442     } else {
443       numFormalParams = 0;
444     }
445   } else {
446     return;
447   }
448 
449   // "nullPos" is the number of formal parameters at the end which
450   // effectively count as part of the variadic arguments.  This is
451   // useful if you would prefer to not have *any* formal parameters,
452   // but the language forces you to have at least one.
453   unsigned nullPos = attr->getNullPos();
454   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
455   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
456 
457   // The number of arguments which should follow the sentinel.
458   unsigned numArgsAfterSentinel = attr->getSentinel();
459 
460   // If there aren't enough arguments for all the formal parameters,
461   // the sentinel, and the args after the sentinel, complain.
462   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
463     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
464     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
465     return;
466   }
467 
468   // Otherwise, find the sentinel expression.
469   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
470   if (!sentinelExpr) return;
471   if (sentinelExpr->isValueDependent()) return;
472   if (Context.isSentinelNullExpr(sentinelExpr)) return;
473 
474   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
475   // or 'NULL' if those are actually defined in the context.  Only use
476   // 'nil' for ObjC methods, where it's much more likely that the
477   // variadic arguments form a list of object pointers.
478   SourceLocation MissingNilLoc
479     = getLocForEndOfToken(sentinelExpr->getLocEnd());
480   std::string NullValue;
481   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
482     NullValue = "nil";
483   else if (getLangOpts().CPlusPlus11)
484     NullValue = "nullptr";
485   else if (PP.isMacroDefined("NULL"))
486     NullValue = "NULL";
487   else
488     NullValue = "(void*) 0";
489 
490   if (MissingNilLoc.isInvalid())
491     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
492   else
493     Diag(MissingNilLoc, diag::warn_missing_sentinel)
494       << int(calleeType)
495       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
496   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
497 }
498 
499 SourceRange Sema::getExprRange(Expr *E) const {
500   return E ? E->getSourceRange() : SourceRange();
501 }
502 
503 //===----------------------------------------------------------------------===//
504 //  Standard Promotions and Conversions
505 //===----------------------------------------------------------------------===//
506 
507 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
508 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
509   // Handle any placeholder expressions which made it here.
510   if (E->getType()->isPlaceholderType()) {
511     ExprResult result = CheckPlaceholderExpr(E);
512     if (result.isInvalid()) return ExprError();
513     E = result.get();
514   }
515 
516   QualType Ty = E->getType();
517   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
518 
519   if (Ty->isFunctionType()) {
520     // If we are here, we are not calling a function but taking
521     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
522     if (getLangOpts().OpenCL) {
523       if (Diagnose)
524         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
525       return ExprError();
526     }
527 
528     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
531           return ExprError();
532 
533     E = ImpCastExprToType(E, Context.getPointerType(Ty),
534                           CK_FunctionToPointerDecay).get();
535   } else if (Ty->isArrayType()) {
536     // In C90 mode, arrays only promote to pointers if the array expression is
537     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538     // type 'array of type' is converted to an expression that has type 'pointer
539     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
540     // that has type 'array of type' ...".  The relevant change is "an lvalue"
541     // (C90) to "an expression" (C99).
542     //
543     // C++ 4.2p1:
544     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545     // T" can be converted to an rvalue of type "pointer to T".
546     //
547     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
548       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549                             CK_ArrayToPointerDecay).get();
550   }
551   return E;
552 }
553 
554 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
555   // Check to see if we are dereferencing a null pointer.  If so,
556   // and if not volatile-qualified, this is undefined behavior that the
557   // optimizer will delete, so warn about it.  People sometimes try to use this
558   // to get a deterministic trap and are surprised by clang's behavior.  This
559   // only handles the pattern "*null", which is a very syntactic check.
560   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
561     if (UO->getOpcode() == UO_Deref &&
562         UO->getSubExpr()->IgnoreParenCasts()->
563           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
564         !UO->getType().isVolatileQualified()) {
565     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
566                           S.PDiag(diag::warn_indirection_through_null)
567                             << UO->getSubExpr()->getSourceRange());
568     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
569                         S.PDiag(diag::note_indirection_through_null));
570   }
571 }
572 
573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574                                     SourceLocation AssignLoc,
575                                     const Expr* RHS) {
576   const ObjCIvarDecl *IV = OIRE->getDecl();
577   if (!IV)
578     return;
579 
580   DeclarationName MemberName = IV->getDeclName();
581   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582   if (!Member || !Member->isStr("isa"))
583     return;
584 
585   const Expr *Base = OIRE->getBase();
586   QualType BaseType = Base->getType();
587   if (OIRE->isArrow())
588     BaseType = BaseType->getPointeeType();
589   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591       ObjCInterfaceDecl *ClassDeclared = nullptr;
592       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593       if (!ClassDeclared->getSuperClass()
594           && (*ClassDeclared->ivar_begin()) == IV) {
595         if (RHS) {
596           NamedDecl *ObjectSetClass =
597             S.LookupSingleName(S.TUScope,
598                                &S.Context.Idents.get("object_setClass"),
599                                SourceLocation(), S.LookupOrdinaryName);
600           if (ObjectSetClass) {
601             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
602             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
603             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
604             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
605                                                      AssignLoc), ",") <<
606             FixItHint::CreateInsertion(RHSLocEnd, ")");
607           }
608           else
609             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
610         } else {
611           NamedDecl *ObjectGetClass =
612             S.LookupSingleName(S.TUScope,
613                                &S.Context.Idents.get("object_getClass"),
614                                SourceLocation(), S.LookupOrdinaryName);
615           if (ObjectGetClass)
616             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
617             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
618             FixItHint::CreateReplacement(
619                                          SourceRange(OIRE->getOpLoc(),
620                                                      OIRE->getLocEnd()), ")");
621           else
622             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
623         }
624         S.Diag(IV->getLocation(), diag::note_ivar_decl);
625       }
626     }
627 }
628 
629 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
630   // Handle any placeholder expressions which made it here.
631   if (E->getType()->isPlaceholderType()) {
632     ExprResult result = CheckPlaceholderExpr(E);
633     if (result.isInvalid()) return ExprError();
634     E = result.get();
635   }
636 
637   // C++ [conv.lval]p1:
638   //   A glvalue of a non-function, non-array type T can be
639   //   converted to a prvalue.
640   if (!E->isGLValue()) return E;
641 
642   QualType T = E->getType();
643   assert(!T.isNull() && "r-value conversion on typeless expression?");
644 
645   // We don't want to throw lvalue-to-rvalue casts on top of
646   // expressions of certain types in C++.
647   if (getLangOpts().CPlusPlus &&
648       (E->getType() == Context.OverloadTy ||
649        T->isDependentType() ||
650        T->isRecordType()))
651     return E;
652 
653   // The C standard is actually really unclear on this point, and
654   // DR106 tells us what the result should be but not why.  It's
655   // generally best to say that void types just doesn't undergo
656   // lvalue-to-rvalue at all.  Note that expressions of unqualified
657   // 'void' type are never l-values, but qualified void can be.
658   if (T->isVoidType())
659     return E;
660 
661   // OpenCL usually rejects direct accesses to values of 'half' type.
662   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
663       T->isHalfType()) {
664     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
665       << 0 << T;
666     return ExprError();
667   }
668 
669   CheckForNullPointerDereference(*this, E);
670   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
671     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
672                                      &Context.Idents.get("object_getClass"),
673                                      SourceLocation(), LookupOrdinaryName);
674     if (ObjectGetClass)
675       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
676         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
677         FixItHint::CreateReplacement(
678                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
679     else
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
681   }
682   else if (const ObjCIvarRefExpr *OIRE =
683             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
684     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
685 
686   // C++ [conv.lval]p1:
687   //   [...] If T is a non-class type, the type of the prvalue is the
688   //   cv-unqualified version of T. Otherwise, the type of the
689   //   rvalue is T.
690   //
691   // C99 6.3.2.1p2:
692   //   If the lvalue has qualified type, the value has the unqualified
693   //   version of the type of the lvalue; otherwise, the value has the
694   //   type of the lvalue.
695   if (T.hasQualifiers())
696     T = T.getUnqualifiedType();
697 
698   // Under the MS ABI, lock down the inheritance model now.
699   if (T->isMemberPointerType() &&
700       Context.getTargetInfo().getCXXABI().isMicrosoft())
701     (void)isCompleteType(E->getExprLoc(), T);
702 
703   UpdateMarkingForLValueToRValue(E);
704 
705   // Loading a __weak object implicitly retains the value, so we need a cleanup to
706   // balance that.
707   if (getLangOpts().ObjCAutoRefCount &&
708       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709     Cleanup.setExprNeedsCleanups(true);
710 
711   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
712                                             nullptr, VK_RValue);
713 
714   // C11 6.3.2.1p2:
715   //   ... if the lvalue has atomic type, the value has the non-atomic version
716   //   of the type of the lvalue ...
717   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
718     T = Atomic->getValueType().getUnqualifiedType();
719     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
720                                    nullptr, VK_RValue);
721   }
722 
723   return Res;
724 }
725 
726 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
727   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
728   if (Res.isInvalid())
729     return ExprError();
730   Res = DefaultLvalueConversion(Res.get());
731   if (Res.isInvalid())
732     return ExprError();
733   return Res;
734 }
735 
736 /// CallExprUnaryConversions - a special case of an unary conversion
737 /// performed on a function designator of a call expression.
738 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
739   QualType Ty = E->getType();
740   ExprResult Res = E;
741   // Only do implicit cast for a function type, but not for a pointer
742   // to function type.
743   if (Ty->isFunctionType()) {
744     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
745                             CK_FunctionToPointerDecay).get();
746     if (Res.isInvalid())
747       return ExprError();
748   }
749   Res = DefaultLvalueConversion(Res.get());
750   if (Res.isInvalid())
751     return ExprError();
752   return Res.get();
753 }
754 
755 /// UsualUnaryConversions - Performs various conversions that are common to most
756 /// operators (C99 6.3). The conversions of array and function types are
757 /// sometimes suppressed. For example, the array->pointer conversion doesn't
758 /// apply if the array is an argument to the sizeof or address (&) operators.
759 /// In these instances, this routine should *not* be called.
760 ExprResult Sema::UsualUnaryConversions(Expr *E) {
761   // First, convert to an r-value.
762   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
763   if (Res.isInvalid())
764     return ExprError();
765   E = Res.get();
766 
767   QualType Ty = E->getType();
768   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
769 
770   // Half FP have to be promoted to float unless it is natively supported
771   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
772     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
773 
774   // Try to perform integral promotions if the object has a theoretically
775   // promotable type.
776   if (Ty->isIntegralOrUnscopedEnumerationType()) {
777     // C99 6.3.1.1p2:
778     //
779     //   The following may be used in an expression wherever an int or
780     //   unsigned int may be used:
781     //     - an object or expression with an integer type whose integer
782     //       conversion rank is less than or equal to the rank of int
783     //       and unsigned int.
784     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
785     //
786     //   If an int can represent all values of the original type, the
787     //   value is converted to an int; otherwise, it is converted to an
788     //   unsigned int. These are called the integer promotions. All
789     //   other types are unchanged by the integer promotions.
790 
791     QualType PTy = Context.isPromotableBitField(E);
792     if (!PTy.isNull()) {
793       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
794       return E;
795     }
796     if (Ty->isPromotableIntegerType()) {
797       QualType PT = Context.getPromotedIntegerType(Ty);
798       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
799       return E;
800     }
801   }
802   return E;
803 }
804 
805 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
806 /// do not have a prototype. Arguments that have type float or __fp16
807 /// are promoted to double. All other argument types are converted by
808 /// UsualUnaryConversions().
809 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
810   QualType Ty = E->getType();
811   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
812 
813   ExprResult Res = UsualUnaryConversions(E);
814   if (Res.isInvalid())
815     return ExprError();
816   E = Res.get();
817 
818   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
819   // double.
820   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
821   if (BTy && (BTy->getKind() == BuiltinType::Half ||
822               BTy->getKind() == BuiltinType::Float)) {
823     if (getLangOpts().OpenCL &&
824         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
825         if (BTy->getKind() == BuiltinType::Half) {
826             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
827         }
828     } else {
829       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
830     }
831   }
832 
833   // C++ performs lvalue-to-rvalue conversion as a default argument
834   // promotion, even on class types, but note:
835   //   C++11 [conv.lval]p2:
836   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
837   //     operand or a subexpression thereof the value contained in the
838   //     referenced object is not accessed. Otherwise, if the glvalue
839   //     has a class type, the conversion copy-initializes a temporary
840   //     of type T from the glvalue and the result of the conversion
841   //     is a prvalue for the temporary.
842   // FIXME: add some way to gate this entire thing for correctness in
843   // potentially potentially evaluated contexts.
844   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
845     ExprResult Temp = PerformCopyInitialization(
846                        InitializedEntity::InitializeTemporary(E->getType()),
847                                                 E->getExprLoc(), E);
848     if (Temp.isInvalid())
849       return ExprError();
850     E = Temp.get();
851   }
852 
853   return E;
854 }
855 
856 /// Determine the degree of POD-ness for an expression.
857 /// Incomplete types are considered POD, since this check can be performed
858 /// when we're in an unevaluated context.
859 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
860   if (Ty->isIncompleteType()) {
861     // C++11 [expr.call]p7:
862     //   After these conversions, if the argument does not have arithmetic,
863     //   enumeration, pointer, pointer to member, or class type, the program
864     //   is ill-formed.
865     //
866     // Since we've already performed array-to-pointer and function-to-pointer
867     // decay, the only such type in C++ is cv void. This also handles
868     // initializer lists as variadic arguments.
869     if (Ty->isVoidType())
870       return VAK_Invalid;
871 
872     if (Ty->isObjCObjectType())
873       return VAK_Invalid;
874     return VAK_Valid;
875   }
876 
877   if (Ty.isCXX98PODType(Context))
878     return VAK_Valid;
879 
880   // C++11 [expr.call]p7:
881   //   Passing a potentially-evaluated argument of class type (Clause 9)
882   //   having a non-trivial copy constructor, a non-trivial move constructor,
883   //   or a non-trivial destructor, with no corresponding parameter,
884   //   is conditionally-supported with implementation-defined semantics.
885   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
886     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
887       if (!Record->hasNonTrivialCopyConstructor() &&
888           !Record->hasNonTrivialMoveConstructor() &&
889           !Record->hasNonTrivialDestructor())
890         return VAK_ValidInCXX11;
891 
892   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
893     return VAK_Valid;
894 
895   if (Ty->isObjCObjectType())
896     return VAK_Invalid;
897 
898   if (getLangOpts().MSVCCompat)
899     return VAK_MSVCUndefined;
900 
901   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
902   // permitted to reject them. We should consider doing so.
903   return VAK_Undefined;
904 }
905 
906 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
907   // Don't allow one to pass an Objective-C interface to a vararg.
908   const QualType &Ty = E->getType();
909   VarArgKind VAK = isValidVarArgType(Ty);
910 
911   // Complain about passing non-POD types through varargs.
912   switch (VAK) {
913   case VAK_ValidInCXX11:
914     DiagRuntimeBehavior(
915         E->getLocStart(), nullptr,
916         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
917           << Ty << CT);
918     // Fall through.
919   case VAK_Valid:
920     if (Ty->isRecordType()) {
921       // This is unlikely to be what the user intended. If the class has a
922       // 'c_str' member function, the user probably meant to call that.
923       DiagRuntimeBehavior(E->getLocStart(), nullptr,
924                           PDiag(diag::warn_pass_class_arg_to_vararg)
925                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
926     }
927     break;
928 
929   case VAK_Undefined:
930   case VAK_MSVCUndefined:
931     DiagRuntimeBehavior(
932         E->getLocStart(), nullptr,
933         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
934           << getLangOpts().CPlusPlus11 << Ty << CT);
935     break;
936 
937   case VAK_Invalid:
938     if (Ty->isObjCObjectType())
939       DiagRuntimeBehavior(
940           E->getLocStart(), nullptr,
941           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
942             << Ty << CT);
943     else
944       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
945         << isa<InitListExpr>(E) << Ty << CT;
946     break;
947   }
948 }
949 
950 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
951 /// will create a trap if the resulting type is not a POD type.
952 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
953                                                   FunctionDecl *FDecl) {
954   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
955     // Strip the unbridged-cast placeholder expression off, if applicable.
956     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
957         (CT == VariadicMethod ||
958          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
959       E = stripARCUnbridgedCast(E);
960 
961     // Otherwise, do normal placeholder checking.
962     } else {
963       ExprResult ExprRes = CheckPlaceholderExpr(E);
964       if (ExprRes.isInvalid())
965         return ExprError();
966       E = ExprRes.get();
967     }
968   }
969 
970   ExprResult ExprRes = DefaultArgumentPromotion(E);
971   if (ExprRes.isInvalid())
972     return ExprError();
973   E = ExprRes.get();
974 
975   // Diagnostics regarding non-POD argument types are
976   // emitted along with format string checking in Sema::CheckFunctionCall().
977   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
978     // Turn this into a trap.
979     CXXScopeSpec SS;
980     SourceLocation TemplateKWLoc;
981     UnqualifiedId Name;
982     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
983                        E->getLocStart());
984     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
985                                           Name, true, false);
986     if (TrapFn.isInvalid())
987       return ExprError();
988 
989     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
990                                     E->getLocStart(), None,
991                                     E->getLocEnd());
992     if (Call.isInvalid())
993       return ExprError();
994 
995     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
996                                   Call.get(), E);
997     if (Comma.isInvalid())
998       return ExprError();
999     return Comma.get();
1000   }
1001 
1002   if (!getLangOpts().CPlusPlus &&
1003       RequireCompleteType(E->getExprLoc(), E->getType(),
1004                           diag::err_call_incomplete_argument))
1005     return ExprError();
1006 
1007   return E;
1008 }
1009 
1010 /// \brief Converts an integer to complex float type.  Helper function of
1011 /// UsualArithmeticConversions()
1012 ///
1013 /// \return false if the integer expression is an integer type and is
1014 /// successfully converted to the complex type.
1015 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1016                                                   ExprResult &ComplexExpr,
1017                                                   QualType IntTy,
1018                                                   QualType ComplexTy,
1019                                                   bool SkipCast) {
1020   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1021   if (SkipCast) return false;
1022   if (IntTy->isIntegerType()) {
1023     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1024     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1025     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1026                                   CK_FloatingRealToComplex);
1027   } else {
1028     assert(IntTy->isComplexIntegerType());
1029     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030                                   CK_IntegralComplexToFloatingComplex);
1031   }
1032   return false;
1033 }
1034 
1035 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1036 /// UsualArithmeticConversions()
1037 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1038                                              ExprResult &RHS, QualType LHSType,
1039                                              QualType RHSType,
1040                                              bool IsCompAssign) {
1041   // if we have an integer operand, the result is the complex type.
1042   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1043                                              /*skipCast*/false))
1044     return LHSType;
1045   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1046                                              /*skipCast*/IsCompAssign))
1047     return RHSType;
1048 
1049   // This handles complex/complex, complex/float, or float/complex.
1050   // When both operands are complex, the shorter operand is converted to the
1051   // type of the longer, and that is the type of the result. This corresponds
1052   // to what is done when combining two real floating-point operands.
1053   // The fun begins when size promotion occur across type domains.
1054   // From H&S 6.3.4: When one operand is complex and the other is a real
1055   // floating-point type, the less precise type is converted, within it's
1056   // real or complex domain, to the precision of the other type. For example,
1057   // when combining a "long double" with a "double _Complex", the
1058   // "double _Complex" is promoted to "long double _Complex".
1059 
1060   // Compute the rank of the two types, regardless of whether they are complex.
1061   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1062 
1063   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1064   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1065   QualType LHSElementType =
1066       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1067   QualType RHSElementType =
1068       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1069 
1070   QualType ResultType = S.Context.getComplexType(LHSElementType);
1071   if (Order < 0) {
1072     // Promote the precision of the LHS if not an assignment.
1073     ResultType = S.Context.getComplexType(RHSElementType);
1074     if (!IsCompAssign) {
1075       if (LHSComplexType)
1076         LHS =
1077             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1078       else
1079         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1080     }
1081   } else if (Order > 0) {
1082     // Promote the precision of the RHS.
1083     if (RHSComplexType)
1084       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1085     else
1086       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1087   }
1088   return ResultType;
1089 }
1090 
1091 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1092 /// of UsualArithmeticConversions()
1093 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1094                                            ExprResult &IntExpr,
1095                                            QualType FloatTy, QualType IntTy,
1096                                            bool ConvertFloat, bool ConvertInt) {
1097   if (IntTy->isIntegerType()) {
1098     if (ConvertInt)
1099       // Convert intExpr to the lhs floating point type.
1100       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1101                                     CK_IntegralToFloating);
1102     return FloatTy;
1103   }
1104 
1105   // Convert both sides to the appropriate complex float.
1106   assert(IntTy->isComplexIntegerType());
1107   QualType result = S.Context.getComplexType(FloatTy);
1108 
1109   // _Complex int -> _Complex float
1110   if (ConvertInt)
1111     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1112                                   CK_IntegralComplexToFloatingComplex);
1113 
1114   // float -> _Complex float
1115   if (ConvertFloat)
1116     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1117                                     CK_FloatingRealToComplex);
1118 
1119   return result;
1120 }
1121 
1122 /// \brief Handle arithmethic conversion with floating point types.  Helper
1123 /// function of UsualArithmeticConversions()
1124 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1125                                       ExprResult &RHS, QualType LHSType,
1126                                       QualType RHSType, bool IsCompAssign) {
1127   bool LHSFloat = LHSType->isRealFloatingType();
1128   bool RHSFloat = RHSType->isRealFloatingType();
1129 
1130   // If we have two real floating types, convert the smaller operand
1131   // to the bigger result.
1132   if (LHSFloat && RHSFloat) {
1133     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1134     if (order > 0) {
1135       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1136       return LHSType;
1137     }
1138 
1139     assert(order < 0 && "illegal float comparison");
1140     if (!IsCompAssign)
1141       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1142     return RHSType;
1143   }
1144 
1145   if (LHSFloat) {
1146     // Half FP has to be promoted to float unless it is natively supported
1147     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1148       LHSType = S.Context.FloatTy;
1149 
1150     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1151                                       /*convertFloat=*/!IsCompAssign,
1152                                       /*convertInt=*/ true);
1153   }
1154   assert(RHSFloat);
1155   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1156                                     /*convertInt=*/ true,
1157                                     /*convertFloat=*/!IsCompAssign);
1158 }
1159 
1160 /// \brief Diagnose attempts to convert between __float128 and long double if
1161 /// there is no support for such conversion. Helper function of
1162 /// UsualArithmeticConversions().
1163 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1164                                       QualType RHSType) {
1165   /*  No issue converting if at least one of the types is not a floating point
1166       type or the two types have the same rank.
1167   */
1168   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1169       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1170     return false;
1171 
1172   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1173          "The remaining types must be floating point types.");
1174 
1175   auto *LHSComplex = LHSType->getAs<ComplexType>();
1176   auto *RHSComplex = RHSType->getAs<ComplexType>();
1177 
1178   QualType LHSElemType = LHSComplex ?
1179     LHSComplex->getElementType() : LHSType;
1180   QualType RHSElemType = RHSComplex ?
1181     RHSComplex->getElementType() : RHSType;
1182 
1183   // No issue if the two types have the same representation
1184   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1185       &S.Context.getFloatTypeSemantics(RHSElemType))
1186     return false;
1187 
1188   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1189                                 RHSElemType == S.Context.LongDoubleTy);
1190   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1191                             RHSElemType == S.Context.Float128Ty);
1192 
1193   /* We've handled the situation where __float128 and long double have the same
1194      representation. The only other allowable conversion is if long double is
1195      really just double.
1196   */
1197   return Float128AndLongDouble &&
1198     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1199      &llvm::APFloat::IEEEdouble());
1200 }
1201 
1202 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1203 
1204 namespace {
1205 /// These helper callbacks are placed in an anonymous namespace to
1206 /// permit their use as function template parameters.
1207 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1208   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1209 }
1210 
1211 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1212   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1213                              CK_IntegralComplexCast);
1214 }
1215 }
1216 
1217 /// \brief Handle integer arithmetic conversions.  Helper function of
1218 /// UsualArithmeticConversions()
1219 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1220 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1221                                         ExprResult &RHS, QualType LHSType,
1222                                         QualType RHSType, bool IsCompAssign) {
1223   // The rules for this case are in C99 6.3.1.8
1224   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1225   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1226   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1227   if (LHSSigned == RHSSigned) {
1228     // Same signedness; use the higher-ranked type
1229     if (order >= 0) {
1230       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1231       return LHSType;
1232     } else if (!IsCompAssign)
1233       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1234     return RHSType;
1235   } else if (order != (LHSSigned ? 1 : -1)) {
1236     // The unsigned type has greater than or equal rank to the
1237     // signed type, so use the unsigned type
1238     if (RHSSigned) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1245     // The two types are different widths; if we are here, that
1246     // means the signed type is larger than the unsigned type, so
1247     // use the signed type.
1248     if (LHSSigned) {
1249       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1250       return LHSType;
1251     } else if (!IsCompAssign)
1252       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1253     return RHSType;
1254   } else {
1255     // The signed type is higher-ranked than the unsigned type,
1256     // but isn't actually any bigger (like unsigned int and long
1257     // on most 32-bit systems).  Use the unsigned type corresponding
1258     // to the signed type.
1259     QualType result =
1260       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1261     RHS = (*doRHSCast)(S, RHS.get(), result);
1262     if (!IsCompAssign)
1263       LHS = (*doLHSCast)(S, LHS.get(), result);
1264     return result;
1265   }
1266 }
1267 
1268 /// \brief Handle conversions with GCC complex int extension.  Helper function
1269 /// of UsualArithmeticConversions()
1270 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1271                                            ExprResult &RHS, QualType LHSType,
1272                                            QualType RHSType,
1273                                            bool IsCompAssign) {
1274   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1275   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1276 
1277   if (LHSComplexInt && RHSComplexInt) {
1278     QualType LHSEltType = LHSComplexInt->getElementType();
1279     QualType RHSEltType = RHSComplexInt->getElementType();
1280     QualType ScalarType =
1281       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1282         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1283 
1284     return S.Context.getComplexType(ScalarType);
1285   }
1286 
1287   if (LHSComplexInt) {
1288     QualType LHSEltType = LHSComplexInt->getElementType();
1289     QualType ScalarType =
1290       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1291         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1292     QualType ComplexType = S.Context.getComplexType(ScalarType);
1293     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1294                               CK_IntegralRealToComplex);
1295 
1296     return ComplexType;
1297   }
1298 
1299   assert(RHSComplexInt);
1300 
1301   QualType RHSEltType = RHSComplexInt->getElementType();
1302   QualType ScalarType =
1303     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1304       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1305   QualType ComplexType = S.Context.getComplexType(ScalarType);
1306 
1307   if (!IsCompAssign)
1308     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1309                               CK_IntegralRealToComplex);
1310   return ComplexType;
1311 }
1312 
1313 /// UsualArithmeticConversions - Performs various conversions that are common to
1314 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1315 /// routine returns the first non-arithmetic type found. The client is
1316 /// responsible for emitting appropriate error diagnostics.
1317 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1318                                           bool IsCompAssign) {
1319   if (!IsCompAssign) {
1320     LHS = UsualUnaryConversions(LHS.get());
1321     if (LHS.isInvalid())
1322       return QualType();
1323   }
1324 
1325   RHS = UsualUnaryConversions(RHS.get());
1326   if (RHS.isInvalid())
1327     return QualType();
1328 
1329   // For conversion purposes, we ignore any qualifiers.
1330   // For example, "const float" and "float" are equivalent.
1331   QualType LHSType =
1332     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1333   QualType RHSType =
1334     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1335 
1336   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1337   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1338     LHSType = AtomicLHS->getValueType();
1339 
1340   // If both types are identical, no conversion is needed.
1341   if (LHSType == RHSType)
1342     return LHSType;
1343 
1344   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1345   // The caller can deal with this (e.g. pointer + int).
1346   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1347     return QualType();
1348 
1349   // Apply unary and bitfield promotions to the LHS's type.
1350   QualType LHSUnpromotedType = LHSType;
1351   if (LHSType->isPromotableIntegerType())
1352     LHSType = Context.getPromotedIntegerType(LHSType);
1353   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1354   if (!LHSBitfieldPromoteTy.isNull())
1355     LHSType = LHSBitfieldPromoteTy;
1356   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1357     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1358 
1359   // If both types are identical, no conversion is needed.
1360   if (LHSType == RHSType)
1361     return LHSType;
1362 
1363   // At this point, we have two different arithmetic types.
1364 
1365   // Diagnose attempts to convert between __float128 and long double where
1366   // such conversions currently can't be handled.
1367   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1368     return QualType();
1369 
1370   // Handle complex types first (C99 6.3.1.8p1).
1371   if (LHSType->isComplexType() || RHSType->isComplexType())
1372     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1373                                         IsCompAssign);
1374 
1375   // Now handle "real" floating types (i.e. float, double, long double).
1376   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1377     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1378                                  IsCompAssign);
1379 
1380   // Handle GCC complex int extension.
1381   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1382     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1383                                       IsCompAssign);
1384 
1385   // Finally, we have two differing integer types.
1386   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1387            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1388 }
1389 
1390 
1391 //===----------------------------------------------------------------------===//
1392 //  Semantic Analysis for various Expression Types
1393 //===----------------------------------------------------------------------===//
1394 
1395 
1396 ExprResult
1397 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1398                                 SourceLocation DefaultLoc,
1399                                 SourceLocation RParenLoc,
1400                                 Expr *ControllingExpr,
1401                                 ArrayRef<ParsedType> ArgTypes,
1402                                 ArrayRef<Expr *> ArgExprs) {
1403   unsigned NumAssocs = ArgTypes.size();
1404   assert(NumAssocs == ArgExprs.size());
1405 
1406   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1407   for (unsigned i = 0; i < NumAssocs; ++i) {
1408     if (ArgTypes[i])
1409       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1410     else
1411       Types[i] = nullptr;
1412   }
1413 
1414   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1415                                              ControllingExpr,
1416                                              llvm::makeArrayRef(Types, NumAssocs),
1417                                              ArgExprs);
1418   delete [] Types;
1419   return ER;
1420 }
1421 
1422 ExprResult
1423 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1424                                  SourceLocation DefaultLoc,
1425                                  SourceLocation RParenLoc,
1426                                  Expr *ControllingExpr,
1427                                  ArrayRef<TypeSourceInfo *> Types,
1428                                  ArrayRef<Expr *> Exprs) {
1429   unsigned NumAssocs = Types.size();
1430   assert(NumAssocs == Exprs.size());
1431 
1432   // Decay and strip qualifiers for the controlling expression type, and handle
1433   // placeholder type replacement. See committee discussion from WG14 DR423.
1434   {
1435     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1436     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1437     if (R.isInvalid())
1438       return ExprError();
1439     ControllingExpr = R.get();
1440   }
1441 
1442   // The controlling expression is an unevaluated operand, so side effects are
1443   // likely unintended.
1444   if (!inTemplateInstantiation() &&
1445       ControllingExpr->HasSideEffects(Context, false))
1446     Diag(ControllingExpr->getExprLoc(),
1447          diag::warn_side_effects_unevaluated_context);
1448 
1449   bool TypeErrorFound = false,
1450        IsResultDependent = ControllingExpr->isTypeDependent(),
1451        ContainsUnexpandedParameterPack
1452          = ControllingExpr->containsUnexpandedParameterPack();
1453 
1454   for (unsigned i = 0; i < NumAssocs; ++i) {
1455     if (Exprs[i]->containsUnexpandedParameterPack())
1456       ContainsUnexpandedParameterPack = true;
1457 
1458     if (Types[i]) {
1459       if (Types[i]->getType()->containsUnexpandedParameterPack())
1460         ContainsUnexpandedParameterPack = true;
1461 
1462       if (Types[i]->getType()->isDependentType()) {
1463         IsResultDependent = true;
1464       } else {
1465         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1466         // complete object type other than a variably modified type."
1467         unsigned D = 0;
1468         if (Types[i]->getType()->isIncompleteType())
1469           D = diag::err_assoc_type_incomplete;
1470         else if (!Types[i]->getType()->isObjectType())
1471           D = diag::err_assoc_type_nonobject;
1472         else if (Types[i]->getType()->isVariablyModifiedType())
1473           D = diag::err_assoc_type_variably_modified;
1474 
1475         if (D != 0) {
1476           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1477             << Types[i]->getTypeLoc().getSourceRange()
1478             << Types[i]->getType();
1479           TypeErrorFound = true;
1480         }
1481 
1482         // C11 6.5.1.1p2 "No two generic associations in the same generic
1483         // selection shall specify compatible types."
1484         for (unsigned j = i+1; j < NumAssocs; ++j)
1485           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1486               Context.typesAreCompatible(Types[i]->getType(),
1487                                          Types[j]->getType())) {
1488             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1489                  diag::err_assoc_compatible_types)
1490               << Types[j]->getTypeLoc().getSourceRange()
1491               << Types[j]->getType()
1492               << Types[i]->getType();
1493             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1494                  diag::note_compat_assoc)
1495               << Types[i]->getTypeLoc().getSourceRange()
1496               << Types[i]->getType();
1497             TypeErrorFound = true;
1498           }
1499       }
1500     }
1501   }
1502   if (TypeErrorFound)
1503     return ExprError();
1504 
1505   // If we determined that the generic selection is result-dependent, don't
1506   // try to compute the result expression.
1507   if (IsResultDependent)
1508     return new (Context) GenericSelectionExpr(
1509         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1510         ContainsUnexpandedParameterPack);
1511 
1512   SmallVector<unsigned, 1> CompatIndices;
1513   unsigned DefaultIndex = -1U;
1514   for (unsigned i = 0; i < NumAssocs; ++i) {
1515     if (!Types[i])
1516       DefaultIndex = i;
1517     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1518                                         Types[i]->getType()))
1519       CompatIndices.push_back(i);
1520   }
1521 
1522   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1523   // type compatible with at most one of the types named in its generic
1524   // association list."
1525   if (CompatIndices.size() > 1) {
1526     // We strip parens here because the controlling expression is typically
1527     // parenthesized in macro definitions.
1528     ControllingExpr = ControllingExpr->IgnoreParens();
1529     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1530       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1531       << (unsigned) CompatIndices.size();
1532     for (unsigned I : CompatIndices) {
1533       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1534            diag::note_compat_assoc)
1535         << Types[I]->getTypeLoc().getSourceRange()
1536         << Types[I]->getType();
1537     }
1538     return ExprError();
1539   }
1540 
1541   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1542   // its controlling expression shall have type compatible with exactly one of
1543   // the types named in its generic association list."
1544   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1545     // We strip parens here because the controlling expression is typically
1546     // parenthesized in macro definitions.
1547     ControllingExpr = ControllingExpr->IgnoreParens();
1548     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1549       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1550     return ExprError();
1551   }
1552 
1553   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1554   // type name that is compatible with the type of the controlling expression,
1555   // then the result expression of the generic selection is the expression
1556   // in that generic association. Otherwise, the result expression of the
1557   // generic selection is the expression in the default generic association."
1558   unsigned ResultIndex =
1559     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1560 
1561   return new (Context) GenericSelectionExpr(
1562       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1563       ContainsUnexpandedParameterPack, ResultIndex);
1564 }
1565 
1566 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1567 /// location of the token and the offset of the ud-suffix within it.
1568 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1569                                      unsigned Offset) {
1570   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1571                                         S.getLangOpts());
1572 }
1573 
1574 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1575 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1576 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1577                                                  IdentifierInfo *UDSuffix,
1578                                                  SourceLocation UDSuffixLoc,
1579                                                  ArrayRef<Expr*> Args,
1580                                                  SourceLocation LitEndLoc) {
1581   assert(Args.size() <= 2 && "too many arguments for literal operator");
1582 
1583   QualType ArgTy[2];
1584   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1585     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1586     if (ArgTy[ArgIdx]->isArrayType())
1587       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1588   }
1589 
1590   DeclarationName OpName =
1591     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1592   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1593   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1594 
1595   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1596   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1597                               /*AllowRaw*/false, /*AllowTemplate*/false,
1598                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1599     return ExprError();
1600 
1601   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1602 }
1603 
1604 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1605 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1606 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1607 /// multiple tokens.  However, the common case is that StringToks points to one
1608 /// string.
1609 ///
1610 ExprResult
1611 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1612   assert(!StringToks.empty() && "Must have at least one string!");
1613 
1614   StringLiteralParser Literal(StringToks, PP);
1615   if (Literal.hadError)
1616     return ExprError();
1617 
1618   SmallVector<SourceLocation, 4> StringTokLocs;
1619   for (const Token &Tok : StringToks)
1620     StringTokLocs.push_back(Tok.getLocation());
1621 
1622   QualType CharTy = Context.CharTy;
1623   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1624   if (Literal.isWide()) {
1625     CharTy = Context.getWideCharType();
1626     Kind = StringLiteral::Wide;
1627   } else if (Literal.isUTF8()) {
1628     Kind = StringLiteral::UTF8;
1629   } else if (Literal.isUTF16()) {
1630     CharTy = Context.Char16Ty;
1631     Kind = StringLiteral::UTF16;
1632   } else if (Literal.isUTF32()) {
1633     CharTy = Context.Char32Ty;
1634     Kind = StringLiteral::UTF32;
1635   } else if (Literal.isPascal()) {
1636     CharTy = Context.UnsignedCharTy;
1637   }
1638 
1639   QualType CharTyConst = CharTy;
1640   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1641   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1642     CharTyConst.addConst();
1643 
1644   // Get an array type for the string, according to C99 6.4.5.  This includes
1645   // the nul terminator character as well as the string length for pascal
1646   // strings.
1647   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1648                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1649                                  ArrayType::Normal, 0);
1650 
1651   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1652   if (getLangOpts().OpenCL) {
1653     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1654   }
1655 
1656   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1657   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1658                                              Kind, Literal.Pascal, StrTy,
1659                                              &StringTokLocs[0],
1660                                              StringTokLocs.size());
1661   if (Literal.getUDSuffix().empty())
1662     return Lit;
1663 
1664   // We're building a user-defined literal.
1665   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1666   SourceLocation UDSuffixLoc =
1667     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1668                    Literal.getUDSuffixOffset());
1669 
1670   // Make sure we're allowed user-defined literals here.
1671   if (!UDLScope)
1672     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1673 
1674   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1675   //   operator "" X (str, len)
1676   QualType SizeType = Context.getSizeType();
1677 
1678   DeclarationName OpName =
1679     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1680   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1681   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1682 
1683   QualType ArgTy[] = {
1684     Context.getArrayDecayedType(StrTy), SizeType
1685   };
1686 
1687   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1688   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1689                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1690                                 /*AllowStringTemplate*/true)) {
1691 
1692   case LOLR_Cooked: {
1693     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1694     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1695                                                     StringTokLocs[0]);
1696     Expr *Args[] = { Lit, LenArg };
1697 
1698     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1699   }
1700 
1701   case LOLR_StringTemplate: {
1702     TemplateArgumentListInfo ExplicitArgs;
1703 
1704     unsigned CharBits = Context.getIntWidth(CharTy);
1705     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1706     llvm::APSInt Value(CharBits, CharIsUnsigned);
1707 
1708     TemplateArgument TypeArg(CharTy);
1709     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1710     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1711 
1712     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1713       Value = Lit->getCodeUnit(I);
1714       TemplateArgument Arg(Context, Value, CharTy);
1715       TemplateArgumentLocInfo ArgInfo;
1716       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1717     }
1718     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1719                                     &ExplicitArgs);
1720   }
1721   case LOLR_Raw:
1722   case LOLR_Template:
1723     llvm_unreachable("unexpected literal operator lookup result");
1724   case LOLR_Error:
1725     return ExprError();
1726   }
1727   llvm_unreachable("unexpected literal operator lookup result");
1728 }
1729 
1730 ExprResult
1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1732                        SourceLocation Loc,
1733                        const CXXScopeSpec *SS) {
1734   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1735   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1736 }
1737 
1738 /// BuildDeclRefExpr - Build an expression that references a
1739 /// declaration that does not require a closure capture.
1740 ExprResult
1741 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1742                        const DeclarationNameInfo &NameInfo,
1743                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1744                        const TemplateArgumentListInfo *TemplateArgs) {
1745   bool RefersToCapturedVariable =
1746       isa<VarDecl>(D) &&
1747       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1748 
1749   DeclRefExpr *E;
1750   if (isa<VarTemplateSpecializationDecl>(D)) {
1751     VarTemplateSpecializationDecl *VarSpec =
1752         cast<VarTemplateSpecializationDecl>(D);
1753 
1754     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1755                                         : NestedNameSpecifierLoc(),
1756                             VarSpec->getTemplateKeywordLoc(), D,
1757                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1758                             FoundD, TemplateArgs);
1759   } else {
1760     assert(!TemplateArgs && "No template arguments for non-variable"
1761                             " template specialization references");
1762     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1763                                         : NestedNameSpecifierLoc(),
1764                             SourceLocation(), D, RefersToCapturedVariable,
1765                             NameInfo, Ty, VK, FoundD);
1766   }
1767 
1768   MarkDeclRefReferenced(E);
1769 
1770   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1771       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1772       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1773       recordUseOfEvaluatedWeak(E);
1774 
1775   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1776     UnusedPrivateFields.remove(FD);
1777     // Just in case we're building an illegal pointer-to-member.
1778     if (FD->isBitField())
1779       E->setObjectKind(OK_BitField);
1780   }
1781 
1782   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1783   // designates a bit-field.
1784   if (auto *BD = dyn_cast<BindingDecl>(D))
1785     if (auto *BE = BD->getBinding())
1786       E->setObjectKind(BE->getObjectKind());
1787 
1788   return E;
1789 }
1790 
1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1792 /// possibly a list of template arguments.
1793 ///
1794 /// If this produces template arguments, it is permitted to call
1795 /// DecomposeTemplateName.
1796 ///
1797 /// This actually loses a lot of source location information for
1798 /// non-standard name kinds; we should consider preserving that in
1799 /// some way.
1800 void
1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1802                              TemplateArgumentListInfo &Buffer,
1803                              DeclarationNameInfo &NameInfo,
1804                              const TemplateArgumentListInfo *&TemplateArgs) {
1805   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1806     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1807     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1808 
1809     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1810                                        Id.TemplateId->NumArgs);
1811     translateTemplateArguments(TemplateArgsPtr, Buffer);
1812 
1813     TemplateName TName = Id.TemplateId->Template.get();
1814     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1815     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1816     TemplateArgs = &Buffer;
1817   } else {
1818     NameInfo = GetNameFromUnqualifiedId(Id);
1819     TemplateArgs = nullptr;
1820   }
1821 }
1822 
1823 static void emitEmptyLookupTypoDiagnostic(
1824     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1825     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1826     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1827   DeclContext *Ctx =
1828       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1829   if (!TC) {
1830     // Emit a special diagnostic for failed member lookups.
1831     // FIXME: computing the declaration context might fail here (?)
1832     if (Ctx)
1833       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1834                                                  << SS.getRange();
1835     else
1836       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1837     return;
1838   }
1839 
1840   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1841   bool DroppedSpecifier =
1842       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1843   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1844                         ? diag::note_implicit_param_decl
1845                         : diag::note_previous_decl;
1846   if (!Ctx)
1847     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1848                          SemaRef.PDiag(NoteID));
1849   else
1850     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1851                                  << Typo << Ctx << DroppedSpecifier
1852                                  << SS.getRange(),
1853                          SemaRef.PDiag(NoteID));
1854 }
1855 
1856 /// Diagnose an empty lookup.
1857 ///
1858 /// \return false if new lookup candidates were found
1859 bool
1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1861                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1862                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1863                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1864   DeclarationName Name = R.getLookupName();
1865 
1866   unsigned diagnostic = diag::err_undeclared_var_use;
1867   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1868   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1869       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1870       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1871     diagnostic = diag::err_undeclared_use;
1872     diagnostic_suggest = diag::err_undeclared_use_suggest;
1873   }
1874 
1875   // If the original lookup was an unqualified lookup, fake an
1876   // unqualified lookup.  This is useful when (for example) the
1877   // original lookup would not have found something because it was a
1878   // dependent name.
1879   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1880   while (DC) {
1881     if (isa<CXXRecordDecl>(DC)) {
1882       LookupQualifiedName(R, DC);
1883 
1884       if (!R.empty()) {
1885         // Don't give errors about ambiguities in this lookup.
1886         R.suppressDiagnostics();
1887 
1888         // During a default argument instantiation the CurContext points
1889         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1890         // function parameter list, hence add an explicit check.
1891         bool isDefaultArgument =
1892             !CodeSynthesisContexts.empty() &&
1893             CodeSynthesisContexts.back().Kind ==
1894                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1895         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1896         bool isInstance = CurMethod &&
1897                           CurMethod->isInstance() &&
1898                           DC == CurMethod->getParent() && !isDefaultArgument;
1899 
1900         // Give a code modification hint to insert 'this->'.
1901         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1902         // Actually quite difficult!
1903         if (getLangOpts().MSVCCompat)
1904           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1905         if (isInstance) {
1906           Diag(R.getNameLoc(), diagnostic) << Name
1907             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1908           CheckCXXThisCapture(R.getNameLoc());
1909         } else {
1910           Diag(R.getNameLoc(), diagnostic) << Name;
1911         }
1912 
1913         // Do we really want to note all of these?
1914         for (NamedDecl *D : R)
1915           Diag(D->getLocation(), diag::note_dependent_var_use);
1916 
1917         // Return true if we are inside a default argument instantiation
1918         // and the found name refers to an instance member function, otherwise
1919         // the function calling DiagnoseEmptyLookup will try to create an
1920         // implicit member call and this is wrong for default argument.
1921         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1922           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1923           return true;
1924         }
1925 
1926         // Tell the callee to try to recover.
1927         return false;
1928       }
1929 
1930       R.clear();
1931     }
1932 
1933     // In Microsoft mode, if we are performing lookup from within a friend
1934     // function definition declared at class scope then we must set
1935     // DC to the lexical parent to be able to search into the parent
1936     // class.
1937     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1938         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1939         DC->getLexicalParent()->isRecord())
1940       DC = DC->getLexicalParent();
1941     else
1942       DC = DC->getParent();
1943   }
1944 
1945   // We didn't find anything, so try to correct for a typo.
1946   TypoCorrection Corrected;
1947   if (S && Out) {
1948     SourceLocation TypoLoc = R.getNameLoc();
1949     assert(!ExplicitTemplateArgs &&
1950            "Diagnosing an empty lookup with explicit template args!");
1951     *Out = CorrectTypoDelayed(
1952         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1953         [=](const TypoCorrection &TC) {
1954           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1955                                         diagnostic, diagnostic_suggest);
1956         },
1957         nullptr, CTK_ErrorRecovery);
1958     if (*Out)
1959       return true;
1960   } else if (S && (Corrected =
1961                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1962                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1963     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1964     bool DroppedSpecifier =
1965         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1966     R.setLookupName(Corrected.getCorrection());
1967 
1968     bool AcceptableWithRecovery = false;
1969     bool AcceptableWithoutRecovery = false;
1970     NamedDecl *ND = Corrected.getFoundDecl();
1971     if (ND) {
1972       if (Corrected.isOverloaded()) {
1973         OverloadCandidateSet OCS(R.getNameLoc(),
1974                                  OverloadCandidateSet::CSK_Normal);
1975         OverloadCandidateSet::iterator Best;
1976         for (NamedDecl *CD : Corrected) {
1977           if (FunctionTemplateDecl *FTD =
1978                    dyn_cast<FunctionTemplateDecl>(CD))
1979             AddTemplateOverloadCandidate(
1980                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1981                 Args, OCS);
1982           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1983             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1984               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1985                                    Args, OCS);
1986         }
1987         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1988         case OR_Success:
1989           ND = Best->FoundDecl;
1990           Corrected.setCorrectionDecl(ND);
1991           break;
1992         default:
1993           // FIXME: Arbitrarily pick the first declaration for the note.
1994           Corrected.setCorrectionDecl(ND);
1995           break;
1996         }
1997       }
1998       R.addDecl(ND);
1999       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2000         CXXRecordDecl *Record = nullptr;
2001         if (Corrected.getCorrectionSpecifier()) {
2002           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2003           Record = Ty->getAsCXXRecordDecl();
2004         }
2005         if (!Record)
2006           Record = cast<CXXRecordDecl>(
2007               ND->getDeclContext()->getRedeclContext());
2008         R.setNamingClass(Record);
2009       }
2010 
2011       auto *UnderlyingND = ND->getUnderlyingDecl();
2012       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2013                                isa<FunctionTemplateDecl>(UnderlyingND);
2014       // FIXME: If we ended up with a typo for a type name or
2015       // Objective-C class name, we're in trouble because the parser
2016       // is in the wrong place to recover. Suggest the typo
2017       // correction, but don't make it a fix-it since we're not going
2018       // to recover well anyway.
2019       AcceptableWithoutRecovery =
2020           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2021     } else {
2022       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2023       // because we aren't able to recover.
2024       AcceptableWithoutRecovery = true;
2025     }
2026 
2027     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2028       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2029                             ? diag::note_implicit_param_decl
2030                             : diag::note_previous_decl;
2031       if (SS.isEmpty())
2032         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2033                      PDiag(NoteID), AcceptableWithRecovery);
2034       else
2035         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2036                                   << Name << computeDeclContext(SS, false)
2037                                   << DroppedSpecifier << SS.getRange(),
2038                      PDiag(NoteID), AcceptableWithRecovery);
2039 
2040       // Tell the callee whether to try to recover.
2041       return !AcceptableWithRecovery;
2042     }
2043   }
2044   R.clear();
2045 
2046   // Emit a special diagnostic for failed member lookups.
2047   // FIXME: computing the declaration context might fail here (?)
2048   if (!SS.isEmpty()) {
2049     Diag(R.getNameLoc(), diag::err_no_member)
2050       << Name << computeDeclContext(SS, false)
2051       << SS.getRange();
2052     return true;
2053   }
2054 
2055   // Give up, we can't recover.
2056   Diag(R.getNameLoc(), diagnostic) << Name;
2057   return true;
2058 }
2059 
2060 /// In Microsoft mode, if we are inside a template class whose parent class has
2061 /// dependent base classes, and we can't resolve an unqualified identifier, then
2062 /// assume the identifier is a member of a dependent base class.  We can only
2063 /// recover successfully in static methods, instance methods, and other contexts
2064 /// where 'this' is available.  This doesn't precisely match MSVC's
2065 /// instantiation model, but it's close enough.
2066 static Expr *
2067 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2068                                DeclarationNameInfo &NameInfo,
2069                                SourceLocation TemplateKWLoc,
2070                                const TemplateArgumentListInfo *TemplateArgs) {
2071   // Only try to recover from lookup into dependent bases in static methods or
2072   // contexts where 'this' is available.
2073   QualType ThisType = S.getCurrentThisType();
2074   const CXXRecordDecl *RD = nullptr;
2075   if (!ThisType.isNull())
2076     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2077   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2078     RD = MD->getParent();
2079   if (!RD || !RD->hasAnyDependentBases())
2080     return nullptr;
2081 
2082   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2083   // is available, suggest inserting 'this->' as a fixit.
2084   SourceLocation Loc = NameInfo.getLoc();
2085   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2086   DB << NameInfo.getName() << RD;
2087 
2088   if (!ThisType.isNull()) {
2089     DB << FixItHint::CreateInsertion(Loc, "this->");
2090     return CXXDependentScopeMemberExpr::Create(
2091         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2092         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2093         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2094   }
2095 
2096   // Synthesize a fake NNS that points to the derived class.  This will
2097   // perform name lookup during template instantiation.
2098   CXXScopeSpec SS;
2099   auto *NNS =
2100       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2101   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2102   return DependentScopeDeclRefExpr::Create(
2103       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2104       TemplateArgs);
2105 }
2106 
2107 ExprResult
2108 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2109                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2110                         bool HasTrailingLParen, bool IsAddressOfOperand,
2111                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2112                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2113   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2114          "cannot be direct & operand and have a trailing lparen");
2115   if (SS.isInvalid())
2116     return ExprError();
2117 
2118   TemplateArgumentListInfo TemplateArgsBuffer;
2119 
2120   // Decompose the UnqualifiedId into the following data.
2121   DeclarationNameInfo NameInfo;
2122   const TemplateArgumentListInfo *TemplateArgs;
2123   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2124 
2125   DeclarationName Name = NameInfo.getName();
2126   IdentifierInfo *II = Name.getAsIdentifierInfo();
2127   SourceLocation NameLoc = NameInfo.getLoc();
2128 
2129   // C++ [temp.dep.expr]p3:
2130   //   An id-expression is type-dependent if it contains:
2131   //     -- an identifier that was declared with a dependent type,
2132   //        (note: handled after lookup)
2133   //     -- a template-id that is dependent,
2134   //        (note: handled in BuildTemplateIdExpr)
2135   //     -- a conversion-function-id that specifies a dependent type,
2136   //     -- a nested-name-specifier that contains a class-name that
2137   //        names a dependent type.
2138   // Determine whether this is a member of an unknown specialization;
2139   // we need to handle these differently.
2140   bool DependentID = false;
2141   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2142       Name.getCXXNameType()->isDependentType()) {
2143     DependentID = true;
2144   } else if (SS.isSet()) {
2145     if (DeclContext *DC = computeDeclContext(SS, false)) {
2146       if (RequireCompleteDeclContext(SS, DC))
2147         return ExprError();
2148     } else {
2149       DependentID = true;
2150     }
2151   }
2152 
2153   if (DependentID)
2154     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2155                                       IsAddressOfOperand, TemplateArgs);
2156 
2157   // Perform the required lookup.
2158   LookupResult R(*this, NameInfo,
2159                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2160                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2161   if (TemplateArgs) {
2162     // Lookup the template name again to correctly establish the context in
2163     // which it was found. This is really unfortunate as we already did the
2164     // lookup to determine that it was a template name in the first place. If
2165     // this becomes a performance hit, we can work harder to preserve those
2166     // results until we get here but it's likely not worth it.
2167     bool MemberOfUnknownSpecialization;
2168     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2169                        MemberOfUnknownSpecialization);
2170 
2171     if (MemberOfUnknownSpecialization ||
2172         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2173       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2174                                         IsAddressOfOperand, TemplateArgs);
2175   } else {
2176     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2177     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2178 
2179     // If the result might be in a dependent base class, this is a dependent
2180     // id-expression.
2181     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2182       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2183                                         IsAddressOfOperand, TemplateArgs);
2184 
2185     // If this reference is in an Objective-C method, then we need to do
2186     // some special Objective-C lookup, too.
2187     if (IvarLookupFollowUp) {
2188       ExprResult E(LookupInObjCMethod(R, S, II, true));
2189       if (E.isInvalid())
2190         return ExprError();
2191 
2192       if (Expr *Ex = E.getAs<Expr>())
2193         return Ex;
2194     }
2195   }
2196 
2197   if (R.isAmbiguous())
2198     return ExprError();
2199 
2200   // This could be an implicitly declared function reference (legal in C90,
2201   // extension in C99, forbidden in C++).
2202   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2203     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2204     if (D) R.addDecl(D);
2205   }
2206 
2207   // Determine whether this name might be a candidate for
2208   // argument-dependent lookup.
2209   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2210 
2211   if (R.empty() && !ADL) {
2212     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2213       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2214                                                    TemplateKWLoc, TemplateArgs))
2215         return E;
2216     }
2217 
2218     // Don't diagnose an empty lookup for inline assembly.
2219     if (IsInlineAsmIdentifier)
2220       return ExprError();
2221 
2222     // If this name wasn't predeclared and if this is not a function
2223     // call, diagnose the problem.
2224     TypoExpr *TE = nullptr;
2225     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2226         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2227     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2228     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2229            "Typo correction callback misconfigured");
2230     if (CCC) {
2231       // Make sure the callback knows what the typo being diagnosed is.
2232       CCC->setTypoName(II);
2233       if (SS.isValid())
2234         CCC->setTypoNNS(SS.getScopeRep());
2235     }
2236     if (DiagnoseEmptyLookup(S, SS, R,
2237                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2238                             nullptr, None, &TE)) {
2239       if (TE && KeywordReplacement) {
2240         auto &State = getTypoExprState(TE);
2241         auto BestTC = State.Consumer->getNextCorrection();
2242         if (BestTC.isKeyword()) {
2243           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2244           if (State.DiagHandler)
2245             State.DiagHandler(BestTC);
2246           KeywordReplacement->startToken();
2247           KeywordReplacement->setKind(II->getTokenID());
2248           KeywordReplacement->setIdentifierInfo(II);
2249           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2250           // Clean up the state associated with the TypoExpr, since it has
2251           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2252           clearDelayedTypo(TE);
2253           // Signal that a correction to a keyword was performed by returning a
2254           // valid-but-null ExprResult.
2255           return (Expr*)nullptr;
2256         }
2257         State.Consumer->resetCorrectionStream();
2258       }
2259       return TE ? TE : ExprError();
2260     }
2261 
2262     assert(!R.empty() &&
2263            "DiagnoseEmptyLookup returned false but added no results");
2264 
2265     // If we found an Objective-C instance variable, let
2266     // LookupInObjCMethod build the appropriate expression to
2267     // reference the ivar.
2268     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2269       R.clear();
2270       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2271       // In a hopelessly buggy code, Objective-C instance variable
2272       // lookup fails and no expression will be built to reference it.
2273       if (!E.isInvalid() && !E.get())
2274         return ExprError();
2275       return E;
2276     }
2277   }
2278 
2279   // This is guaranteed from this point on.
2280   assert(!R.empty() || ADL);
2281 
2282   // Check whether this might be a C++ implicit instance member access.
2283   // C++ [class.mfct.non-static]p3:
2284   //   When an id-expression that is not part of a class member access
2285   //   syntax and not used to form a pointer to member is used in the
2286   //   body of a non-static member function of class X, if name lookup
2287   //   resolves the name in the id-expression to a non-static non-type
2288   //   member of some class C, the id-expression is transformed into a
2289   //   class member access expression using (*this) as the
2290   //   postfix-expression to the left of the . operator.
2291   //
2292   // But we don't actually need to do this for '&' operands if R
2293   // resolved to a function or overloaded function set, because the
2294   // expression is ill-formed if it actually works out to be a
2295   // non-static member function:
2296   //
2297   // C++ [expr.ref]p4:
2298   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2299   //   [t]he expression can be used only as the left-hand operand of a
2300   //   member function call.
2301   //
2302   // There are other safeguards against such uses, but it's important
2303   // to get this right here so that we don't end up making a
2304   // spuriously dependent expression if we're inside a dependent
2305   // instance method.
2306   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2307     bool MightBeImplicitMember;
2308     if (!IsAddressOfOperand)
2309       MightBeImplicitMember = true;
2310     else if (!SS.isEmpty())
2311       MightBeImplicitMember = false;
2312     else if (R.isOverloadedResult())
2313       MightBeImplicitMember = false;
2314     else if (R.isUnresolvableResult())
2315       MightBeImplicitMember = true;
2316     else
2317       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2318                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2319                               isa<MSPropertyDecl>(R.getFoundDecl());
2320 
2321     if (MightBeImplicitMember)
2322       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2323                                              R, TemplateArgs, S);
2324   }
2325 
2326   if (TemplateArgs || TemplateKWLoc.isValid()) {
2327 
2328     // In C++1y, if this is a variable template id, then check it
2329     // in BuildTemplateIdExpr().
2330     // The single lookup result must be a variable template declaration.
2331     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2332         Id.TemplateId->Kind == TNK_Var_template) {
2333       assert(R.getAsSingle<VarTemplateDecl>() &&
2334              "There should only be one declaration found.");
2335     }
2336 
2337     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2338   }
2339 
2340   return BuildDeclarationNameExpr(SS, R, ADL);
2341 }
2342 
2343 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2344 /// declaration name, generally during template instantiation.
2345 /// There's a large number of things which don't need to be done along
2346 /// this path.
2347 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2348     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2349     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2350   DeclContext *DC = computeDeclContext(SS, false);
2351   if (!DC)
2352     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2353                                      NameInfo, /*TemplateArgs=*/nullptr);
2354 
2355   if (RequireCompleteDeclContext(SS, DC))
2356     return ExprError();
2357 
2358   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2359   LookupQualifiedName(R, DC);
2360 
2361   if (R.isAmbiguous())
2362     return ExprError();
2363 
2364   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2365     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2366                                      NameInfo, /*TemplateArgs=*/nullptr);
2367 
2368   if (R.empty()) {
2369     Diag(NameInfo.getLoc(), diag::err_no_member)
2370       << NameInfo.getName() << DC << SS.getRange();
2371     return ExprError();
2372   }
2373 
2374   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2375     // Diagnose a missing typename if this resolved unambiguously to a type in
2376     // a dependent context.  If we can recover with a type, downgrade this to
2377     // a warning in Microsoft compatibility mode.
2378     unsigned DiagID = diag::err_typename_missing;
2379     if (RecoveryTSI && getLangOpts().MSVCCompat)
2380       DiagID = diag::ext_typename_missing;
2381     SourceLocation Loc = SS.getBeginLoc();
2382     auto D = Diag(Loc, DiagID);
2383     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2384       << SourceRange(Loc, NameInfo.getEndLoc());
2385 
2386     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2387     // context.
2388     if (!RecoveryTSI)
2389       return ExprError();
2390 
2391     // Only issue the fixit if we're prepared to recover.
2392     D << FixItHint::CreateInsertion(Loc, "typename ");
2393 
2394     // Recover by pretending this was an elaborated type.
2395     QualType Ty = Context.getTypeDeclType(TD);
2396     TypeLocBuilder TLB;
2397     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2398 
2399     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2400     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2401     QTL.setElaboratedKeywordLoc(SourceLocation());
2402     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2403 
2404     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2405 
2406     return ExprEmpty();
2407   }
2408 
2409   // Defend against this resolving to an implicit member access. We usually
2410   // won't get here if this might be a legitimate a class member (we end up in
2411   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2412   // a pointer-to-member or in an unevaluated context in C++11.
2413   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2414     return BuildPossibleImplicitMemberExpr(SS,
2415                                            /*TemplateKWLoc=*/SourceLocation(),
2416                                            R, /*TemplateArgs=*/nullptr, S);
2417 
2418   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2419 }
2420 
2421 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2422 /// detected that we're currently inside an ObjC method.  Perform some
2423 /// additional lookup.
2424 ///
2425 /// Ideally, most of this would be done by lookup, but there's
2426 /// actually quite a lot of extra work involved.
2427 ///
2428 /// Returns a null sentinel to indicate trivial success.
2429 ExprResult
2430 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2431                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2432   SourceLocation Loc = Lookup.getNameLoc();
2433   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2434 
2435   // Check for error condition which is already reported.
2436   if (!CurMethod)
2437     return ExprError();
2438 
2439   // There are two cases to handle here.  1) scoped lookup could have failed,
2440   // in which case we should look for an ivar.  2) scoped lookup could have
2441   // found a decl, but that decl is outside the current instance method (i.e.
2442   // a global variable).  In these two cases, we do a lookup for an ivar with
2443   // this name, if the lookup sucedes, we replace it our current decl.
2444 
2445   // If we're in a class method, we don't normally want to look for
2446   // ivars.  But if we don't find anything else, and there's an
2447   // ivar, that's an error.
2448   bool IsClassMethod = CurMethod->isClassMethod();
2449 
2450   bool LookForIvars;
2451   if (Lookup.empty())
2452     LookForIvars = true;
2453   else if (IsClassMethod)
2454     LookForIvars = false;
2455   else
2456     LookForIvars = (Lookup.isSingleResult() &&
2457                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2458   ObjCInterfaceDecl *IFace = nullptr;
2459   if (LookForIvars) {
2460     IFace = CurMethod->getClassInterface();
2461     ObjCInterfaceDecl *ClassDeclared;
2462     ObjCIvarDecl *IV = nullptr;
2463     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2464       // Diagnose using an ivar in a class method.
2465       if (IsClassMethod)
2466         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2467                          << IV->getDeclName());
2468 
2469       // If we're referencing an invalid decl, just return this as a silent
2470       // error node.  The error diagnostic was already emitted on the decl.
2471       if (IV->isInvalidDecl())
2472         return ExprError();
2473 
2474       // Check if referencing a field with __attribute__((deprecated)).
2475       if (DiagnoseUseOfDecl(IV, Loc))
2476         return ExprError();
2477 
2478       // Diagnose the use of an ivar outside of the declaring class.
2479       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2480           !declaresSameEntity(ClassDeclared, IFace) &&
2481           !getLangOpts().DebuggerSupport)
2482         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2483 
2484       // FIXME: This should use a new expr for a direct reference, don't
2485       // turn this into Self->ivar, just return a BareIVarExpr or something.
2486       IdentifierInfo &II = Context.Idents.get("self");
2487       UnqualifiedId SelfName;
2488       SelfName.setIdentifier(&II, SourceLocation());
2489       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2490       CXXScopeSpec SelfScopeSpec;
2491       SourceLocation TemplateKWLoc;
2492       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2493                                               SelfName, false, false);
2494       if (SelfExpr.isInvalid())
2495         return ExprError();
2496 
2497       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2498       if (SelfExpr.isInvalid())
2499         return ExprError();
2500 
2501       MarkAnyDeclReferenced(Loc, IV, true);
2502 
2503       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2504       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2505           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2506         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2507 
2508       ObjCIvarRefExpr *Result = new (Context)
2509           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2510                           IV->getLocation(), SelfExpr.get(), true, true);
2511 
2512       if (getLangOpts().ObjCAutoRefCount) {
2513         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2514           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2515             recordUseOfEvaluatedWeak(Result);
2516         }
2517         if (CurContext->isClosure())
2518           Diag(Loc, diag::warn_implicitly_retains_self)
2519             << FixItHint::CreateInsertion(Loc, "self->");
2520       }
2521 
2522       return Result;
2523     }
2524   } else if (CurMethod->isInstanceMethod()) {
2525     // We should warn if a local variable hides an ivar.
2526     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2527       ObjCInterfaceDecl *ClassDeclared;
2528       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2529         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2530             declaresSameEntity(IFace, ClassDeclared))
2531           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2532       }
2533     }
2534   } else if (Lookup.isSingleResult() &&
2535              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2536     // If accessing a stand-alone ivar in a class method, this is an error.
2537     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2538       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2539                        << IV->getDeclName());
2540   }
2541 
2542   if (Lookup.empty() && II && AllowBuiltinCreation) {
2543     // FIXME. Consolidate this with similar code in LookupName.
2544     if (unsigned BuiltinID = II->getBuiltinID()) {
2545       if (!(getLangOpts().CPlusPlus &&
2546             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2547         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2548                                            S, Lookup.isForRedeclaration(),
2549                                            Lookup.getNameLoc());
2550         if (D) Lookup.addDecl(D);
2551       }
2552     }
2553   }
2554   // Sentinel value saying that we didn't do anything special.
2555   return ExprResult((Expr *)nullptr);
2556 }
2557 
2558 /// \brief Cast a base object to a member's actual type.
2559 ///
2560 /// Logically this happens in three phases:
2561 ///
2562 /// * First we cast from the base type to the naming class.
2563 ///   The naming class is the class into which we were looking
2564 ///   when we found the member;  it's the qualifier type if a
2565 ///   qualifier was provided, and otherwise it's the base type.
2566 ///
2567 /// * Next we cast from the naming class to the declaring class.
2568 ///   If the member we found was brought into a class's scope by
2569 ///   a using declaration, this is that class;  otherwise it's
2570 ///   the class declaring the member.
2571 ///
2572 /// * Finally we cast from the declaring class to the "true"
2573 ///   declaring class of the member.  This conversion does not
2574 ///   obey access control.
2575 ExprResult
2576 Sema::PerformObjectMemberConversion(Expr *From,
2577                                     NestedNameSpecifier *Qualifier,
2578                                     NamedDecl *FoundDecl,
2579                                     NamedDecl *Member) {
2580   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2581   if (!RD)
2582     return From;
2583 
2584   QualType DestRecordType;
2585   QualType DestType;
2586   QualType FromRecordType;
2587   QualType FromType = From->getType();
2588   bool PointerConversions = false;
2589   if (isa<FieldDecl>(Member)) {
2590     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2591 
2592     if (FromType->getAs<PointerType>()) {
2593       DestType = Context.getPointerType(DestRecordType);
2594       FromRecordType = FromType->getPointeeType();
2595       PointerConversions = true;
2596     } else {
2597       DestType = DestRecordType;
2598       FromRecordType = FromType;
2599     }
2600   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2601     if (Method->isStatic())
2602       return From;
2603 
2604     DestType = Method->getThisType(Context);
2605     DestRecordType = DestType->getPointeeType();
2606 
2607     if (FromType->getAs<PointerType>()) {
2608       FromRecordType = FromType->getPointeeType();
2609       PointerConversions = true;
2610     } else {
2611       FromRecordType = FromType;
2612       DestType = DestRecordType;
2613     }
2614   } else {
2615     // No conversion necessary.
2616     return From;
2617   }
2618 
2619   if (DestType->isDependentType() || FromType->isDependentType())
2620     return From;
2621 
2622   // If the unqualified types are the same, no conversion is necessary.
2623   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2624     return From;
2625 
2626   SourceRange FromRange = From->getSourceRange();
2627   SourceLocation FromLoc = FromRange.getBegin();
2628 
2629   ExprValueKind VK = From->getValueKind();
2630 
2631   // C++ [class.member.lookup]p8:
2632   //   [...] Ambiguities can often be resolved by qualifying a name with its
2633   //   class name.
2634   //
2635   // If the member was a qualified name and the qualified referred to a
2636   // specific base subobject type, we'll cast to that intermediate type
2637   // first and then to the object in which the member is declared. That allows
2638   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2639   //
2640   //   class Base { public: int x; };
2641   //   class Derived1 : public Base { };
2642   //   class Derived2 : public Base { };
2643   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2644   //
2645   //   void VeryDerived::f() {
2646   //     x = 17; // error: ambiguous base subobjects
2647   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2648   //   }
2649   if (Qualifier && Qualifier->getAsType()) {
2650     QualType QType = QualType(Qualifier->getAsType(), 0);
2651     assert(QType->isRecordType() && "lookup done with non-record type");
2652 
2653     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2654 
2655     // In C++98, the qualifier type doesn't actually have to be a base
2656     // type of the object type, in which case we just ignore it.
2657     // Otherwise build the appropriate casts.
2658     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2659       CXXCastPath BasePath;
2660       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2661                                        FromLoc, FromRange, &BasePath))
2662         return ExprError();
2663 
2664       if (PointerConversions)
2665         QType = Context.getPointerType(QType);
2666       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2667                                VK, &BasePath).get();
2668 
2669       FromType = QType;
2670       FromRecordType = QRecordType;
2671 
2672       // If the qualifier type was the same as the destination type,
2673       // we're done.
2674       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2675         return From;
2676     }
2677   }
2678 
2679   bool IgnoreAccess = false;
2680 
2681   // If we actually found the member through a using declaration, cast
2682   // down to the using declaration's type.
2683   //
2684   // Pointer equality is fine here because only one declaration of a
2685   // class ever has member declarations.
2686   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2687     assert(isa<UsingShadowDecl>(FoundDecl));
2688     QualType URecordType = Context.getTypeDeclType(
2689                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2690 
2691     // We only need to do this if the naming-class to declaring-class
2692     // conversion is non-trivial.
2693     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2694       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2695       CXXCastPath BasePath;
2696       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2697                                        FromLoc, FromRange, &BasePath))
2698         return ExprError();
2699 
2700       QualType UType = URecordType;
2701       if (PointerConversions)
2702         UType = Context.getPointerType(UType);
2703       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2704                                VK, &BasePath).get();
2705       FromType = UType;
2706       FromRecordType = URecordType;
2707     }
2708 
2709     // We don't do access control for the conversion from the
2710     // declaring class to the true declaring class.
2711     IgnoreAccess = true;
2712   }
2713 
2714   CXXCastPath BasePath;
2715   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2716                                    FromLoc, FromRange, &BasePath,
2717                                    IgnoreAccess))
2718     return ExprError();
2719 
2720   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2721                            VK, &BasePath);
2722 }
2723 
2724 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2725                                       const LookupResult &R,
2726                                       bool HasTrailingLParen) {
2727   // Only when used directly as the postfix-expression of a call.
2728   if (!HasTrailingLParen)
2729     return false;
2730 
2731   // Never if a scope specifier was provided.
2732   if (SS.isSet())
2733     return false;
2734 
2735   // Only in C++ or ObjC++.
2736   if (!getLangOpts().CPlusPlus)
2737     return false;
2738 
2739   // Turn off ADL when we find certain kinds of declarations during
2740   // normal lookup:
2741   for (NamedDecl *D : R) {
2742     // C++0x [basic.lookup.argdep]p3:
2743     //     -- a declaration of a class member
2744     // Since using decls preserve this property, we check this on the
2745     // original decl.
2746     if (D->isCXXClassMember())
2747       return false;
2748 
2749     // C++0x [basic.lookup.argdep]p3:
2750     //     -- a block-scope function declaration that is not a
2751     //        using-declaration
2752     // NOTE: we also trigger this for function templates (in fact, we
2753     // don't check the decl type at all, since all other decl types
2754     // turn off ADL anyway).
2755     if (isa<UsingShadowDecl>(D))
2756       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2757     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2758       return false;
2759 
2760     // C++0x [basic.lookup.argdep]p3:
2761     //     -- a declaration that is neither a function or a function
2762     //        template
2763     // And also for builtin functions.
2764     if (isa<FunctionDecl>(D)) {
2765       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2766 
2767       // But also builtin functions.
2768       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2769         return false;
2770     } else if (!isa<FunctionTemplateDecl>(D))
2771       return false;
2772   }
2773 
2774   return true;
2775 }
2776 
2777 
2778 /// Diagnoses obvious problems with the use of the given declaration
2779 /// as an expression.  This is only actually called for lookups that
2780 /// were not overloaded, and it doesn't promise that the declaration
2781 /// will in fact be used.
2782 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2783   if (D->isInvalidDecl())
2784     return true;
2785 
2786   if (isa<TypedefNameDecl>(D)) {
2787     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2788     return true;
2789   }
2790 
2791   if (isa<ObjCInterfaceDecl>(D)) {
2792     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2793     return true;
2794   }
2795 
2796   if (isa<NamespaceDecl>(D)) {
2797     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2798     return true;
2799   }
2800 
2801   return false;
2802 }
2803 
2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2805                                           LookupResult &R, bool NeedsADL,
2806                                           bool AcceptInvalidDecl) {
2807   // If this is a single, fully-resolved result and we don't need ADL,
2808   // just build an ordinary singleton decl ref.
2809   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2810     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2811                                     R.getRepresentativeDecl(), nullptr,
2812                                     AcceptInvalidDecl);
2813 
2814   // We only need to check the declaration if there's exactly one
2815   // result, because in the overloaded case the results can only be
2816   // functions and function templates.
2817   if (R.isSingleResult() &&
2818       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2819     return ExprError();
2820 
2821   // Otherwise, just build an unresolved lookup expression.  Suppress
2822   // any lookup-related diagnostics; we'll hash these out later, when
2823   // we've picked a target.
2824   R.suppressDiagnostics();
2825 
2826   UnresolvedLookupExpr *ULE
2827     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2828                                    SS.getWithLocInContext(Context),
2829                                    R.getLookupNameInfo(),
2830                                    NeedsADL, R.isOverloadedResult(),
2831                                    R.begin(), R.end());
2832 
2833   return ULE;
2834 }
2835 
2836 static void
2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2838                                    ValueDecl *var, DeclContext *DC);
2839 
2840 /// \brief Complete semantic analysis for a reference to the given declaration.
2841 ExprResult Sema::BuildDeclarationNameExpr(
2842     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2843     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2844     bool AcceptInvalidDecl) {
2845   assert(D && "Cannot refer to a NULL declaration");
2846   assert(!isa<FunctionTemplateDecl>(D) &&
2847          "Cannot refer unambiguously to a function template");
2848 
2849   SourceLocation Loc = NameInfo.getLoc();
2850   if (CheckDeclInExpr(*this, Loc, D))
2851     return ExprError();
2852 
2853   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2854     // Specifically diagnose references to class templates that are missing
2855     // a template argument list.
2856     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2857                                            << Template << SS.getRange();
2858     Diag(Template->getLocation(), diag::note_template_decl_here);
2859     return ExprError();
2860   }
2861 
2862   // Make sure that we're referring to a value.
2863   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2864   if (!VD) {
2865     Diag(Loc, diag::err_ref_non_value)
2866       << D << SS.getRange();
2867     Diag(D->getLocation(), diag::note_declared_at);
2868     return ExprError();
2869   }
2870 
2871   // Check whether this declaration can be used. Note that we suppress
2872   // this check when we're going to perform argument-dependent lookup
2873   // on this function name, because this might not be the function
2874   // that overload resolution actually selects.
2875   if (DiagnoseUseOfDecl(VD, Loc))
2876     return ExprError();
2877 
2878   // Only create DeclRefExpr's for valid Decl's.
2879   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2880     return ExprError();
2881 
2882   // Handle members of anonymous structs and unions.  If we got here,
2883   // and the reference is to a class member indirect field, then this
2884   // must be the subject of a pointer-to-member expression.
2885   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2886     if (!indirectField->isCXXClassMember())
2887       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2888                                                       indirectField);
2889 
2890   {
2891     QualType type = VD->getType();
2892     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2893       // C++ [except.spec]p17:
2894       //   An exception-specification is considered to be needed when:
2895       //   - in an expression, the function is the unique lookup result or
2896       //     the selected member of a set of overloaded functions.
2897       ResolveExceptionSpec(Loc, FPT);
2898       type = VD->getType();
2899     }
2900     ExprValueKind valueKind = VK_RValue;
2901 
2902     switch (D->getKind()) {
2903     // Ignore all the non-ValueDecl kinds.
2904 #define ABSTRACT_DECL(kind)
2905 #define VALUE(type, base)
2906 #define DECL(type, base) \
2907     case Decl::type:
2908 #include "clang/AST/DeclNodes.inc"
2909       llvm_unreachable("invalid value decl kind");
2910 
2911     // These shouldn't make it here.
2912     case Decl::ObjCAtDefsField:
2913     case Decl::ObjCIvar:
2914       llvm_unreachable("forming non-member reference to ivar?");
2915 
2916     // Enum constants are always r-values and never references.
2917     // Unresolved using declarations are dependent.
2918     case Decl::EnumConstant:
2919     case Decl::UnresolvedUsingValue:
2920     case Decl::OMPDeclareReduction:
2921       valueKind = VK_RValue;
2922       break;
2923 
2924     // Fields and indirect fields that got here must be for
2925     // pointer-to-member expressions; we just call them l-values for
2926     // internal consistency, because this subexpression doesn't really
2927     // exist in the high-level semantics.
2928     case Decl::Field:
2929     case Decl::IndirectField:
2930       assert(getLangOpts().CPlusPlus &&
2931              "building reference to field in C?");
2932 
2933       // These can't have reference type in well-formed programs, but
2934       // for internal consistency we do this anyway.
2935       type = type.getNonReferenceType();
2936       valueKind = VK_LValue;
2937       break;
2938 
2939     // Non-type template parameters are either l-values or r-values
2940     // depending on the type.
2941     case Decl::NonTypeTemplateParm: {
2942       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2943         type = reftype->getPointeeType();
2944         valueKind = VK_LValue; // even if the parameter is an r-value reference
2945         break;
2946       }
2947 
2948       // For non-references, we need to strip qualifiers just in case
2949       // the template parameter was declared as 'const int' or whatever.
2950       valueKind = VK_RValue;
2951       type = type.getUnqualifiedType();
2952       break;
2953     }
2954 
2955     case Decl::Var:
2956     case Decl::VarTemplateSpecialization:
2957     case Decl::VarTemplatePartialSpecialization:
2958     case Decl::Decomposition:
2959     case Decl::OMPCapturedExpr:
2960       // In C, "extern void blah;" is valid and is an r-value.
2961       if (!getLangOpts().CPlusPlus &&
2962           !type.hasQualifiers() &&
2963           type->isVoidType()) {
2964         valueKind = VK_RValue;
2965         break;
2966       }
2967       // fallthrough
2968 
2969     case Decl::ImplicitParam:
2970     case Decl::ParmVar: {
2971       // These are always l-values.
2972       valueKind = VK_LValue;
2973       type = type.getNonReferenceType();
2974 
2975       // FIXME: Does the addition of const really only apply in
2976       // potentially-evaluated contexts? Since the variable isn't actually
2977       // captured in an unevaluated context, it seems that the answer is no.
2978       if (!isUnevaluatedContext()) {
2979         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2980         if (!CapturedType.isNull())
2981           type = CapturedType;
2982       }
2983 
2984       break;
2985     }
2986 
2987     case Decl::Binding: {
2988       // These are always lvalues.
2989       valueKind = VK_LValue;
2990       type = type.getNonReferenceType();
2991       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2992       // decides how that's supposed to work.
2993       auto *BD = cast<BindingDecl>(VD);
2994       if (BD->getDeclContext()->isFunctionOrMethod() &&
2995           BD->getDeclContext() != CurContext)
2996         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2997       break;
2998     }
2999 
3000     case Decl::Function: {
3001       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3002         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3003           type = Context.BuiltinFnTy;
3004           valueKind = VK_RValue;
3005           break;
3006         }
3007       }
3008 
3009       const FunctionType *fty = type->castAs<FunctionType>();
3010 
3011       // If we're referring to a function with an __unknown_anytype
3012       // result type, make the entire expression __unknown_anytype.
3013       if (fty->getReturnType() == Context.UnknownAnyTy) {
3014         type = Context.UnknownAnyTy;
3015         valueKind = VK_RValue;
3016         break;
3017       }
3018 
3019       // Functions are l-values in C++.
3020       if (getLangOpts().CPlusPlus) {
3021         valueKind = VK_LValue;
3022         break;
3023       }
3024 
3025       // C99 DR 316 says that, if a function type comes from a
3026       // function definition (without a prototype), that type is only
3027       // used for checking compatibility. Therefore, when referencing
3028       // the function, we pretend that we don't have the full function
3029       // type.
3030       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3031           isa<FunctionProtoType>(fty))
3032         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3033                                               fty->getExtInfo());
3034 
3035       // Functions are r-values in C.
3036       valueKind = VK_RValue;
3037       break;
3038     }
3039 
3040     case Decl::CXXDeductionGuide:
3041       llvm_unreachable("building reference to deduction guide");
3042 
3043     case Decl::MSProperty:
3044       valueKind = VK_LValue;
3045       break;
3046 
3047     case Decl::CXXMethod:
3048       // If we're referring to a method with an __unknown_anytype
3049       // result type, make the entire expression __unknown_anytype.
3050       // This should only be possible with a type written directly.
3051       if (const FunctionProtoType *proto
3052             = dyn_cast<FunctionProtoType>(VD->getType()))
3053         if (proto->getReturnType() == Context.UnknownAnyTy) {
3054           type = Context.UnknownAnyTy;
3055           valueKind = VK_RValue;
3056           break;
3057         }
3058 
3059       // C++ methods are l-values if static, r-values if non-static.
3060       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3061         valueKind = VK_LValue;
3062         break;
3063       }
3064       // fallthrough
3065 
3066     case Decl::CXXConversion:
3067     case Decl::CXXDestructor:
3068     case Decl::CXXConstructor:
3069       valueKind = VK_RValue;
3070       break;
3071     }
3072 
3073     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3074                             TemplateArgs);
3075   }
3076 }
3077 
3078 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3079                                     SmallString<32> &Target) {
3080   Target.resize(CharByteWidth * (Source.size() + 1));
3081   char *ResultPtr = &Target[0];
3082   const llvm::UTF8 *ErrorPtr;
3083   bool success =
3084       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3085   (void)success;
3086   assert(success);
3087   Target.resize(ResultPtr - &Target[0]);
3088 }
3089 
3090 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3091                                      PredefinedExpr::IdentType IT) {
3092   // Pick the current block, lambda, captured statement or function.
3093   Decl *currentDecl = nullptr;
3094   if (const BlockScopeInfo *BSI = getCurBlock())
3095     currentDecl = BSI->TheDecl;
3096   else if (const LambdaScopeInfo *LSI = getCurLambda())
3097     currentDecl = LSI->CallOperator;
3098   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3099     currentDecl = CSI->TheCapturedDecl;
3100   else
3101     currentDecl = getCurFunctionOrMethodDecl();
3102 
3103   if (!currentDecl) {
3104     Diag(Loc, diag::ext_predef_outside_function);
3105     currentDecl = Context.getTranslationUnitDecl();
3106   }
3107 
3108   QualType ResTy;
3109   StringLiteral *SL = nullptr;
3110   if (cast<DeclContext>(currentDecl)->isDependentContext())
3111     ResTy = Context.DependentTy;
3112   else {
3113     // Pre-defined identifiers are of type char[x], where x is the length of
3114     // the string.
3115     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3116     unsigned Length = Str.length();
3117 
3118     llvm::APInt LengthI(32, Length + 1);
3119     if (IT == PredefinedExpr::LFunction) {
3120       ResTy = Context.WideCharTy.withConst();
3121       SmallString<32> RawChars;
3122       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3123                               Str, RawChars);
3124       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3125                                            /*IndexTypeQuals*/ 0);
3126       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3127                                  /*Pascal*/ false, ResTy, Loc);
3128     } else {
3129       ResTy = Context.CharTy.withConst();
3130       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3131                                            /*IndexTypeQuals*/ 0);
3132       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3133                                  /*Pascal*/ false, ResTy, Loc);
3134     }
3135   }
3136 
3137   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3138 }
3139 
3140 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3141   PredefinedExpr::IdentType IT;
3142 
3143   switch (Kind) {
3144   default: llvm_unreachable("Unknown simple primary expr!");
3145   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3146   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3147   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3148   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3149   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3150   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3151   }
3152 
3153   return BuildPredefinedExpr(Loc, IT);
3154 }
3155 
3156 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3157   SmallString<16> CharBuffer;
3158   bool Invalid = false;
3159   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3160   if (Invalid)
3161     return ExprError();
3162 
3163   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3164                             PP, Tok.getKind());
3165   if (Literal.hadError())
3166     return ExprError();
3167 
3168   QualType Ty;
3169   if (Literal.isWide())
3170     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3171   else if (Literal.isUTF16())
3172     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3173   else if (Literal.isUTF32())
3174     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3175   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3176     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3177   else
3178     Ty = Context.CharTy;  // 'x' -> char in C++
3179 
3180   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3181   if (Literal.isWide())
3182     Kind = CharacterLiteral::Wide;
3183   else if (Literal.isUTF16())
3184     Kind = CharacterLiteral::UTF16;
3185   else if (Literal.isUTF32())
3186     Kind = CharacterLiteral::UTF32;
3187   else if (Literal.isUTF8())
3188     Kind = CharacterLiteral::UTF8;
3189 
3190   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3191                                              Tok.getLocation());
3192 
3193   if (Literal.getUDSuffix().empty())
3194     return Lit;
3195 
3196   // We're building a user-defined literal.
3197   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3198   SourceLocation UDSuffixLoc =
3199     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3200 
3201   // Make sure we're allowed user-defined literals here.
3202   if (!UDLScope)
3203     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3204 
3205   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3206   //   operator "" X (ch)
3207   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3208                                         Lit, Tok.getLocation());
3209 }
3210 
3211 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3212   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3213   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3214                                 Context.IntTy, Loc);
3215 }
3216 
3217 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3218                                   QualType Ty, SourceLocation Loc) {
3219   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3220 
3221   using llvm::APFloat;
3222   APFloat Val(Format);
3223 
3224   APFloat::opStatus result = Literal.GetFloatValue(Val);
3225 
3226   // Overflow is always an error, but underflow is only an error if
3227   // we underflowed to zero (APFloat reports denormals as underflow).
3228   if ((result & APFloat::opOverflow) ||
3229       ((result & APFloat::opUnderflow) && Val.isZero())) {
3230     unsigned diagnostic;
3231     SmallString<20> buffer;
3232     if (result & APFloat::opOverflow) {
3233       diagnostic = diag::warn_float_overflow;
3234       APFloat::getLargest(Format).toString(buffer);
3235     } else {
3236       diagnostic = diag::warn_float_underflow;
3237       APFloat::getSmallest(Format).toString(buffer);
3238     }
3239 
3240     S.Diag(Loc, diagnostic)
3241       << Ty
3242       << StringRef(buffer.data(), buffer.size());
3243   }
3244 
3245   bool isExact = (result == APFloat::opOK);
3246   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3247 }
3248 
3249 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3250   assert(E && "Invalid expression");
3251 
3252   if (E->isValueDependent())
3253     return false;
3254 
3255   QualType QT = E->getType();
3256   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3257     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3258     return true;
3259   }
3260 
3261   llvm::APSInt ValueAPS;
3262   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3263 
3264   if (R.isInvalid())
3265     return true;
3266 
3267   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3268   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3269     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3270         << ValueAPS.toString(10) << ValueIsPositive;
3271     return true;
3272   }
3273 
3274   return false;
3275 }
3276 
3277 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3278   // Fast path for a single digit (which is quite common).  A single digit
3279   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3280   if (Tok.getLength() == 1) {
3281     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3282     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3283   }
3284 
3285   SmallString<128> SpellingBuffer;
3286   // NumericLiteralParser wants to overread by one character.  Add padding to
3287   // the buffer in case the token is copied to the buffer.  If getSpelling()
3288   // returns a StringRef to the memory buffer, it should have a null char at
3289   // the EOF, so it is also safe.
3290   SpellingBuffer.resize(Tok.getLength() + 1);
3291 
3292   // Get the spelling of the token, which eliminates trigraphs, etc.
3293   bool Invalid = false;
3294   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3295   if (Invalid)
3296     return ExprError();
3297 
3298   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3299   if (Literal.hadError)
3300     return ExprError();
3301 
3302   if (Literal.hasUDSuffix()) {
3303     // We're building a user-defined literal.
3304     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3305     SourceLocation UDSuffixLoc =
3306       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3307 
3308     // Make sure we're allowed user-defined literals here.
3309     if (!UDLScope)
3310       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3311 
3312     QualType CookedTy;
3313     if (Literal.isFloatingLiteral()) {
3314       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3315       // long double, the literal is treated as a call of the form
3316       //   operator "" X (f L)
3317       CookedTy = Context.LongDoubleTy;
3318     } else {
3319       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3320       // unsigned long long, the literal is treated as a call of the form
3321       //   operator "" X (n ULL)
3322       CookedTy = Context.UnsignedLongLongTy;
3323     }
3324 
3325     DeclarationName OpName =
3326       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3327     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3328     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3329 
3330     SourceLocation TokLoc = Tok.getLocation();
3331 
3332     // Perform literal operator lookup to determine if we're building a raw
3333     // literal or a cooked one.
3334     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3335     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3336                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3337                                   /*AllowStringTemplate*/false)) {
3338     case LOLR_Error:
3339       return ExprError();
3340 
3341     case LOLR_Cooked: {
3342       Expr *Lit;
3343       if (Literal.isFloatingLiteral()) {
3344         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3345       } else {
3346         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3347         if (Literal.GetIntegerValue(ResultVal))
3348           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3349               << /* Unsigned */ 1;
3350         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3351                                      Tok.getLocation());
3352       }
3353       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3354     }
3355 
3356     case LOLR_Raw: {
3357       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3358       // literal is treated as a call of the form
3359       //   operator "" X ("n")
3360       unsigned Length = Literal.getUDSuffixOffset();
3361       QualType StrTy = Context.getConstantArrayType(
3362           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3363           ArrayType::Normal, 0);
3364       Expr *Lit = StringLiteral::Create(
3365           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3366           /*Pascal*/false, StrTy, &TokLoc, 1);
3367       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3368     }
3369 
3370     case LOLR_Template: {
3371       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3372       // template), L is treated as a call fo the form
3373       //   operator "" X <'c1', 'c2', ... 'ck'>()
3374       // where n is the source character sequence c1 c2 ... ck.
3375       TemplateArgumentListInfo ExplicitArgs;
3376       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3377       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3378       llvm::APSInt Value(CharBits, CharIsUnsigned);
3379       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3380         Value = TokSpelling[I];
3381         TemplateArgument Arg(Context, Value, Context.CharTy);
3382         TemplateArgumentLocInfo ArgInfo;
3383         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3384       }
3385       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3386                                       &ExplicitArgs);
3387     }
3388     case LOLR_StringTemplate:
3389       llvm_unreachable("unexpected literal operator lookup result");
3390     }
3391   }
3392 
3393   Expr *Res;
3394 
3395   if (Literal.isFloatingLiteral()) {
3396     QualType Ty;
3397     if (Literal.isHalf){
3398       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3399         Ty = Context.HalfTy;
3400       else {
3401         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3402         return ExprError();
3403       }
3404     } else if (Literal.isFloat)
3405       Ty = Context.FloatTy;
3406     else if (Literal.isLong)
3407       Ty = Context.LongDoubleTy;
3408     else if (Literal.isFloat128)
3409       Ty = Context.Float128Ty;
3410     else
3411       Ty = Context.DoubleTy;
3412 
3413     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3414 
3415     if (Ty == Context.DoubleTy) {
3416       if (getLangOpts().SinglePrecisionConstants) {
3417         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3418         if (BTy->getKind() != BuiltinType::Float) {
3419           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3420         }
3421       } else if (getLangOpts().OpenCL &&
3422                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3423         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3424         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3425         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3426       }
3427     }
3428   } else if (!Literal.isIntegerLiteral()) {
3429     return ExprError();
3430   } else {
3431     QualType Ty;
3432 
3433     // 'long long' is a C99 or C++11 feature.
3434     if (!getLangOpts().C99 && Literal.isLongLong) {
3435       if (getLangOpts().CPlusPlus)
3436         Diag(Tok.getLocation(),
3437              getLangOpts().CPlusPlus11 ?
3438              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3439       else
3440         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3441     }
3442 
3443     // Get the value in the widest-possible width.
3444     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3445     llvm::APInt ResultVal(MaxWidth, 0);
3446 
3447     if (Literal.GetIntegerValue(ResultVal)) {
3448       // If this value didn't fit into uintmax_t, error and force to ull.
3449       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3450           << /* Unsigned */ 1;
3451       Ty = Context.UnsignedLongLongTy;
3452       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3453              "long long is not intmax_t?");
3454     } else {
3455       // If this value fits into a ULL, try to figure out what else it fits into
3456       // according to the rules of C99 6.4.4.1p5.
3457 
3458       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3459       // be an unsigned int.
3460       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3461 
3462       // Check from smallest to largest, picking the smallest type we can.
3463       unsigned Width = 0;
3464 
3465       // Microsoft specific integer suffixes are explicitly sized.
3466       if (Literal.MicrosoftInteger) {
3467         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3468           Width = 8;
3469           Ty = Context.CharTy;
3470         } else {
3471           Width = Literal.MicrosoftInteger;
3472           Ty = Context.getIntTypeForBitwidth(Width,
3473                                              /*Signed=*/!Literal.isUnsigned);
3474         }
3475       }
3476 
3477       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3478         // Are int/unsigned possibilities?
3479         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3480 
3481         // Does it fit in a unsigned int?
3482         if (ResultVal.isIntN(IntSize)) {
3483           // Does it fit in a signed int?
3484           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3485             Ty = Context.IntTy;
3486           else if (AllowUnsigned)
3487             Ty = Context.UnsignedIntTy;
3488           Width = IntSize;
3489         }
3490       }
3491 
3492       // Are long/unsigned long possibilities?
3493       if (Ty.isNull() && !Literal.isLongLong) {
3494         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3495 
3496         // Does it fit in a unsigned long?
3497         if (ResultVal.isIntN(LongSize)) {
3498           // Does it fit in a signed long?
3499           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3500             Ty = Context.LongTy;
3501           else if (AllowUnsigned)
3502             Ty = Context.UnsignedLongTy;
3503           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3504           // is compatible.
3505           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3506             const unsigned LongLongSize =
3507                 Context.getTargetInfo().getLongLongWidth();
3508             Diag(Tok.getLocation(),
3509                  getLangOpts().CPlusPlus
3510                      ? Literal.isLong
3511                            ? diag::warn_old_implicitly_unsigned_long_cxx
3512                            : /*C++98 UB*/ diag::
3513                                  ext_old_implicitly_unsigned_long_cxx
3514                      : diag::warn_old_implicitly_unsigned_long)
3515                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3516                                             : /*will be ill-formed*/ 1);
3517             Ty = Context.UnsignedLongTy;
3518           }
3519           Width = LongSize;
3520         }
3521       }
3522 
3523       // Check long long if needed.
3524       if (Ty.isNull()) {
3525         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3526 
3527         // Does it fit in a unsigned long long?
3528         if (ResultVal.isIntN(LongLongSize)) {
3529           // Does it fit in a signed long long?
3530           // To be compatible with MSVC, hex integer literals ending with the
3531           // LL or i64 suffix are always signed in Microsoft mode.
3532           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3533               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3534             Ty = Context.LongLongTy;
3535           else if (AllowUnsigned)
3536             Ty = Context.UnsignedLongLongTy;
3537           Width = LongLongSize;
3538         }
3539       }
3540 
3541       // If we still couldn't decide a type, we probably have something that
3542       // does not fit in a signed long long, but has no U suffix.
3543       if (Ty.isNull()) {
3544         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3545         Ty = Context.UnsignedLongLongTy;
3546         Width = Context.getTargetInfo().getLongLongWidth();
3547       }
3548 
3549       if (ResultVal.getBitWidth() != Width)
3550         ResultVal = ResultVal.trunc(Width);
3551     }
3552     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3553   }
3554 
3555   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3556   if (Literal.isImaginary)
3557     Res = new (Context) ImaginaryLiteral(Res,
3558                                         Context.getComplexType(Res->getType()));
3559 
3560   return Res;
3561 }
3562 
3563 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3564   assert(E && "ActOnParenExpr() missing expr");
3565   return new (Context) ParenExpr(L, R, E);
3566 }
3567 
3568 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3569                                          SourceLocation Loc,
3570                                          SourceRange ArgRange) {
3571   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3572   // scalar or vector data type argument..."
3573   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3574   // type (C99 6.2.5p18) or void.
3575   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3576     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3577       << T << ArgRange;
3578     return true;
3579   }
3580 
3581   assert((T->isVoidType() || !T->isIncompleteType()) &&
3582          "Scalar types should always be complete");
3583   return false;
3584 }
3585 
3586 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3587                                            SourceLocation Loc,
3588                                            SourceRange ArgRange,
3589                                            UnaryExprOrTypeTrait TraitKind) {
3590   // Invalid types must be hard errors for SFINAE in C++.
3591   if (S.LangOpts.CPlusPlus)
3592     return true;
3593 
3594   // C99 6.5.3.4p1:
3595   if (T->isFunctionType() &&
3596       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3597     // sizeof(function)/alignof(function) is allowed as an extension.
3598     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3599       << TraitKind << ArgRange;
3600     return false;
3601   }
3602 
3603   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3604   // this is an error (OpenCL v1.1 s6.3.k)
3605   if (T->isVoidType()) {
3606     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3607                                         : diag::ext_sizeof_alignof_void_type;
3608     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3609     return false;
3610   }
3611 
3612   return true;
3613 }
3614 
3615 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3616                                              SourceLocation Loc,
3617                                              SourceRange ArgRange,
3618                                              UnaryExprOrTypeTrait TraitKind) {
3619   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3620   // runtime doesn't allow it.
3621   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3622     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3623       << T << (TraitKind == UETT_SizeOf)
3624       << ArgRange;
3625     return true;
3626   }
3627 
3628   return false;
3629 }
3630 
3631 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3632 /// pointer type is equal to T) and emit a warning if it is.
3633 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3634                                      Expr *E) {
3635   // Don't warn if the operation changed the type.
3636   if (T != E->getType())
3637     return;
3638 
3639   // Now look for array decays.
3640   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3641   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3642     return;
3643 
3644   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3645                                              << ICE->getType()
3646                                              << ICE->getSubExpr()->getType();
3647 }
3648 
3649 /// \brief Check the constraints on expression operands to unary type expression
3650 /// and type traits.
3651 ///
3652 /// Completes any types necessary and validates the constraints on the operand
3653 /// expression. The logic mostly mirrors the type-based overload, but may modify
3654 /// the expression as it completes the type for that expression through template
3655 /// instantiation, etc.
3656 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3657                                             UnaryExprOrTypeTrait ExprKind) {
3658   QualType ExprTy = E->getType();
3659   assert(!ExprTy->isReferenceType());
3660 
3661   if (ExprKind == UETT_VecStep)
3662     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3663                                         E->getSourceRange());
3664 
3665   // Whitelist some types as extensions
3666   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3667                                       E->getSourceRange(), ExprKind))
3668     return false;
3669 
3670   // 'alignof' applied to an expression only requires the base element type of
3671   // the expression to be complete. 'sizeof' requires the expression's type to
3672   // be complete (and will attempt to complete it if it's an array of unknown
3673   // bound).
3674   if (ExprKind == UETT_AlignOf) {
3675     if (RequireCompleteType(E->getExprLoc(),
3676                             Context.getBaseElementType(E->getType()),
3677                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3678                             E->getSourceRange()))
3679       return true;
3680   } else {
3681     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3682                                 ExprKind, E->getSourceRange()))
3683       return true;
3684   }
3685 
3686   // Completing the expression's type may have changed it.
3687   ExprTy = E->getType();
3688   assert(!ExprTy->isReferenceType());
3689 
3690   if (ExprTy->isFunctionType()) {
3691     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3692       << ExprKind << E->getSourceRange();
3693     return true;
3694   }
3695 
3696   // The operand for sizeof and alignof is in an unevaluated expression context,
3697   // so side effects could result in unintended consequences.
3698   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3699       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3700     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3701 
3702   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3703                                        E->getSourceRange(), ExprKind))
3704     return true;
3705 
3706   if (ExprKind == UETT_SizeOf) {
3707     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3708       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3709         QualType OType = PVD->getOriginalType();
3710         QualType Type = PVD->getType();
3711         if (Type->isPointerType() && OType->isArrayType()) {
3712           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3713             << Type << OType;
3714           Diag(PVD->getLocation(), diag::note_declared_at);
3715         }
3716       }
3717     }
3718 
3719     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3720     // decays into a pointer and returns an unintended result. This is most
3721     // likely a typo for "sizeof(array) op x".
3722     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3723       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3724                                BO->getLHS());
3725       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3726                                BO->getRHS());
3727     }
3728   }
3729 
3730   return false;
3731 }
3732 
3733 /// \brief Check the constraints on operands to unary expression and type
3734 /// traits.
3735 ///
3736 /// This will complete any types necessary, and validate the various constraints
3737 /// on those operands.
3738 ///
3739 /// The UsualUnaryConversions() function is *not* called by this routine.
3740 /// C99 6.3.2.1p[2-4] all state:
3741 ///   Except when it is the operand of the sizeof operator ...
3742 ///
3743 /// C++ [expr.sizeof]p4
3744 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3745 ///   standard conversions are not applied to the operand of sizeof.
3746 ///
3747 /// This policy is followed for all of the unary trait expressions.
3748 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3749                                             SourceLocation OpLoc,
3750                                             SourceRange ExprRange,
3751                                             UnaryExprOrTypeTrait ExprKind) {
3752   if (ExprType->isDependentType())
3753     return false;
3754 
3755   // C++ [expr.sizeof]p2:
3756   //     When applied to a reference or a reference type, the result
3757   //     is the size of the referenced type.
3758   // C++11 [expr.alignof]p3:
3759   //     When alignof is applied to a reference type, the result
3760   //     shall be the alignment of the referenced type.
3761   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3762     ExprType = Ref->getPointeeType();
3763 
3764   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3765   //   When alignof or _Alignof is applied to an array type, the result
3766   //   is the alignment of the element type.
3767   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3768     ExprType = Context.getBaseElementType(ExprType);
3769 
3770   if (ExprKind == UETT_VecStep)
3771     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3772 
3773   // Whitelist some types as extensions
3774   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3775                                       ExprKind))
3776     return false;
3777 
3778   if (RequireCompleteType(OpLoc, ExprType,
3779                           diag::err_sizeof_alignof_incomplete_type,
3780                           ExprKind, ExprRange))
3781     return true;
3782 
3783   if (ExprType->isFunctionType()) {
3784     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3785       << ExprKind << ExprRange;
3786     return true;
3787   }
3788 
3789   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3790                                        ExprKind))
3791     return true;
3792 
3793   return false;
3794 }
3795 
3796 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3797   E = E->IgnoreParens();
3798 
3799   // Cannot know anything else if the expression is dependent.
3800   if (E->isTypeDependent())
3801     return false;
3802 
3803   if (E->getObjectKind() == OK_BitField) {
3804     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3805        << 1 << E->getSourceRange();
3806     return true;
3807   }
3808 
3809   ValueDecl *D = nullptr;
3810   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3811     D = DRE->getDecl();
3812   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3813     D = ME->getMemberDecl();
3814   }
3815 
3816   // If it's a field, require the containing struct to have a
3817   // complete definition so that we can compute the layout.
3818   //
3819   // This can happen in C++11 onwards, either by naming the member
3820   // in a way that is not transformed into a member access expression
3821   // (in an unevaluated operand, for instance), or by naming the member
3822   // in a trailing-return-type.
3823   //
3824   // For the record, since __alignof__ on expressions is a GCC
3825   // extension, GCC seems to permit this but always gives the
3826   // nonsensical answer 0.
3827   //
3828   // We don't really need the layout here --- we could instead just
3829   // directly check for all the appropriate alignment-lowing
3830   // attributes --- but that would require duplicating a lot of
3831   // logic that just isn't worth duplicating for such a marginal
3832   // use-case.
3833   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3834     // Fast path this check, since we at least know the record has a
3835     // definition if we can find a member of it.
3836     if (!FD->getParent()->isCompleteDefinition()) {
3837       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3838         << E->getSourceRange();
3839       return true;
3840     }
3841 
3842     // Otherwise, if it's a field, and the field doesn't have
3843     // reference type, then it must have a complete type (or be a
3844     // flexible array member, which we explicitly want to
3845     // white-list anyway), which makes the following checks trivial.
3846     if (!FD->getType()->isReferenceType())
3847       return false;
3848   }
3849 
3850   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3851 }
3852 
3853 bool Sema::CheckVecStepExpr(Expr *E) {
3854   E = E->IgnoreParens();
3855 
3856   // Cannot know anything else if the expression is dependent.
3857   if (E->isTypeDependent())
3858     return false;
3859 
3860   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3861 }
3862 
3863 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3864                                         CapturingScopeInfo *CSI) {
3865   assert(T->isVariablyModifiedType());
3866   assert(CSI != nullptr);
3867 
3868   // We're going to walk down into the type and look for VLA expressions.
3869   do {
3870     const Type *Ty = T.getTypePtr();
3871     switch (Ty->getTypeClass()) {
3872 #define TYPE(Class, Base)
3873 #define ABSTRACT_TYPE(Class, Base)
3874 #define NON_CANONICAL_TYPE(Class, Base)
3875 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3876 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3877 #include "clang/AST/TypeNodes.def"
3878       T = QualType();
3879       break;
3880     // These types are never variably-modified.
3881     case Type::Builtin:
3882     case Type::Complex:
3883     case Type::Vector:
3884     case Type::ExtVector:
3885     case Type::Record:
3886     case Type::Enum:
3887     case Type::Elaborated:
3888     case Type::TemplateSpecialization:
3889     case Type::ObjCObject:
3890     case Type::ObjCInterface:
3891     case Type::ObjCObjectPointer:
3892     case Type::ObjCTypeParam:
3893     case Type::Pipe:
3894       llvm_unreachable("type class is never variably-modified!");
3895     case Type::Adjusted:
3896       T = cast<AdjustedType>(Ty)->getOriginalType();
3897       break;
3898     case Type::Decayed:
3899       T = cast<DecayedType>(Ty)->getPointeeType();
3900       break;
3901     case Type::Pointer:
3902       T = cast<PointerType>(Ty)->getPointeeType();
3903       break;
3904     case Type::BlockPointer:
3905       T = cast<BlockPointerType>(Ty)->getPointeeType();
3906       break;
3907     case Type::LValueReference:
3908     case Type::RValueReference:
3909       T = cast<ReferenceType>(Ty)->getPointeeType();
3910       break;
3911     case Type::MemberPointer:
3912       T = cast<MemberPointerType>(Ty)->getPointeeType();
3913       break;
3914     case Type::ConstantArray:
3915     case Type::IncompleteArray:
3916       // Losing element qualification here is fine.
3917       T = cast<ArrayType>(Ty)->getElementType();
3918       break;
3919     case Type::VariableArray: {
3920       // Losing element qualification here is fine.
3921       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3922 
3923       // Unknown size indication requires no size computation.
3924       // Otherwise, evaluate and record it.
3925       if (auto Size = VAT->getSizeExpr()) {
3926         if (!CSI->isVLATypeCaptured(VAT)) {
3927           RecordDecl *CapRecord = nullptr;
3928           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3929             CapRecord = LSI->Lambda;
3930           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3931             CapRecord = CRSI->TheRecordDecl;
3932           }
3933           if (CapRecord) {
3934             auto ExprLoc = Size->getExprLoc();
3935             auto SizeType = Context.getSizeType();
3936             // Build the non-static data member.
3937             auto Field =
3938                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3939                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3940                                   /*BW*/ nullptr, /*Mutable*/ false,
3941                                   /*InitStyle*/ ICIS_NoInit);
3942             Field->setImplicit(true);
3943             Field->setAccess(AS_private);
3944             Field->setCapturedVLAType(VAT);
3945             CapRecord->addDecl(Field);
3946 
3947             CSI->addVLATypeCapture(ExprLoc, SizeType);
3948           }
3949         }
3950       }
3951       T = VAT->getElementType();
3952       break;
3953     }
3954     case Type::FunctionProto:
3955     case Type::FunctionNoProto:
3956       T = cast<FunctionType>(Ty)->getReturnType();
3957       break;
3958     case Type::Paren:
3959     case Type::TypeOf:
3960     case Type::UnaryTransform:
3961     case Type::Attributed:
3962     case Type::SubstTemplateTypeParm:
3963     case Type::PackExpansion:
3964       // Keep walking after single level desugaring.
3965       T = T.getSingleStepDesugaredType(Context);
3966       break;
3967     case Type::Typedef:
3968       T = cast<TypedefType>(Ty)->desugar();
3969       break;
3970     case Type::Decltype:
3971       T = cast<DecltypeType>(Ty)->desugar();
3972       break;
3973     case Type::Auto:
3974     case Type::DeducedTemplateSpecialization:
3975       T = cast<DeducedType>(Ty)->getDeducedType();
3976       break;
3977     case Type::TypeOfExpr:
3978       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3979       break;
3980     case Type::Atomic:
3981       T = cast<AtomicType>(Ty)->getValueType();
3982       break;
3983     }
3984   } while (!T.isNull() && T->isVariablyModifiedType());
3985 }
3986 
3987 /// \brief Build a sizeof or alignof expression given a type operand.
3988 ExprResult
3989 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3990                                      SourceLocation OpLoc,
3991                                      UnaryExprOrTypeTrait ExprKind,
3992                                      SourceRange R) {
3993   if (!TInfo)
3994     return ExprError();
3995 
3996   QualType T = TInfo->getType();
3997 
3998   if (!T->isDependentType() &&
3999       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4000     return ExprError();
4001 
4002   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4003     if (auto *TT = T->getAs<TypedefType>()) {
4004       for (auto I = FunctionScopes.rbegin(),
4005                 E = std::prev(FunctionScopes.rend());
4006            I != E; ++I) {
4007         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4008         if (CSI == nullptr)
4009           break;
4010         DeclContext *DC = nullptr;
4011         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4012           DC = LSI->CallOperator;
4013         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4014           DC = CRSI->TheCapturedDecl;
4015         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4016           DC = BSI->TheDecl;
4017         if (DC) {
4018           if (DC->containsDecl(TT->getDecl()))
4019             break;
4020           captureVariablyModifiedType(Context, T, CSI);
4021         }
4022       }
4023     }
4024   }
4025 
4026   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4027   return new (Context) UnaryExprOrTypeTraitExpr(
4028       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4029 }
4030 
4031 /// \brief Build a sizeof or alignof expression given an expression
4032 /// operand.
4033 ExprResult
4034 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4035                                      UnaryExprOrTypeTrait ExprKind) {
4036   ExprResult PE = CheckPlaceholderExpr(E);
4037   if (PE.isInvalid())
4038     return ExprError();
4039 
4040   E = PE.get();
4041 
4042   // Verify that the operand is valid.
4043   bool isInvalid = false;
4044   if (E->isTypeDependent()) {
4045     // Delay type-checking for type-dependent expressions.
4046   } else if (ExprKind == UETT_AlignOf) {
4047     isInvalid = CheckAlignOfExpr(*this, E);
4048   } else if (ExprKind == UETT_VecStep) {
4049     isInvalid = CheckVecStepExpr(E);
4050   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4051       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4052       isInvalid = true;
4053   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4054     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4055     isInvalid = true;
4056   } else {
4057     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4058   }
4059 
4060   if (isInvalid)
4061     return ExprError();
4062 
4063   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4064     PE = TransformToPotentiallyEvaluated(E);
4065     if (PE.isInvalid()) return ExprError();
4066     E = PE.get();
4067   }
4068 
4069   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4070   return new (Context) UnaryExprOrTypeTraitExpr(
4071       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4072 }
4073 
4074 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4075 /// expr and the same for @c alignof and @c __alignof
4076 /// Note that the ArgRange is invalid if isType is false.
4077 ExprResult
4078 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4079                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4080                                     void *TyOrEx, SourceRange ArgRange) {
4081   // If error parsing type, ignore.
4082   if (!TyOrEx) return ExprError();
4083 
4084   if (IsType) {
4085     TypeSourceInfo *TInfo;
4086     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4087     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4088   }
4089 
4090   Expr *ArgEx = (Expr *)TyOrEx;
4091   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4092   return Result;
4093 }
4094 
4095 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4096                                      bool IsReal) {
4097   if (V.get()->isTypeDependent())
4098     return S.Context.DependentTy;
4099 
4100   // _Real and _Imag are only l-values for normal l-values.
4101   if (V.get()->getObjectKind() != OK_Ordinary) {
4102     V = S.DefaultLvalueConversion(V.get());
4103     if (V.isInvalid())
4104       return QualType();
4105   }
4106 
4107   // These operators return the element type of a complex type.
4108   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4109     return CT->getElementType();
4110 
4111   // Otherwise they pass through real integer and floating point types here.
4112   if (V.get()->getType()->isArithmeticType())
4113     return V.get()->getType();
4114 
4115   // Test for placeholders.
4116   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4117   if (PR.isInvalid()) return QualType();
4118   if (PR.get() != V.get()) {
4119     V = PR;
4120     return CheckRealImagOperand(S, V, Loc, IsReal);
4121   }
4122 
4123   // Reject anything else.
4124   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4125     << (IsReal ? "__real" : "__imag");
4126   return QualType();
4127 }
4128 
4129 
4130 
4131 ExprResult
4132 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4133                           tok::TokenKind Kind, Expr *Input) {
4134   UnaryOperatorKind Opc;
4135   switch (Kind) {
4136   default: llvm_unreachable("Unknown unary op!");
4137   case tok::plusplus:   Opc = UO_PostInc; break;
4138   case tok::minusminus: Opc = UO_PostDec; break;
4139   }
4140 
4141   // Since this might is a postfix expression, get rid of ParenListExprs.
4142   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4143   if (Result.isInvalid()) return ExprError();
4144   Input = Result.get();
4145 
4146   return BuildUnaryOp(S, OpLoc, Opc, Input);
4147 }
4148 
4149 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4150 ///
4151 /// \return true on error
4152 static bool checkArithmeticOnObjCPointer(Sema &S,
4153                                          SourceLocation opLoc,
4154                                          Expr *op) {
4155   assert(op->getType()->isObjCObjectPointerType());
4156   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4157       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4158     return false;
4159 
4160   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4161     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4162     << op->getSourceRange();
4163   return true;
4164 }
4165 
4166 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4167   auto *BaseNoParens = Base->IgnoreParens();
4168   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4169     return MSProp->getPropertyDecl()->getType()->isArrayType();
4170   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4171 }
4172 
4173 ExprResult
4174 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4175                               Expr *idx, SourceLocation rbLoc) {
4176   if (base && !base->getType().isNull() &&
4177       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4178     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4179                                     /*Length=*/nullptr, rbLoc);
4180 
4181   // Since this might be a postfix expression, get rid of ParenListExprs.
4182   if (isa<ParenListExpr>(base)) {
4183     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4184     if (result.isInvalid()) return ExprError();
4185     base = result.get();
4186   }
4187 
4188   // Handle any non-overload placeholder types in the base and index
4189   // expressions.  We can't handle overloads here because the other
4190   // operand might be an overloadable type, in which case the overload
4191   // resolution for the operator overload should get the first crack
4192   // at the overload.
4193   bool IsMSPropertySubscript = false;
4194   if (base->getType()->isNonOverloadPlaceholderType()) {
4195     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4196     if (!IsMSPropertySubscript) {
4197       ExprResult result = CheckPlaceholderExpr(base);
4198       if (result.isInvalid())
4199         return ExprError();
4200       base = result.get();
4201     }
4202   }
4203   if (idx->getType()->isNonOverloadPlaceholderType()) {
4204     ExprResult result = CheckPlaceholderExpr(idx);
4205     if (result.isInvalid()) return ExprError();
4206     idx = result.get();
4207   }
4208 
4209   // Build an unanalyzed expression if either operand is type-dependent.
4210   if (getLangOpts().CPlusPlus &&
4211       (base->isTypeDependent() || idx->isTypeDependent())) {
4212     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4213                                             VK_LValue, OK_Ordinary, rbLoc);
4214   }
4215 
4216   // MSDN, property (C++)
4217   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4218   // This attribute can also be used in the declaration of an empty array in a
4219   // class or structure definition. For example:
4220   // __declspec(property(get=GetX, put=PutX)) int x[];
4221   // The above statement indicates that x[] can be used with one or more array
4222   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4223   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4224   if (IsMSPropertySubscript) {
4225     // Build MS property subscript expression if base is MS property reference
4226     // or MS property subscript.
4227     return new (Context) MSPropertySubscriptExpr(
4228         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4229   }
4230 
4231   // Use C++ overloaded-operator rules if either operand has record
4232   // type.  The spec says to do this if either type is *overloadable*,
4233   // but enum types can't declare subscript operators or conversion
4234   // operators, so there's nothing interesting for overload resolution
4235   // to do if there aren't any record types involved.
4236   //
4237   // ObjC pointers have their own subscripting logic that is not tied
4238   // to overload resolution and so should not take this path.
4239   if (getLangOpts().CPlusPlus &&
4240       (base->getType()->isRecordType() ||
4241        (!base->getType()->isObjCObjectPointerType() &&
4242         idx->getType()->isRecordType()))) {
4243     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4244   }
4245 
4246   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4247 }
4248 
4249 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4250                                           Expr *LowerBound,
4251                                           SourceLocation ColonLoc, Expr *Length,
4252                                           SourceLocation RBLoc) {
4253   if (Base->getType()->isPlaceholderType() &&
4254       !Base->getType()->isSpecificPlaceholderType(
4255           BuiltinType::OMPArraySection)) {
4256     ExprResult Result = CheckPlaceholderExpr(Base);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Base = Result.get();
4260   }
4261   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4262     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4263     if (Result.isInvalid())
4264       return ExprError();
4265     Result = DefaultLvalueConversion(Result.get());
4266     if (Result.isInvalid())
4267       return ExprError();
4268     LowerBound = Result.get();
4269   }
4270   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4271     ExprResult Result = CheckPlaceholderExpr(Length);
4272     if (Result.isInvalid())
4273       return ExprError();
4274     Result = DefaultLvalueConversion(Result.get());
4275     if (Result.isInvalid())
4276       return ExprError();
4277     Length = Result.get();
4278   }
4279 
4280   // Build an unanalyzed expression if either operand is type-dependent.
4281   if (Base->isTypeDependent() ||
4282       (LowerBound &&
4283        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4284       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4285     return new (Context)
4286         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4287                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4288   }
4289 
4290   // Perform default conversions.
4291   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4292   QualType ResultTy;
4293   if (OriginalTy->isAnyPointerType()) {
4294     ResultTy = OriginalTy->getPointeeType();
4295   } else if (OriginalTy->isArrayType()) {
4296     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4297   } else {
4298     return ExprError(
4299         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4300         << Base->getSourceRange());
4301   }
4302   // C99 6.5.2.1p1
4303   if (LowerBound) {
4304     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4305                                                       LowerBound);
4306     if (Res.isInvalid())
4307       return ExprError(Diag(LowerBound->getExprLoc(),
4308                             diag::err_omp_typecheck_section_not_integer)
4309                        << 0 << LowerBound->getSourceRange());
4310     LowerBound = Res.get();
4311 
4312     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4313         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4314       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4315           << 0 << LowerBound->getSourceRange();
4316   }
4317   if (Length) {
4318     auto Res =
4319         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4320     if (Res.isInvalid())
4321       return ExprError(Diag(Length->getExprLoc(),
4322                             diag::err_omp_typecheck_section_not_integer)
4323                        << 1 << Length->getSourceRange());
4324     Length = Res.get();
4325 
4326     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4327         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4328       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4329           << 1 << Length->getSourceRange();
4330   }
4331 
4332   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4333   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4334   // type. Note that functions are not objects, and that (in C99 parlance)
4335   // incomplete types are not object types.
4336   if (ResultTy->isFunctionType()) {
4337     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4338         << ResultTy << Base->getSourceRange();
4339     return ExprError();
4340   }
4341 
4342   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4343                           diag::err_omp_section_incomplete_type, Base))
4344     return ExprError();
4345 
4346   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4347     llvm::APSInt LowerBoundValue;
4348     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4349       // OpenMP 4.5, [2.4 Array Sections]
4350       // The array section must be a subset of the original array.
4351       if (LowerBoundValue.isNegative()) {
4352         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4353             << LowerBound->getSourceRange();
4354         return ExprError();
4355       }
4356     }
4357   }
4358 
4359   if (Length) {
4360     llvm::APSInt LengthValue;
4361     if (Length->EvaluateAsInt(LengthValue, Context)) {
4362       // OpenMP 4.5, [2.4 Array Sections]
4363       // The length must evaluate to non-negative integers.
4364       if (LengthValue.isNegative()) {
4365         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4366             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4367             << Length->getSourceRange();
4368         return ExprError();
4369       }
4370     }
4371   } else if (ColonLoc.isValid() &&
4372              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4373                                       !OriginalTy->isVariableArrayType()))) {
4374     // OpenMP 4.5, [2.4 Array Sections]
4375     // When the size of the array dimension is not known, the length must be
4376     // specified explicitly.
4377     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4378         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4379     return ExprError();
4380   }
4381 
4382   if (!Base->getType()->isSpecificPlaceholderType(
4383           BuiltinType::OMPArraySection)) {
4384     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4385     if (Result.isInvalid())
4386       return ExprError();
4387     Base = Result.get();
4388   }
4389   return new (Context)
4390       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4391                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4392 }
4393 
4394 ExprResult
4395 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4396                                       Expr *Idx, SourceLocation RLoc) {
4397   Expr *LHSExp = Base;
4398   Expr *RHSExp = Idx;
4399 
4400   ExprValueKind VK = VK_LValue;
4401   ExprObjectKind OK = OK_Ordinary;
4402 
4403   // Per C++ core issue 1213, the result is an xvalue if either operand is
4404   // a non-lvalue array, and an lvalue otherwise.
4405   if (getLangOpts().CPlusPlus11 &&
4406       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4407        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4408     VK = VK_XValue;
4409 
4410   // Perform default conversions.
4411   if (!LHSExp->getType()->getAs<VectorType>()) {
4412     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4413     if (Result.isInvalid())
4414       return ExprError();
4415     LHSExp = Result.get();
4416   }
4417   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4418   if (Result.isInvalid())
4419     return ExprError();
4420   RHSExp = Result.get();
4421 
4422   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4423 
4424   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4425   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4426   // in the subscript position. As a result, we need to derive the array base
4427   // and index from the expression types.
4428   Expr *BaseExpr, *IndexExpr;
4429   QualType ResultType;
4430   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4431     BaseExpr = LHSExp;
4432     IndexExpr = RHSExp;
4433     ResultType = Context.DependentTy;
4434   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4435     BaseExpr = LHSExp;
4436     IndexExpr = RHSExp;
4437     ResultType = PTy->getPointeeType();
4438   } else if (const ObjCObjectPointerType *PTy =
4439                LHSTy->getAs<ObjCObjectPointerType>()) {
4440     BaseExpr = LHSExp;
4441     IndexExpr = RHSExp;
4442 
4443     // Use custom logic if this should be the pseudo-object subscript
4444     // expression.
4445     if (!LangOpts.isSubscriptPointerArithmetic())
4446       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4447                                           nullptr);
4448 
4449     ResultType = PTy->getPointeeType();
4450   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4451      // Handle the uncommon case of "123[Ptr]".
4452     BaseExpr = RHSExp;
4453     IndexExpr = LHSExp;
4454     ResultType = PTy->getPointeeType();
4455   } else if (const ObjCObjectPointerType *PTy =
4456                RHSTy->getAs<ObjCObjectPointerType>()) {
4457      // Handle the uncommon case of "123[Ptr]".
4458     BaseExpr = RHSExp;
4459     IndexExpr = LHSExp;
4460     ResultType = PTy->getPointeeType();
4461     if (!LangOpts.isSubscriptPointerArithmetic()) {
4462       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4463         << ResultType << BaseExpr->getSourceRange();
4464       return ExprError();
4465     }
4466   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4467     BaseExpr = LHSExp;    // vectors: V[123]
4468     IndexExpr = RHSExp;
4469     VK = LHSExp->getValueKind();
4470     if (VK != VK_RValue)
4471       OK = OK_VectorComponent;
4472 
4473     // FIXME: need to deal with const...
4474     ResultType = VTy->getElementType();
4475   } else if (LHSTy->isArrayType()) {
4476     // If we see an array that wasn't promoted by
4477     // DefaultFunctionArrayLvalueConversion, it must be an array that
4478     // wasn't promoted because of the C90 rule that doesn't
4479     // allow promoting non-lvalue arrays.  Warn, then
4480     // force the promotion here.
4481     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4482         LHSExp->getSourceRange();
4483     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4484                                CK_ArrayToPointerDecay).get();
4485     LHSTy = LHSExp->getType();
4486 
4487     BaseExpr = LHSExp;
4488     IndexExpr = RHSExp;
4489     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4490   } else if (RHSTy->isArrayType()) {
4491     // Same as previous, except for 123[f().a] case
4492     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4493         RHSExp->getSourceRange();
4494     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4495                                CK_ArrayToPointerDecay).get();
4496     RHSTy = RHSExp->getType();
4497 
4498     BaseExpr = RHSExp;
4499     IndexExpr = LHSExp;
4500     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4501   } else {
4502     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4503        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4504   }
4505   // C99 6.5.2.1p1
4506   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4507     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4508                      << IndexExpr->getSourceRange());
4509 
4510   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4511        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4512          && !IndexExpr->isTypeDependent())
4513     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4514 
4515   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4516   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4517   // type. Note that Functions are not objects, and that (in C99 parlance)
4518   // incomplete types are not object types.
4519   if (ResultType->isFunctionType()) {
4520     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4521       << ResultType << BaseExpr->getSourceRange();
4522     return ExprError();
4523   }
4524 
4525   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4526     // GNU extension: subscripting on pointer to void
4527     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4528       << BaseExpr->getSourceRange();
4529 
4530     // C forbids expressions of unqualified void type from being l-values.
4531     // See IsCForbiddenLValueType.
4532     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4533   } else if (!ResultType->isDependentType() &&
4534       RequireCompleteType(LLoc, ResultType,
4535                           diag::err_subscript_incomplete_type, BaseExpr))
4536     return ExprError();
4537 
4538   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4539          !ResultType.isCForbiddenLValueType());
4540 
4541   return new (Context)
4542       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4543 }
4544 
4545 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4546                                   ParmVarDecl *Param) {
4547   if (Param->hasUnparsedDefaultArg()) {
4548     Diag(CallLoc,
4549          diag::err_use_of_default_argument_to_function_declared_later) <<
4550       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4551     Diag(UnparsedDefaultArgLocs[Param],
4552          diag::note_default_argument_declared_here);
4553     return true;
4554   }
4555 
4556   if (Param->hasUninstantiatedDefaultArg()) {
4557     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4558 
4559     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4560                                                  Param);
4561 
4562     // Instantiate the expression.
4563     MultiLevelTemplateArgumentList MutiLevelArgList
4564       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4565 
4566     InstantiatingTemplate Inst(*this, CallLoc, Param,
4567                                MutiLevelArgList.getInnermost());
4568     if (Inst.isInvalid())
4569       return true;
4570     if (Inst.isAlreadyInstantiating()) {
4571       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4572       Param->setInvalidDecl();
4573       return true;
4574     }
4575 
4576     ExprResult Result;
4577     {
4578       // C++ [dcl.fct.default]p5:
4579       //   The names in the [default argument] expression are bound, and
4580       //   the semantic constraints are checked, at the point where the
4581       //   default argument expression appears.
4582       ContextRAII SavedContext(*this, FD);
4583       LocalInstantiationScope Local(*this);
4584       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4585                                 /*DirectInit*/false);
4586     }
4587     if (Result.isInvalid())
4588       return true;
4589 
4590     // Check the expression as an initializer for the parameter.
4591     InitializedEntity Entity
4592       = InitializedEntity::InitializeParameter(Context, Param);
4593     InitializationKind Kind
4594       = InitializationKind::CreateCopy(Param->getLocation(),
4595              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4596     Expr *ResultE = Result.getAs<Expr>();
4597 
4598     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4599     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4600     if (Result.isInvalid())
4601       return true;
4602 
4603     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4604                                  Param->getOuterLocStart());
4605     if (Result.isInvalid())
4606       return true;
4607 
4608     // Remember the instantiated default argument.
4609     Param->setDefaultArg(Result.getAs<Expr>());
4610     if (ASTMutationListener *L = getASTMutationListener()) {
4611       L->DefaultArgumentInstantiated(Param);
4612     }
4613   }
4614 
4615   // If the default argument expression is not set yet, we are building it now.
4616   if (!Param->hasInit()) {
4617     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4618     Param->setInvalidDecl();
4619     return true;
4620   }
4621 
4622   // If the default expression creates temporaries, we need to
4623   // push them to the current stack of expression temporaries so they'll
4624   // be properly destroyed.
4625   // FIXME: We should really be rebuilding the default argument with new
4626   // bound temporaries; see the comment in PR5810.
4627   // We don't need to do that with block decls, though, because
4628   // blocks in default argument expression can never capture anything.
4629   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4630     // Set the "needs cleanups" bit regardless of whether there are
4631     // any explicit objects.
4632     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4633 
4634     // Append all the objects to the cleanup list.  Right now, this
4635     // should always be a no-op, because blocks in default argument
4636     // expressions should never be able to capture anything.
4637     assert(!Init->getNumObjects() &&
4638            "default argument expression has capturing blocks?");
4639   }
4640 
4641   // We already type-checked the argument, so we know it works.
4642   // Just mark all of the declarations in this potentially-evaluated expression
4643   // as being "referenced".
4644   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4645                                    /*SkipLocalVariables=*/true);
4646   return false;
4647 }
4648 
4649 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4650                                         FunctionDecl *FD, ParmVarDecl *Param) {
4651   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4652     return ExprError();
4653   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4654 }
4655 
4656 Sema::VariadicCallType
4657 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4658                           Expr *Fn) {
4659   if (Proto && Proto->isVariadic()) {
4660     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4661       return VariadicConstructor;
4662     else if (Fn && Fn->getType()->isBlockPointerType())
4663       return VariadicBlock;
4664     else if (FDecl) {
4665       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4666         if (Method->isInstance())
4667           return VariadicMethod;
4668     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4669       return VariadicMethod;
4670     return VariadicFunction;
4671   }
4672   return VariadicDoesNotApply;
4673 }
4674 
4675 namespace {
4676 class FunctionCallCCC : public FunctionCallFilterCCC {
4677 public:
4678   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4679                   unsigned NumArgs, MemberExpr *ME)
4680       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4681         FunctionName(FuncName) {}
4682 
4683   bool ValidateCandidate(const TypoCorrection &candidate) override {
4684     if (!candidate.getCorrectionSpecifier() ||
4685         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4686       return false;
4687     }
4688 
4689     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4690   }
4691 
4692 private:
4693   const IdentifierInfo *const FunctionName;
4694 };
4695 }
4696 
4697 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4698                                                FunctionDecl *FDecl,
4699                                                ArrayRef<Expr *> Args) {
4700   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4701   DeclarationName FuncName = FDecl->getDeclName();
4702   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4703 
4704   if (TypoCorrection Corrected = S.CorrectTypo(
4705           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4706           S.getScopeForContext(S.CurContext), nullptr,
4707           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4708                                              Args.size(), ME),
4709           Sema::CTK_ErrorRecovery)) {
4710     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4711       if (Corrected.isOverloaded()) {
4712         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4713         OverloadCandidateSet::iterator Best;
4714         for (NamedDecl *CD : Corrected) {
4715           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4716             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4717                                    OCS);
4718         }
4719         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4720         case OR_Success:
4721           ND = Best->FoundDecl;
4722           Corrected.setCorrectionDecl(ND);
4723           break;
4724         default:
4725           break;
4726         }
4727       }
4728       ND = ND->getUnderlyingDecl();
4729       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4730         return Corrected;
4731     }
4732   }
4733   return TypoCorrection();
4734 }
4735 
4736 /// ConvertArgumentsForCall - Converts the arguments specified in
4737 /// Args/NumArgs to the parameter types of the function FDecl with
4738 /// function prototype Proto. Call is the call expression itself, and
4739 /// Fn is the function expression. For a C++ member function, this
4740 /// routine does not attempt to convert the object argument. Returns
4741 /// true if the call is ill-formed.
4742 bool
4743 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4744                               FunctionDecl *FDecl,
4745                               const FunctionProtoType *Proto,
4746                               ArrayRef<Expr *> Args,
4747                               SourceLocation RParenLoc,
4748                               bool IsExecConfig) {
4749   // Bail out early if calling a builtin with custom typechecking.
4750   if (FDecl)
4751     if (unsigned ID = FDecl->getBuiltinID())
4752       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4753         return false;
4754 
4755   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4756   // assignment, to the types of the corresponding parameter, ...
4757   unsigned NumParams = Proto->getNumParams();
4758   bool Invalid = false;
4759   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4760   unsigned FnKind = Fn->getType()->isBlockPointerType()
4761                        ? 1 /* block */
4762                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4763                                        : 0 /* function */);
4764 
4765   // If too few arguments are available (and we don't have default
4766   // arguments for the remaining parameters), don't make the call.
4767   if (Args.size() < NumParams) {
4768     if (Args.size() < MinArgs) {
4769       TypoCorrection TC;
4770       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4771         unsigned diag_id =
4772             MinArgs == NumParams && !Proto->isVariadic()
4773                 ? diag::err_typecheck_call_too_few_args_suggest
4774                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4775         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4776                                         << static_cast<unsigned>(Args.size())
4777                                         << TC.getCorrectionRange());
4778       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4779         Diag(RParenLoc,
4780              MinArgs == NumParams && !Proto->isVariadic()
4781                  ? diag::err_typecheck_call_too_few_args_one
4782                  : diag::err_typecheck_call_too_few_args_at_least_one)
4783             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4784       else
4785         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4786                             ? diag::err_typecheck_call_too_few_args
4787                             : diag::err_typecheck_call_too_few_args_at_least)
4788             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4789             << Fn->getSourceRange();
4790 
4791       // Emit the location of the prototype.
4792       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4793         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4794           << FDecl;
4795 
4796       return true;
4797     }
4798     Call->setNumArgs(Context, NumParams);
4799   }
4800 
4801   // If too many are passed and not variadic, error on the extras and drop
4802   // them.
4803   if (Args.size() > NumParams) {
4804     if (!Proto->isVariadic()) {
4805       TypoCorrection TC;
4806       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4807         unsigned diag_id =
4808             MinArgs == NumParams && !Proto->isVariadic()
4809                 ? diag::err_typecheck_call_too_many_args_suggest
4810                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4811         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4812                                         << static_cast<unsigned>(Args.size())
4813                                         << TC.getCorrectionRange());
4814       } else if (NumParams == 1 && FDecl &&
4815                  FDecl->getParamDecl(0)->getDeclName())
4816         Diag(Args[NumParams]->getLocStart(),
4817              MinArgs == NumParams
4818                  ? diag::err_typecheck_call_too_many_args_one
4819                  : diag::err_typecheck_call_too_many_args_at_most_one)
4820             << FnKind << FDecl->getParamDecl(0)
4821             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4822             << SourceRange(Args[NumParams]->getLocStart(),
4823                            Args.back()->getLocEnd());
4824       else
4825         Diag(Args[NumParams]->getLocStart(),
4826              MinArgs == NumParams
4827                  ? diag::err_typecheck_call_too_many_args
4828                  : diag::err_typecheck_call_too_many_args_at_most)
4829             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4830             << Fn->getSourceRange()
4831             << SourceRange(Args[NumParams]->getLocStart(),
4832                            Args.back()->getLocEnd());
4833 
4834       // Emit the location of the prototype.
4835       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4836         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4837           << FDecl;
4838 
4839       // This deletes the extra arguments.
4840       Call->setNumArgs(Context, NumParams);
4841       return true;
4842     }
4843   }
4844   SmallVector<Expr *, 8> AllArgs;
4845   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4846 
4847   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4848                                    Proto, 0, Args, AllArgs, CallType);
4849   if (Invalid)
4850     return true;
4851   unsigned TotalNumArgs = AllArgs.size();
4852   for (unsigned i = 0; i < TotalNumArgs; ++i)
4853     Call->setArg(i, AllArgs[i]);
4854 
4855   return false;
4856 }
4857 
4858 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4859                                   const FunctionProtoType *Proto,
4860                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4861                                   SmallVectorImpl<Expr *> &AllArgs,
4862                                   VariadicCallType CallType, bool AllowExplicit,
4863                                   bool IsListInitialization) {
4864   unsigned NumParams = Proto->getNumParams();
4865   bool Invalid = false;
4866   size_t ArgIx = 0;
4867   // Continue to check argument types (even if we have too few/many args).
4868   for (unsigned i = FirstParam; i < NumParams; i++) {
4869     QualType ProtoArgType = Proto->getParamType(i);
4870 
4871     Expr *Arg;
4872     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4873     if (ArgIx < Args.size()) {
4874       Arg = Args[ArgIx++];
4875 
4876       if (RequireCompleteType(Arg->getLocStart(),
4877                               ProtoArgType,
4878                               diag::err_call_incomplete_argument, Arg))
4879         return true;
4880 
4881       // Strip the unbridged-cast placeholder expression off, if applicable.
4882       bool CFAudited = false;
4883       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4884           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4885           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4886         Arg = stripARCUnbridgedCast(Arg);
4887       else if (getLangOpts().ObjCAutoRefCount &&
4888                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4889                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4890         CFAudited = true;
4891 
4892       InitializedEntity Entity =
4893           Param ? InitializedEntity::InitializeParameter(Context, Param,
4894                                                          ProtoArgType)
4895                 : InitializedEntity::InitializeParameter(
4896                       Context, ProtoArgType, Proto->isParamConsumed(i));
4897 
4898       // Remember that parameter belongs to a CF audited API.
4899       if (CFAudited)
4900         Entity.setParameterCFAudited();
4901 
4902       ExprResult ArgE = PerformCopyInitialization(
4903           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4904       if (ArgE.isInvalid())
4905         return true;
4906 
4907       Arg = ArgE.getAs<Expr>();
4908     } else {
4909       assert(Param && "can't use default arguments without a known callee");
4910 
4911       ExprResult ArgExpr =
4912         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4913       if (ArgExpr.isInvalid())
4914         return true;
4915 
4916       Arg = ArgExpr.getAs<Expr>();
4917     }
4918 
4919     // Check for array bounds violations for each argument to the call. This
4920     // check only triggers warnings when the argument isn't a more complex Expr
4921     // with its own checking, such as a BinaryOperator.
4922     CheckArrayAccess(Arg);
4923 
4924     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4925     CheckStaticArrayArgument(CallLoc, Param, Arg);
4926 
4927     AllArgs.push_back(Arg);
4928   }
4929 
4930   // If this is a variadic call, handle args passed through "...".
4931   if (CallType != VariadicDoesNotApply) {
4932     // Assume that extern "C" functions with variadic arguments that
4933     // return __unknown_anytype aren't *really* variadic.
4934     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4935         FDecl->isExternC()) {
4936       for (Expr *A : Args.slice(ArgIx)) {
4937         QualType paramType; // ignored
4938         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4939         Invalid |= arg.isInvalid();
4940         AllArgs.push_back(arg.get());
4941       }
4942 
4943     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4944     } else {
4945       for (Expr *A : Args.slice(ArgIx)) {
4946         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4947         Invalid |= Arg.isInvalid();
4948         AllArgs.push_back(Arg.get());
4949       }
4950     }
4951 
4952     // Check for array bounds violations.
4953     for (Expr *A : Args.slice(ArgIx))
4954       CheckArrayAccess(A);
4955   }
4956   return Invalid;
4957 }
4958 
4959 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4960   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4961   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4962     TL = DTL.getOriginalLoc();
4963   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4964     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4965       << ATL.getLocalSourceRange();
4966 }
4967 
4968 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4969 /// array parameter, check that it is non-null, and that if it is formed by
4970 /// array-to-pointer decay, the underlying array is sufficiently large.
4971 ///
4972 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4973 /// array type derivation, then for each call to the function, the value of the
4974 /// corresponding actual argument shall provide access to the first element of
4975 /// an array with at least as many elements as specified by the size expression.
4976 void
4977 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4978                                ParmVarDecl *Param,
4979                                const Expr *ArgExpr) {
4980   // Static array parameters are not supported in C++.
4981   if (!Param || getLangOpts().CPlusPlus)
4982     return;
4983 
4984   QualType OrigTy = Param->getOriginalType();
4985 
4986   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4987   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4988     return;
4989 
4990   if (ArgExpr->isNullPointerConstant(Context,
4991                                      Expr::NPC_NeverValueDependent)) {
4992     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4993     DiagnoseCalleeStaticArrayParam(*this, Param);
4994     return;
4995   }
4996 
4997   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4998   if (!CAT)
4999     return;
5000 
5001   const ConstantArrayType *ArgCAT =
5002     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5003   if (!ArgCAT)
5004     return;
5005 
5006   if (ArgCAT->getSize().ult(CAT->getSize())) {
5007     Diag(CallLoc, diag::warn_static_array_too_small)
5008       << ArgExpr->getSourceRange()
5009       << (unsigned) ArgCAT->getSize().getZExtValue()
5010       << (unsigned) CAT->getSize().getZExtValue();
5011     DiagnoseCalleeStaticArrayParam(*this, Param);
5012   }
5013 }
5014 
5015 /// Given a function expression of unknown-any type, try to rebuild it
5016 /// to have a function type.
5017 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5018 
5019 /// Is the given type a placeholder that we need to lower out
5020 /// immediately during argument processing?
5021 static bool isPlaceholderToRemoveAsArg(QualType type) {
5022   // Placeholders are never sugared.
5023   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5024   if (!placeholder) return false;
5025 
5026   switch (placeholder->getKind()) {
5027   // Ignore all the non-placeholder types.
5028 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5029   case BuiltinType::Id:
5030 #include "clang/Basic/OpenCLImageTypes.def"
5031 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5032 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5033 #include "clang/AST/BuiltinTypes.def"
5034     return false;
5035 
5036   // We cannot lower out overload sets; they might validly be resolved
5037   // by the call machinery.
5038   case BuiltinType::Overload:
5039     return false;
5040 
5041   // Unbridged casts in ARC can be handled in some call positions and
5042   // should be left in place.
5043   case BuiltinType::ARCUnbridgedCast:
5044     return false;
5045 
5046   // Pseudo-objects should be converted as soon as possible.
5047   case BuiltinType::PseudoObject:
5048     return true;
5049 
5050   // The debugger mode could theoretically but currently does not try
5051   // to resolve unknown-typed arguments based on known parameter types.
5052   case BuiltinType::UnknownAny:
5053     return true;
5054 
5055   // These are always invalid as call arguments and should be reported.
5056   case BuiltinType::BoundMember:
5057   case BuiltinType::BuiltinFn:
5058   case BuiltinType::OMPArraySection:
5059     return true;
5060 
5061   }
5062   llvm_unreachable("bad builtin type kind");
5063 }
5064 
5065 /// Check an argument list for placeholders that we won't try to
5066 /// handle later.
5067 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5068   // Apply this processing to all the arguments at once instead of
5069   // dying at the first failure.
5070   bool hasInvalid = false;
5071   for (size_t i = 0, e = args.size(); i != e; i++) {
5072     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5073       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5074       if (result.isInvalid()) hasInvalid = true;
5075       else args[i] = result.get();
5076     } else if (hasInvalid) {
5077       (void)S.CorrectDelayedTyposInExpr(args[i]);
5078     }
5079   }
5080   return hasInvalid;
5081 }
5082 
5083 /// If a builtin function has a pointer argument with no explicit address
5084 /// space, then it should be able to accept a pointer to any address
5085 /// space as input.  In order to do this, we need to replace the
5086 /// standard builtin declaration with one that uses the same address space
5087 /// as the call.
5088 ///
5089 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5090 ///                  it does not contain any pointer arguments without
5091 ///                  an address space qualifer.  Otherwise the rewritten
5092 ///                  FunctionDecl is returned.
5093 /// TODO: Handle pointer return types.
5094 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5095                                                 const FunctionDecl *FDecl,
5096                                                 MultiExprArg ArgExprs) {
5097 
5098   QualType DeclType = FDecl->getType();
5099   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5100 
5101   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5102       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5103     return nullptr;
5104 
5105   bool NeedsNewDecl = false;
5106   unsigned i = 0;
5107   SmallVector<QualType, 8> OverloadParams;
5108 
5109   for (QualType ParamType : FT->param_types()) {
5110 
5111     // Convert array arguments to pointer to simplify type lookup.
5112     ExprResult ArgRes =
5113         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5114     if (ArgRes.isInvalid())
5115       return nullptr;
5116     Expr *Arg = ArgRes.get();
5117     QualType ArgType = Arg->getType();
5118     if (!ParamType->isPointerType() ||
5119         ParamType.getQualifiers().hasAddressSpace() ||
5120         !ArgType->isPointerType() ||
5121         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5122       OverloadParams.push_back(ParamType);
5123       continue;
5124     }
5125 
5126     NeedsNewDecl = true;
5127     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5128 
5129     QualType PointeeType = ParamType->getPointeeType();
5130     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5131     OverloadParams.push_back(Context.getPointerType(PointeeType));
5132   }
5133 
5134   if (!NeedsNewDecl)
5135     return nullptr;
5136 
5137   FunctionProtoType::ExtProtoInfo EPI;
5138   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5139                                                 OverloadParams, EPI);
5140   DeclContext *Parent = Context.getTranslationUnitDecl();
5141   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5142                                                     FDecl->getLocation(),
5143                                                     FDecl->getLocation(),
5144                                                     FDecl->getIdentifier(),
5145                                                     OverloadTy,
5146                                                     /*TInfo=*/nullptr,
5147                                                     SC_Extern, false,
5148                                                     /*hasPrototype=*/true);
5149   SmallVector<ParmVarDecl*, 16> Params;
5150   FT = cast<FunctionProtoType>(OverloadTy);
5151   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5152     QualType ParamType = FT->getParamType(i);
5153     ParmVarDecl *Parm =
5154         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5155                                 SourceLocation(), nullptr, ParamType,
5156                                 /*TInfo=*/nullptr, SC_None, nullptr);
5157     Parm->setScopeInfo(0, i);
5158     Params.push_back(Parm);
5159   }
5160   OverloadDecl->setParams(Params);
5161   return OverloadDecl;
5162 }
5163 
5164 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5165                                     FunctionDecl *Callee,
5166                                     MultiExprArg ArgExprs) {
5167   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5168   // similar attributes) really don't like it when functions are called with an
5169   // invalid number of args.
5170   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5171                          /*PartialOverloading=*/false) &&
5172       !Callee->isVariadic())
5173     return;
5174   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5175     return;
5176 
5177   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5178     S.Diag(Fn->getLocStart(),
5179            isa<CXXMethodDecl>(Callee)
5180                ? diag::err_ovl_no_viable_member_function_in_call
5181                : diag::err_ovl_no_viable_function_in_call)
5182         << Callee << Callee->getSourceRange();
5183     S.Diag(Callee->getLocation(),
5184            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5185         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5186     return;
5187   }
5188 }
5189 
5190 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5191 /// This provides the location of the left/right parens and a list of comma
5192 /// locations.
5193 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5194                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5195                                Expr *ExecConfig, bool IsExecConfig) {
5196   // Since this might be a postfix expression, get rid of ParenListExprs.
5197   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5198   if (Result.isInvalid()) return ExprError();
5199   Fn = Result.get();
5200 
5201   if (checkArgsForPlaceholders(*this, ArgExprs))
5202     return ExprError();
5203 
5204   if (getLangOpts().CPlusPlus) {
5205     // If this is a pseudo-destructor expression, build the call immediately.
5206     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5207       if (!ArgExprs.empty()) {
5208         // Pseudo-destructor calls should not have any arguments.
5209         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5210             << FixItHint::CreateRemoval(
5211                    SourceRange(ArgExprs.front()->getLocStart(),
5212                                ArgExprs.back()->getLocEnd()));
5213       }
5214 
5215       return new (Context)
5216           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5217     }
5218     if (Fn->getType() == Context.PseudoObjectTy) {
5219       ExprResult result = CheckPlaceholderExpr(Fn);
5220       if (result.isInvalid()) return ExprError();
5221       Fn = result.get();
5222     }
5223 
5224     // Determine whether this is a dependent call inside a C++ template,
5225     // in which case we won't do any semantic analysis now.
5226     bool Dependent = false;
5227     if (Fn->isTypeDependent())
5228       Dependent = true;
5229     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5230       Dependent = true;
5231 
5232     if (Dependent) {
5233       if (ExecConfig) {
5234         return new (Context) CUDAKernelCallExpr(
5235             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5236             Context.DependentTy, VK_RValue, RParenLoc);
5237       } else {
5238         return new (Context) CallExpr(
5239             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5240       }
5241     }
5242 
5243     // Determine whether this is a call to an object (C++ [over.call.object]).
5244     if (Fn->getType()->isRecordType())
5245       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5246                                           RParenLoc);
5247 
5248     if (Fn->getType() == Context.UnknownAnyTy) {
5249       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5250       if (result.isInvalid()) return ExprError();
5251       Fn = result.get();
5252     }
5253 
5254     if (Fn->getType() == Context.BoundMemberTy) {
5255       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5256                                        RParenLoc);
5257     }
5258   }
5259 
5260   // Check for overloaded calls.  This can happen even in C due to extensions.
5261   if (Fn->getType() == Context.OverloadTy) {
5262     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5263 
5264     // We aren't supposed to apply this logic for if there'Scope an '&'
5265     // involved.
5266     if (!find.HasFormOfMemberPointer) {
5267       OverloadExpr *ovl = find.Expression;
5268       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5269         return BuildOverloadedCallExpr(
5270             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5271             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5272       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5273                                        RParenLoc);
5274     }
5275   }
5276 
5277   // If we're directly calling a function, get the appropriate declaration.
5278   if (Fn->getType() == Context.UnknownAnyTy) {
5279     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5280     if (result.isInvalid()) return ExprError();
5281     Fn = result.get();
5282   }
5283 
5284   Expr *NakedFn = Fn->IgnoreParens();
5285 
5286   bool CallingNDeclIndirectly = false;
5287   NamedDecl *NDecl = nullptr;
5288   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5289     if (UnOp->getOpcode() == UO_AddrOf) {
5290       CallingNDeclIndirectly = true;
5291       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5292     }
5293   }
5294 
5295   if (isa<DeclRefExpr>(NakedFn)) {
5296     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5297 
5298     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5299     if (FDecl && FDecl->getBuiltinID()) {
5300       // Rewrite the function decl for this builtin by replacing parameters
5301       // with no explicit address space with the address space of the arguments
5302       // in ArgExprs.
5303       if ((FDecl =
5304                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5305         NDecl = FDecl;
5306         Fn = DeclRefExpr::Create(
5307             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5308             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5309       }
5310     }
5311   } else if (isa<MemberExpr>(NakedFn))
5312     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5313 
5314   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5315     if (CallingNDeclIndirectly &&
5316         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5317                                            Fn->getLocStart()))
5318       return ExprError();
5319 
5320     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5321       return ExprError();
5322 
5323     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5324   }
5325 
5326   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5327                                ExecConfig, IsExecConfig);
5328 }
5329 
5330 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5331 ///
5332 /// __builtin_astype( value, dst type )
5333 ///
5334 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5335                                  SourceLocation BuiltinLoc,
5336                                  SourceLocation RParenLoc) {
5337   ExprValueKind VK = VK_RValue;
5338   ExprObjectKind OK = OK_Ordinary;
5339   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5340   QualType SrcTy = E->getType();
5341   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5342     return ExprError(Diag(BuiltinLoc,
5343                           diag::err_invalid_astype_of_different_size)
5344                      << DstTy
5345                      << SrcTy
5346                      << E->getSourceRange());
5347   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5348 }
5349 
5350 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5351 /// provided arguments.
5352 ///
5353 /// __builtin_convertvector( value, dst type )
5354 ///
5355 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5356                                         SourceLocation BuiltinLoc,
5357                                         SourceLocation RParenLoc) {
5358   TypeSourceInfo *TInfo;
5359   GetTypeFromParser(ParsedDestTy, &TInfo);
5360   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5361 }
5362 
5363 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5364 /// i.e. an expression not of \p OverloadTy.  The expression should
5365 /// unary-convert to an expression of function-pointer or
5366 /// block-pointer type.
5367 ///
5368 /// \param NDecl the declaration being called, if available
5369 ExprResult
5370 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5371                             SourceLocation LParenLoc,
5372                             ArrayRef<Expr *> Args,
5373                             SourceLocation RParenLoc,
5374                             Expr *Config, bool IsExecConfig) {
5375   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5376   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5377 
5378   // Functions with 'interrupt' attribute cannot be called directly.
5379   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5380     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5381     return ExprError();
5382   }
5383 
5384   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5385   // so there's some risk when calling out to non-interrupt handler functions
5386   // that the callee might not preserve them. This is easy to diagnose here,
5387   // but can be very challenging to debug.
5388   if (auto *Caller = getCurFunctionDecl())
5389     if (Caller->hasAttr<ARMInterruptAttr>())
5390       if (!FDecl->hasAttr<ARMInterruptAttr>())
5391         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5392 
5393   // Promote the function operand.
5394   // We special-case function promotion here because we only allow promoting
5395   // builtin functions to function pointers in the callee of a call.
5396   ExprResult Result;
5397   if (BuiltinID &&
5398       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5399     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5400                                CK_BuiltinFnToFnPtr).get();
5401   } else {
5402     Result = CallExprUnaryConversions(Fn);
5403   }
5404   if (Result.isInvalid())
5405     return ExprError();
5406   Fn = Result.get();
5407 
5408   // Make the call expr early, before semantic checks.  This guarantees cleanup
5409   // of arguments and function on error.
5410   CallExpr *TheCall;
5411   if (Config)
5412     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5413                                                cast<CallExpr>(Config), Args,
5414                                                Context.BoolTy, VK_RValue,
5415                                                RParenLoc);
5416   else
5417     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5418                                      VK_RValue, RParenLoc);
5419 
5420   if (!getLangOpts().CPlusPlus) {
5421     // C cannot always handle TypoExpr nodes in builtin calls and direct
5422     // function calls as their argument checking don't necessarily handle
5423     // dependent types properly, so make sure any TypoExprs have been
5424     // dealt with.
5425     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5426     if (!Result.isUsable()) return ExprError();
5427     TheCall = dyn_cast<CallExpr>(Result.get());
5428     if (!TheCall) return Result;
5429     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5430   }
5431 
5432   // Bail out early if calling a builtin with custom typechecking.
5433   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5434     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5435 
5436  retry:
5437   const FunctionType *FuncT;
5438   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5439     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5440     // have type pointer to function".
5441     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5442     if (!FuncT)
5443       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5444                          << Fn->getType() << Fn->getSourceRange());
5445   } else if (const BlockPointerType *BPT =
5446                Fn->getType()->getAs<BlockPointerType>()) {
5447     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5448   } else {
5449     // Handle calls to expressions of unknown-any type.
5450     if (Fn->getType() == Context.UnknownAnyTy) {
5451       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5452       if (rewrite.isInvalid()) return ExprError();
5453       Fn = rewrite.get();
5454       TheCall->setCallee(Fn);
5455       goto retry;
5456     }
5457 
5458     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5459       << Fn->getType() << Fn->getSourceRange());
5460   }
5461 
5462   if (getLangOpts().CUDA) {
5463     if (Config) {
5464       // CUDA: Kernel calls must be to global functions
5465       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5466         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5467             << FDecl->getName() << Fn->getSourceRange());
5468 
5469       // CUDA: Kernel function must have 'void' return type
5470       if (!FuncT->getReturnType()->isVoidType())
5471         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5472             << Fn->getType() << Fn->getSourceRange());
5473     } else {
5474       // CUDA: Calls to global functions must be configured
5475       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5476         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5477             << FDecl->getName() << Fn->getSourceRange());
5478     }
5479   }
5480 
5481   // Check for a valid return type
5482   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5483                           FDecl))
5484     return ExprError();
5485 
5486   // We know the result type of the call, set it.
5487   TheCall->setType(FuncT->getCallResultType(Context));
5488   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5489 
5490   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5491   if (Proto) {
5492     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5493                                 IsExecConfig))
5494       return ExprError();
5495   } else {
5496     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5497 
5498     if (FDecl) {
5499       // Check if we have too few/too many template arguments, based
5500       // on our knowledge of the function definition.
5501       const FunctionDecl *Def = nullptr;
5502       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5503         Proto = Def->getType()->getAs<FunctionProtoType>();
5504        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5505           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5506           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5507       }
5508 
5509       // If the function we're calling isn't a function prototype, but we have
5510       // a function prototype from a prior declaratiom, use that prototype.
5511       if (!FDecl->hasPrototype())
5512         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5513     }
5514 
5515     // Promote the arguments (C99 6.5.2.2p6).
5516     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5517       Expr *Arg = Args[i];
5518 
5519       if (Proto && i < Proto->getNumParams()) {
5520         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5521             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5522         ExprResult ArgE =
5523             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5524         if (ArgE.isInvalid())
5525           return true;
5526 
5527         Arg = ArgE.getAs<Expr>();
5528 
5529       } else {
5530         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5531 
5532         if (ArgE.isInvalid())
5533           return true;
5534 
5535         Arg = ArgE.getAs<Expr>();
5536       }
5537 
5538       if (RequireCompleteType(Arg->getLocStart(),
5539                               Arg->getType(),
5540                               diag::err_call_incomplete_argument, Arg))
5541         return ExprError();
5542 
5543       TheCall->setArg(i, Arg);
5544     }
5545   }
5546 
5547   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5548     if (!Method->isStatic())
5549       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5550         << Fn->getSourceRange());
5551 
5552   // Check for sentinels
5553   if (NDecl)
5554     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5555 
5556   // Do special checking on direct calls to functions.
5557   if (FDecl) {
5558     if (CheckFunctionCall(FDecl, TheCall, Proto))
5559       return ExprError();
5560 
5561     if (BuiltinID)
5562       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5563   } else if (NDecl) {
5564     if (CheckPointerCall(NDecl, TheCall, Proto))
5565       return ExprError();
5566   } else {
5567     if (CheckOtherCall(TheCall, Proto))
5568       return ExprError();
5569   }
5570 
5571   return MaybeBindToTemporary(TheCall);
5572 }
5573 
5574 ExprResult
5575 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5576                            SourceLocation RParenLoc, Expr *InitExpr) {
5577   assert(Ty && "ActOnCompoundLiteral(): missing type");
5578   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5579 
5580   TypeSourceInfo *TInfo;
5581   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5582   if (!TInfo)
5583     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5584 
5585   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5586 }
5587 
5588 ExprResult
5589 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5590                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5591   QualType literalType = TInfo->getType();
5592 
5593   if (literalType->isArrayType()) {
5594     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5595           diag::err_illegal_decl_array_incomplete_type,
5596           SourceRange(LParenLoc,
5597                       LiteralExpr->getSourceRange().getEnd())))
5598       return ExprError();
5599     if (literalType->isVariableArrayType())
5600       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5601         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5602   } else if (!literalType->isDependentType() &&
5603              RequireCompleteType(LParenLoc, literalType,
5604                diag::err_typecheck_decl_incomplete_type,
5605                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5606     return ExprError();
5607 
5608   InitializedEntity Entity
5609     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5610   InitializationKind Kind
5611     = InitializationKind::CreateCStyleCast(LParenLoc,
5612                                            SourceRange(LParenLoc, RParenLoc),
5613                                            /*InitList=*/true);
5614   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5615   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5616                                       &literalType);
5617   if (Result.isInvalid())
5618     return ExprError();
5619   LiteralExpr = Result.get();
5620 
5621   bool isFileScope = !CurContext->isFunctionOrMethod();
5622   if (isFileScope &&
5623       !LiteralExpr->isTypeDependent() &&
5624       !LiteralExpr->isValueDependent() &&
5625       !literalType->isDependentType()) { // 6.5.2.5p3
5626     if (CheckForConstantInitializer(LiteralExpr, literalType))
5627       return ExprError();
5628   }
5629 
5630   // In C, compound literals are l-values for some reason.
5631   // For GCC compatibility, in C++, file-scope array compound literals with
5632   // constant initializers are also l-values, and compound literals are
5633   // otherwise prvalues.
5634   //
5635   // (GCC also treats C++ list-initialized file-scope array prvalues with
5636   // constant initializers as l-values, but that's non-conforming, so we don't
5637   // follow it there.)
5638   //
5639   // FIXME: It would be better to handle the lvalue cases as materializing and
5640   // lifetime-extending a temporary object, but our materialized temporaries
5641   // representation only supports lifetime extension from a variable, not "out
5642   // of thin air".
5643   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5644   // is bound to the result of applying array-to-pointer decay to the compound
5645   // literal.
5646   // FIXME: GCC supports compound literals of reference type, which should
5647   // obviously have a value kind derived from the kind of reference involved.
5648   ExprValueKind VK =
5649       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5650           ? VK_RValue
5651           : VK_LValue;
5652 
5653   return MaybeBindToTemporary(
5654       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5655                                         VK, LiteralExpr, isFileScope));
5656 }
5657 
5658 ExprResult
5659 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5660                     SourceLocation RBraceLoc) {
5661   // Immediately handle non-overload placeholders.  Overloads can be
5662   // resolved contextually, but everything else here can't.
5663   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5664     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5665       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5666 
5667       // Ignore failures; dropping the entire initializer list because
5668       // of one failure would be terrible for indexing/etc.
5669       if (result.isInvalid()) continue;
5670 
5671       InitArgList[I] = result.get();
5672     }
5673   }
5674 
5675   // Semantic analysis for initializers is done by ActOnDeclarator() and
5676   // CheckInitializer() - it requires knowledge of the object being intialized.
5677 
5678   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5679                                                RBraceLoc);
5680   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5681   return E;
5682 }
5683 
5684 /// Do an explicit extend of the given block pointer if we're in ARC.
5685 void Sema::maybeExtendBlockObject(ExprResult &E) {
5686   assert(E.get()->getType()->isBlockPointerType());
5687   assert(E.get()->isRValue());
5688 
5689   // Only do this in an r-value context.
5690   if (!getLangOpts().ObjCAutoRefCount) return;
5691 
5692   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5693                                CK_ARCExtendBlockObject, E.get(),
5694                                /*base path*/ nullptr, VK_RValue);
5695   Cleanup.setExprNeedsCleanups(true);
5696 }
5697 
5698 /// Prepare a conversion of the given expression to an ObjC object
5699 /// pointer type.
5700 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5701   QualType type = E.get()->getType();
5702   if (type->isObjCObjectPointerType()) {
5703     return CK_BitCast;
5704   } else if (type->isBlockPointerType()) {
5705     maybeExtendBlockObject(E);
5706     return CK_BlockPointerToObjCPointerCast;
5707   } else {
5708     assert(type->isPointerType());
5709     return CK_CPointerToObjCPointerCast;
5710   }
5711 }
5712 
5713 /// Prepares for a scalar cast, performing all the necessary stages
5714 /// except the final cast and returning the kind required.
5715 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5716   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5717   // Also, callers should have filtered out the invalid cases with
5718   // pointers.  Everything else should be possible.
5719 
5720   QualType SrcTy = Src.get()->getType();
5721   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5722     return CK_NoOp;
5723 
5724   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5725   case Type::STK_MemberPointer:
5726     llvm_unreachable("member pointer type in C");
5727 
5728   case Type::STK_CPointer:
5729   case Type::STK_BlockPointer:
5730   case Type::STK_ObjCObjectPointer:
5731     switch (DestTy->getScalarTypeKind()) {
5732     case Type::STK_CPointer: {
5733       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5734       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5735       if (SrcAS != DestAS)
5736         return CK_AddressSpaceConversion;
5737       return CK_BitCast;
5738     }
5739     case Type::STK_BlockPointer:
5740       return (SrcKind == Type::STK_BlockPointer
5741                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5742     case Type::STK_ObjCObjectPointer:
5743       if (SrcKind == Type::STK_ObjCObjectPointer)
5744         return CK_BitCast;
5745       if (SrcKind == Type::STK_CPointer)
5746         return CK_CPointerToObjCPointerCast;
5747       maybeExtendBlockObject(Src);
5748       return CK_BlockPointerToObjCPointerCast;
5749     case Type::STK_Bool:
5750       return CK_PointerToBoolean;
5751     case Type::STK_Integral:
5752       return CK_PointerToIntegral;
5753     case Type::STK_Floating:
5754     case Type::STK_FloatingComplex:
5755     case Type::STK_IntegralComplex:
5756     case Type::STK_MemberPointer:
5757       llvm_unreachable("illegal cast from pointer");
5758     }
5759     llvm_unreachable("Should have returned before this");
5760 
5761   case Type::STK_Bool: // casting from bool is like casting from an integer
5762   case Type::STK_Integral:
5763     switch (DestTy->getScalarTypeKind()) {
5764     case Type::STK_CPointer:
5765     case Type::STK_ObjCObjectPointer:
5766     case Type::STK_BlockPointer:
5767       if (Src.get()->isNullPointerConstant(Context,
5768                                            Expr::NPC_ValueDependentIsNull))
5769         return CK_NullToPointer;
5770       return CK_IntegralToPointer;
5771     case Type::STK_Bool:
5772       return CK_IntegralToBoolean;
5773     case Type::STK_Integral:
5774       return CK_IntegralCast;
5775     case Type::STK_Floating:
5776       return CK_IntegralToFloating;
5777     case Type::STK_IntegralComplex:
5778       Src = ImpCastExprToType(Src.get(),
5779                       DestTy->castAs<ComplexType>()->getElementType(),
5780                       CK_IntegralCast);
5781       return CK_IntegralRealToComplex;
5782     case Type::STK_FloatingComplex:
5783       Src = ImpCastExprToType(Src.get(),
5784                       DestTy->castAs<ComplexType>()->getElementType(),
5785                       CK_IntegralToFloating);
5786       return CK_FloatingRealToComplex;
5787     case Type::STK_MemberPointer:
5788       llvm_unreachable("member pointer type in C");
5789     }
5790     llvm_unreachable("Should have returned before this");
5791 
5792   case Type::STK_Floating:
5793     switch (DestTy->getScalarTypeKind()) {
5794     case Type::STK_Floating:
5795       return CK_FloatingCast;
5796     case Type::STK_Bool:
5797       return CK_FloatingToBoolean;
5798     case Type::STK_Integral:
5799       return CK_FloatingToIntegral;
5800     case Type::STK_FloatingComplex:
5801       Src = ImpCastExprToType(Src.get(),
5802                               DestTy->castAs<ComplexType>()->getElementType(),
5803                               CK_FloatingCast);
5804       return CK_FloatingRealToComplex;
5805     case Type::STK_IntegralComplex:
5806       Src = ImpCastExprToType(Src.get(),
5807                               DestTy->castAs<ComplexType>()->getElementType(),
5808                               CK_FloatingToIntegral);
5809       return CK_IntegralRealToComplex;
5810     case Type::STK_CPointer:
5811     case Type::STK_ObjCObjectPointer:
5812     case Type::STK_BlockPointer:
5813       llvm_unreachable("valid float->pointer cast?");
5814     case Type::STK_MemberPointer:
5815       llvm_unreachable("member pointer type in C");
5816     }
5817     llvm_unreachable("Should have returned before this");
5818 
5819   case Type::STK_FloatingComplex:
5820     switch (DestTy->getScalarTypeKind()) {
5821     case Type::STK_FloatingComplex:
5822       return CK_FloatingComplexCast;
5823     case Type::STK_IntegralComplex:
5824       return CK_FloatingComplexToIntegralComplex;
5825     case Type::STK_Floating: {
5826       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5827       if (Context.hasSameType(ET, DestTy))
5828         return CK_FloatingComplexToReal;
5829       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5830       return CK_FloatingCast;
5831     }
5832     case Type::STK_Bool:
5833       return CK_FloatingComplexToBoolean;
5834     case Type::STK_Integral:
5835       Src = ImpCastExprToType(Src.get(),
5836                               SrcTy->castAs<ComplexType>()->getElementType(),
5837                               CK_FloatingComplexToReal);
5838       return CK_FloatingToIntegral;
5839     case Type::STK_CPointer:
5840     case Type::STK_ObjCObjectPointer:
5841     case Type::STK_BlockPointer:
5842       llvm_unreachable("valid complex float->pointer cast?");
5843     case Type::STK_MemberPointer:
5844       llvm_unreachable("member pointer type in C");
5845     }
5846     llvm_unreachable("Should have returned before this");
5847 
5848   case Type::STK_IntegralComplex:
5849     switch (DestTy->getScalarTypeKind()) {
5850     case Type::STK_FloatingComplex:
5851       return CK_IntegralComplexToFloatingComplex;
5852     case Type::STK_IntegralComplex:
5853       return CK_IntegralComplexCast;
5854     case Type::STK_Integral: {
5855       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5856       if (Context.hasSameType(ET, DestTy))
5857         return CK_IntegralComplexToReal;
5858       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5859       return CK_IntegralCast;
5860     }
5861     case Type::STK_Bool:
5862       return CK_IntegralComplexToBoolean;
5863     case Type::STK_Floating:
5864       Src = ImpCastExprToType(Src.get(),
5865                               SrcTy->castAs<ComplexType>()->getElementType(),
5866                               CK_IntegralComplexToReal);
5867       return CK_IntegralToFloating;
5868     case Type::STK_CPointer:
5869     case Type::STK_ObjCObjectPointer:
5870     case Type::STK_BlockPointer:
5871       llvm_unreachable("valid complex int->pointer cast?");
5872     case Type::STK_MemberPointer:
5873       llvm_unreachable("member pointer type in C");
5874     }
5875     llvm_unreachable("Should have returned before this");
5876   }
5877 
5878   llvm_unreachable("Unhandled scalar cast");
5879 }
5880 
5881 static bool breakDownVectorType(QualType type, uint64_t &len,
5882                                 QualType &eltType) {
5883   // Vectors are simple.
5884   if (const VectorType *vecType = type->getAs<VectorType>()) {
5885     len = vecType->getNumElements();
5886     eltType = vecType->getElementType();
5887     assert(eltType->isScalarType());
5888     return true;
5889   }
5890 
5891   // We allow lax conversion to and from non-vector types, but only if
5892   // they're real types (i.e. non-complex, non-pointer scalar types).
5893   if (!type->isRealType()) return false;
5894 
5895   len = 1;
5896   eltType = type;
5897   return true;
5898 }
5899 
5900 /// Are the two types lax-compatible vector types?  That is, given
5901 /// that one of them is a vector, do they have equal storage sizes,
5902 /// where the storage size is the number of elements times the element
5903 /// size?
5904 ///
5905 /// This will also return false if either of the types is neither a
5906 /// vector nor a real type.
5907 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5908   assert(destTy->isVectorType() || srcTy->isVectorType());
5909 
5910   // Disallow lax conversions between scalars and ExtVectors (these
5911   // conversions are allowed for other vector types because common headers
5912   // depend on them).  Most scalar OP ExtVector cases are handled by the
5913   // splat path anyway, which does what we want (convert, not bitcast).
5914   // What this rules out for ExtVectors is crazy things like char4*float.
5915   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5916   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5917 
5918   uint64_t srcLen, destLen;
5919   QualType srcEltTy, destEltTy;
5920   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5921   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5922 
5923   // ASTContext::getTypeSize will return the size rounded up to a
5924   // power of 2, so instead of using that, we need to use the raw
5925   // element size multiplied by the element count.
5926   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5927   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5928 
5929   return (srcLen * srcEltSize == destLen * destEltSize);
5930 }
5931 
5932 /// Is this a legal conversion between two types, one of which is
5933 /// known to be a vector type?
5934 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5935   assert(destTy->isVectorType() || srcTy->isVectorType());
5936 
5937   if (!Context.getLangOpts().LaxVectorConversions)
5938     return false;
5939   return areLaxCompatibleVectorTypes(srcTy, destTy);
5940 }
5941 
5942 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5943                            CastKind &Kind) {
5944   assert(VectorTy->isVectorType() && "Not a vector type!");
5945 
5946   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5947     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5948       return Diag(R.getBegin(),
5949                   Ty->isVectorType() ?
5950                   diag::err_invalid_conversion_between_vectors :
5951                   diag::err_invalid_conversion_between_vector_and_integer)
5952         << VectorTy << Ty << R;
5953   } else
5954     return Diag(R.getBegin(),
5955                 diag::err_invalid_conversion_between_vector_and_scalar)
5956       << VectorTy << Ty << R;
5957 
5958   Kind = CK_BitCast;
5959   return false;
5960 }
5961 
5962 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5963   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5964 
5965   if (DestElemTy == SplattedExpr->getType())
5966     return SplattedExpr;
5967 
5968   assert(DestElemTy->isFloatingType() ||
5969          DestElemTy->isIntegralOrEnumerationType());
5970 
5971   CastKind CK;
5972   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5973     // OpenCL requires that we convert `true` boolean expressions to -1, but
5974     // only when splatting vectors.
5975     if (DestElemTy->isFloatingType()) {
5976       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5977       // in two steps: boolean to signed integral, then to floating.
5978       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5979                                                  CK_BooleanToSignedIntegral);
5980       SplattedExpr = CastExprRes.get();
5981       CK = CK_IntegralToFloating;
5982     } else {
5983       CK = CK_BooleanToSignedIntegral;
5984     }
5985   } else {
5986     ExprResult CastExprRes = SplattedExpr;
5987     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5988     if (CastExprRes.isInvalid())
5989       return ExprError();
5990     SplattedExpr = CastExprRes.get();
5991   }
5992   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5993 }
5994 
5995 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5996                                     Expr *CastExpr, CastKind &Kind) {
5997   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5998 
5999   QualType SrcTy = CastExpr->getType();
6000 
6001   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6002   // an ExtVectorType.
6003   // In OpenCL, casts between vectors of different types are not allowed.
6004   // (See OpenCL 6.2).
6005   if (SrcTy->isVectorType()) {
6006     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6007         || (getLangOpts().OpenCL &&
6008             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6009       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6010         << DestTy << SrcTy << R;
6011       return ExprError();
6012     }
6013     Kind = CK_BitCast;
6014     return CastExpr;
6015   }
6016 
6017   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6018   // conversion will take place first from scalar to elt type, and then
6019   // splat from elt type to vector.
6020   if (SrcTy->isPointerType())
6021     return Diag(R.getBegin(),
6022                 diag::err_invalid_conversion_between_vector_and_scalar)
6023       << DestTy << SrcTy << R;
6024 
6025   Kind = CK_VectorSplat;
6026   return prepareVectorSplat(DestTy, CastExpr);
6027 }
6028 
6029 ExprResult
6030 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6031                     Declarator &D, ParsedType &Ty,
6032                     SourceLocation RParenLoc, Expr *CastExpr) {
6033   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6034          "ActOnCastExpr(): missing type or expr");
6035 
6036   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6037   if (D.isInvalidType())
6038     return ExprError();
6039 
6040   if (getLangOpts().CPlusPlus) {
6041     // Check that there are no default arguments (C++ only).
6042     CheckExtraCXXDefaultArguments(D);
6043   } else {
6044     // Make sure any TypoExprs have been dealt with.
6045     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6046     if (!Res.isUsable())
6047       return ExprError();
6048     CastExpr = Res.get();
6049   }
6050 
6051   checkUnusedDeclAttributes(D);
6052 
6053   QualType castType = castTInfo->getType();
6054   Ty = CreateParsedType(castType, castTInfo);
6055 
6056   bool isVectorLiteral = false;
6057 
6058   // Check for an altivec or OpenCL literal,
6059   // i.e. all the elements are integer constants.
6060   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6061   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6062   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6063        && castType->isVectorType() && (PE || PLE)) {
6064     if (PLE && PLE->getNumExprs() == 0) {
6065       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6066       return ExprError();
6067     }
6068     if (PE || PLE->getNumExprs() == 1) {
6069       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6070       if (!E->getType()->isVectorType())
6071         isVectorLiteral = true;
6072     }
6073     else
6074       isVectorLiteral = true;
6075   }
6076 
6077   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6078   // then handle it as such.
6079   if (isVectorLiteral)
6080     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6081 
6082   // If the Expr being casted is a ParenListExpr, handle it specially.
6083   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6084   // sequence of BinOp comma operators.
6085   if (isa<ParenListExpr>(CastExpr)) {
6086     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6087     if (Result.isInvalid()) return ExprError();
6088     CastExpr = Result.get();
6089   }
6090 
6091   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6092       !getSourceManager().isInSystemMacro(LParenLoc))
6093     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6094 
6095   CheckTollFreeBridgeCast(castType, CastExpr);
6096 
6097   CheckObjCBridgeRelatedCast(castType, CastExpr);
6098 
6099   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6100 
6101   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6102 }
6103 
6104 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6105                                     SourceLocation RParenLoc, Expr *E,
6106                                     TypeSourceInfo *TInfo) {
6107   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6108          "Expected paren or paren list expression");
6109 
6110   Expr **exprs;
6111   unsigned numExprs;
6112   Expr *subExpr;
6113   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6114   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6115     LiteralLParenLoc = PE->getLParenLoc();
6116     LiteralRParenLoc = PE->getRParenLoc();
6117     exprs = PE->getExprs();
6118     numExprs = PE->getNumExprs();
6119   } else { // isa<ParenExpr> by assertion at function entrance
6120     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6121     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6122     subExpr = cast<ParenExpr>(E)->getSubExpr();
6123     exprs = &subExpr;
6124     numExprs = 1;
6125   }
6126 
6127   QualType Ty = TInfo->getType();
6128   assert(Ty->isVectorType() && "Expected vector type");
6129 
6130   SmallVector<Expr *, 8> initExprs;
6131   const VectorType *VTy = Ty->getAs<VectorType>();
6132   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6133 
6134   // '(...)' form of vector initialization in AltiVec: the number of
6135   // initializers must be one or must match the size of the vector.
6136   // If a single value is specified in the initializer then it will be
6137   // replicated to all the components of the vector
6138   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6139     // The number of initializers must be one or must match the size of the
6140     // vector. If a single value is specified in the initializer then it will
6141     // be replicated to all the components of the vector
6142     if (numExprs == 1) {
6143       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6144       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6145       if (Literal.isInvalid())
6146         return ExprError();
6147       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6148                                   PrepareScalarCast(Literal, ElemTy));
6149       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6150     }
6151     else if (numExprs < numElems) {
6152       Diag(E->getExprLoc(),
6153            diag::err_incorrect_number_of_vector_initializers);
6154       return ExprError();
6155     }
6156     else
6157       initExprs.append(exprs, exprs + numExprs);
6158   }
6159   else {
6160     // For OpenCL, when the number of initializers is a single value,
6161     // it will be replicated to all components of the vector.
6162     if (getLangOpts().OpenCL &&
6163         VTy->getVectorKind() == VectorType::GenericVector &&
6164         numExprs == 1) {
6165         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6166         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6167         if (Literal.isInvalid())
6168           return ExprError();
6169         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6170                                     PrepareScalarCast(Literal, ElemTy));
6171         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6172     }
6173 
6174     initExprs.append(exprs, exprs + numExprs);
6175   }
6176   // FIXME: This means that pretty-printing the final AST will produce curly
6177   // braces instead of the original commas.
6178   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6179                                                    initExprs, LiteralRParenLoc);
6180   initE->setType(Ty);
6181   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6182 }
6183 
6184 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6185 /// the ParenListExpr into a sequence of comma binary operators.
6186 ExprResult
6187 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6188   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6189   if (!E)
6190     return OrigExpr;
6191 
6192   ExprResult Result(E->getExpr(0));
6193 
6194   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6195     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6196                         E->getExpr(i));
6197 
6198   if (Result.isInvalid()) return ExprError();
6199 
6200   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6201 }
6202 
6203 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6204                                     SourceLocation R,
6205                                     MultiExprArg Val) {
6206   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6207   return expr;
6208 }
6209 
6210 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6211 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6212 /// emitted.
6213 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6214                                       SourceLocation QuestionLoc) {
6215   Expr *NullExpr = LHSExpr;
6216   Expr *NonPointerExpr = RHSExpr;
6217   Expr::NullPointerConstantKind NullKind =
6218       NullExpr->isNullPointerConstant(Context,
6219                                       Expr::NPC_ValueDependentIsNotNull);
6220 
6221   if (NullKind == Expr::NPCK_NotNull) {
6222     NullExpr = RHSExpr;
6223     NonPointerExpr = LHSExpr;
6224     NullKind =
6225         NullExpr->isNullPointerConstant(Context,
6226                                         Expr::NPC_ValueDependentIsNotNull);
6227   }
6228 
6229   if (NullKind == Expr::NPCK_NotNull)
6230     return false;
6231 
6232   if (NullKind == Expr::NPCK_ZeroExpression)
6233     return false;
6234 
6235   if (NullKind == Expr::NPCK_ZeroLiteral) {
6236     // In this case, check to make sure that we got here from a "NULL"
6237     // string in the source code.
6238     NullExpr = NullExpr->IgnoreParenImpCasts();
6239     SourceLocation loc = NullExpr->getExprLoc();
6240     if (!findMacroSpelling(loc, "NULL"))
6241       return false;
6242   }
6243 
6244   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6245   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6246       << NonPointerExpr->getType() << DiagType
6247       << NonPointerExpr->getSourceRange();
6248   return true;
6249 }
6250 
6251 /// \brief Return false if the condition expression is valid, true otherwise.
6252 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6253   QualType CondTy = Cond->getType();
6254 
6255   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6256   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6257     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6258       << CondTy << Cond->getSourceRange();
6259     return true;
6260   }
6261 
6262   // C99 6.5.15p2
6263   if (CondTy->isScalarType()) return false;
6264 
6265   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6266     << CondTy << Cond->getSourceRange();
6267   return true;
6268 }
6269 
6270 /// \brief Handle when one or both operands are void type.
6271 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6272                                          ExprResult &RHS) {
6273     Expr *LHSExpr = LHS.get();
6274     Expr *RHSExpr = RHS.get();
6275 
6276     if (!LHSExpr->getType()->isVoidType())
6277       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6278         << RHSExpr->getSourceRange();
6279     if (!RHSExpr->getType()->isVoidType())
6280       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6281         << LHSExpr->getSourceRange();
6282     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6283     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6284     return S.Context.VoidTy;
6285 }
6286 
6287 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6288 /// true otherwise.
6289 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6290                                         QualType PointerTy) {
6291   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6292       !NullExpr.get()->isNullPointerConstant(S.Context,
6293                                             Expr::NPC_ValueDependentIsNull))
6294     return true;
6295 
6296   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6297   return false;
6298 }
6299 
6300 /// \brief Checks compatibility between two pointers and return the resulting
6301 /// type.
6302 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6303                                                      ExprResult &RHS,
6304                                                      SourceLocation Loc) {
6305   QualType LHSTy = LHS.get()->getType();
6306   QualType RHSTy = RHS.get()->getType();
6307 
6308   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6309     // Two identical pointers types are always compatible.
6310     return LHSTy;
6311   }
6312 
6313   QualType lhptee, rhptee;
6314 
6315   // Get the pointee types.
6316   bool IsBlockPointer = false;
6317   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6318     lhptee = LHSBTy->getPointeeType();
6319     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6320     IsBlockPointer = true;
6321   } else {
6322     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6323     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6324   }
6325 
6326   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6327   // differently qualified versions of compatible types, the result type is
6328   // a pointer to an appropriately qualified version of the composite
6329   // type.
6330 
6331   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6332   // clause doesn't make sense for our extensions. E.g. address space 2 should
6333   // be incompatible with address space 3: they may live on different devices or
6334   // anything.
6335   Qualifiers lhQual = lhptee.getQualifiers();
6336   Qualifiers rhQual = rhptee.getQualifiers();
6337 
6338   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6339   lhQual.removeCVRQualifiers();
6340   rhQual.removeCVRQualifiers();
6341 
6342   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6343   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6344 
6345   // For OpenCL:
6346   // 1. If LHS and RHS types match exactly and:
6347   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6348   //  (b) AS overlap => generate addrspacecast
6349   //  (c) AS don't overlap => give an error
6350   // 2. if LHS and RHS types don't match:
6351   //  (a) AS match => use standard C rules, generate bitcast
6352   //  (b) AS overlap => generate addrspacecast instead of bitcast
6353   //  (c) AS don't overlap => give an error
6354 
6355   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6356   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6357 
6358   // OpenCL cases 1c, 2a, 2b, and 2c.
6359   if (CompositeTy.isNull()) {
6360     // In this situation, we assume void* type. No especially good
6361     // reason, but this is what gcc does, and we do have to pick
6362     // to get a consistent AST.
6363     QualType incompatTy;
6364     if (S.getLangOpts().OpenCL) {
6365       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6366       // spaces is disallowed.
6367       unsigned ResultAddrSpace;
6368       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6369         // Cases 2a and 2b.
6370         ResultAddrSpace = lhQual.getAddressSpace();
6371       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6372         // Cases 2a and 2b.
6373         ResultAddrSpace = rhQual.getAddressSpace();
6374       } else {
6375         // Cases 1c and 2c.
6376         S.Diag(Loc,
6377                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6378             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6379             << RHS.get()->getSourceRange();
6380         return QualType();
6381       }
6382 
6383       // Continue handling cases 2a and 2b.
6384       incompatTy = S.Context.getPointerType(
6385           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6386       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6387                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6388                                     ? CK_AddressSpaceConversion /* 2b */
6389                                     : CK_BitCast /* 2a */);
6390       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6391                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6392                                     ? CK_AddressSpaceConversion /* 2b */
6393                                     : CK_BitCast /* 2a */);
6394     } else {
6395       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6396           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6397           << RHS.get()->getSourceRange();
6398       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6399       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6400       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6401     }
6402     return incompatTy;
6403   }
6404 
6405   // The pointer types are compatible.
6406   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6407   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6408   if (IsBlockPointer)
6409     ResultTy = S.Context.getBlockPointerType(ResultTy);
6410   else {
6411     // Cases 1a and 1b for OpenCL.
6412     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6413     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6414                       ? CK_BitCast /* 1a */
6415                       : CK_AddressSpaceConversion /* 1b */;
6416     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6417                       ? CK_BitCast /* 1a */
6418                       : CK_AddressSpaceConversion /* 1b */;
6419     ResultTy = S.Context.getPointerType(ResultTy);
6420   }
6421 
6422   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6423   // if the target type does not change.
6424   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6425   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6426   return ResultTy;
6427 }
6428 
6429 /// \brief Return the resulting type when the operands are both block pointers.
6430 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6431                                                           ExprResult &LHS,
6432                                                           ExprResult &RHS,
6433                                                           SourceLocation Loc) {
6434   QualType LHSTy = LHS.get()->getType();
6435   QualType RHSTy = RHS.get()->getType();
6436 
6437   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6438     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6439       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6440       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6441       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6442       return destType;
6443     }
6444     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6445       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6446       << RHS.get()->getSourceRange();
6447     return QualType();
6448   }
6449 
6450   // We have 2 block pointer types.
6451   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6452 }
6453 
6454 /// \brief Return the resulting type when the operands are both pointers.
6455 static QualType
6456 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6457                                             ExprResult &RHS,
6458                                             SourceLocation Loc) {
6459   // get the pointer types
6460   QualType LHSTy = LHS.get()->getType();
6461   QualType RHSTy = RHS.get()->getType();
6462 
6463   // get the "pointed to" types
6464   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6465   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6466 
6467   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6468   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6469     // Figure out necessary qualifiers (C99 6.5.15p6)
6470     QualType destPointee
6471       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6472     QualType destType = S.Context.getPointerType(destPointee);
6473     // Add qualifiers if necessary.
6474     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6475     // Promote to void*.
6476     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6477     return destType;
6478   }
6479   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6480     QualType destPointee
6481       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6482     QualType destType = S.Context.getPointerType(destPointee);
6483     // Add qualifiers if necessary.
6484     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6485     // Promote to void*.
6486     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6487     return destType;
6488   }
6489 
6490   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6491 }
6492 
6493 /// \brief Return false if the first expression is not an integer and the second
6494 /// expression is not a pointer, true otherwise.
6495 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6496                                         Expr* PointerExpr, SourceLocation Loc,
6497                                         bool IsIntFirstExpr) {
6498   if (!PointerExpr->getType()->isPointerType() ||
6499       !Int.get()->getType()->isIntegerType())
6500     return false;
6501 
6502   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6503   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6504 
6505   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6506     << Expr1->getType() << Expr2->getType()
6507     << Expr1->getSourceRange() << Expr2->getSourceRange();
6508   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6509                             CK_IntegralToPointer);
6510   return true;
6511 }
6512 
6513 /// \brief Simple conversion between integer and floating point types.
6514 ///
6515 /// Used when handling the OpenCL conditional operator where the
6516 /// condition is a vector while the other operands are scalar.
6517 ///
6518 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6519 /// types are either integer or floating type. Between the two
6520 /// operands, the type with the higher rank is defined as the "result
6521 /// type". The other operand needs to be promoted to the same type. No
6522 /// other type promotion is allowed. We cannot use
6523 /// UsualArithmeticConversions() for this purpose, since it always
6524 /// promotes promotable types.
6525 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6526                                             ExprResult &RHS,
6527                                             SourceLocation QuestionLoc) {
6528   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6529   if (LHS.isInvalid())
6530     return QualType();
6531   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6532   if (RHS.isInvalid())
6533     return QualType();
6534 
6535   // For conversion purposes, we ignore any qualifiers.
6536   // For example, "const float" and "float" are equivalent.
6537   QualType LHSType =
6538     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6539   QualType RHSType =
6540     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6541 
6542   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6543     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6544       << LHSType << LHS.get()->getSourceRange();
6545     return QualType();
6546   }
6547 
6548   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6549     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6550       << RHSType << RHS.get()->getSourceRange();
6551     return QualType();
6552   }
6553 
6554   // If both types are identical, no conversion is needed.
6555   if (LHSType == RHSType)
6556     return LHSType;
6557 
6558   // Now handle "real" floating types (i.e. float, double, long double).
6559   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6560     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6561                                  /*IsCompAssign = */ false);
6562 
6563   // Finally, we have two differing integer types.
6564   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6565   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6566 }
6567 
6568 /// \brief Convert scalar operands to a vector that matches the
6569 ///        condition in length.
6570 ///
6571 /// Used when handling the OpenCL conditional operator where the
6572 /// condition is a vector while the other operands are scalar.
6573 ///
6574 /// We first compute the "result type" for the scalar operands
6575 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6576 /// into a vector of that type where the length matches the condition
6577 /// vector type. s6.11.6 requires that the element types of the result
6578 /// and the condition must have the same number of bits.
6579 static QualType
6580 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6581                               QualType CondTy, SourceLocation QuestionLoc) {
6582   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6583   if (ResTy.isNull()) return QualType();
6584 
6585   const VectorType *CV = CondTy->getAs<VectorType>();
6586   assert(CV);
6587 
6588   // Determine the vector result type
6589   unsigned NumElements = CV->getNumElements();
6590   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6591 
6592   // Ensure that all types have the same number of bits
6593   if (S.Context.getTypeSize(CV->getElementType())
6594       != S.Context.getTypeSize(ResTy)) {
6595     // Since VectorTy is created internally, it does not pretty print
6596     // with an OpenCL name. Instead, we just print a description.
6597     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6598     SmallString<64> Str;
6599     llvm::raw_svector_ostream OS(Str);
6600     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6601     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6602       << CondTy << OS.str();
6603     return QualType();
6604   }
6605 
6606   // Convert operands to the vector result type
6607   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6608   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6609 
6610   return VectorTy;
6611 }
6612 
6613 /// \brief Return false if this is a valid OpenCL condition vector
6614 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6615                                        SourceLocation QuestionLoc) {
6616   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6617   // integral type.
6618   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6619   assert(CondTy);
6620   QualType EleTy = CondTy->getElementType();
6621   if (EleTy->isIntegerType()) return false;
6622 
6623   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6624     << Cond->getType() << Cond->getSourceRange();
6625   return true;
6626 }
6627 
6628 /// \brief Return false if the vector condition type and the vector
6629 ///        result type are compatible.
6630 ///
6631 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6632 /// number of elements, and their element types have the same number
6633 /// of bits.
6634 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6635                               SourceLocation QuestionLoc) {
6636   const VectorType *CV = CondTy->getAs<VectorType>();
6637   const VectorType *RV = VecResTy->getAs<VectorType>();
6638   assert(CV && RV);
6639 
6640   if (CV->getNumElements() != RV->getNumElements()) {
6641     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6642       << CondTy << VecResTy;
6643     return true;
6644   }
6645 
6646   QualType CVE = CV->getElementType();
6647   QualType RVE = RV->getElementType();
6648 
6649   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6650     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6651       << CondTy << VecResTy;
6652     return true;
6653   }
6654 
6655   return false;
6656 }
6657 
6658 /// \brief Return the resulting type for the conditional operator in
6659 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6660 ///        s6.3.i) when the condition is a vector type.
6661 static QualType
6662 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6663                              ExprResult &LHS, ExprResult &RHS,
6664                              SourceLocation QuestionLoc) {
6665   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6666   if (Cond.isInvalid())
6667     return QualType();
6668   QualType CondTy = Cond.get()->getType();
6669 
6670   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6671     return QualType();
6672 
6673   // If either operand is a vector then find the vector type of the
6674   // result as specified in OpenCL v1.1 s6.3.i.
6675   if (LHS.get()->getType()->isVectorType() ||
6676       RHS.get()->getType()->isVectorType()) {
6677     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6678                                               /*isCompAssign*/false,
6679                                               /*AllowBothBool*/true,
6680                                               /*AllowBoolConversions*/false);
6681     if (VecResTy.isNull()) return QualType();
6682     // The result type must match the condition type as specified in
6683     // OpenCL v1.1 s6.11.6.
6684     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6685       return QualType();
6686     return VecResTy;
6687   }
6688 
6689   // Both operands are scalar.
6690   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6691 }
6692 
6693 /// \brief Return true if the Expr is block type
6694 static bool checkBlockType(Sema &S, const Expr *E) {
6695   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6696     QualType Ty = CE->getCallee()->getType();
6697     if (Ty->isBlockPointerType()) {
6698       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6699       return true;
6700     }
6701   }
6702   return false;
6703 }
6704 
6705 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6706 /// In that case, LHS = cond.
6707 /// C99 6.5.15
6708 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6709                                         ExprResult &RHS, ExprValueKind &VK,
6710                                         ExprObjectKind &OK,
6711                                         SourceLocation QuestionLoc) {
6712 
6713   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6714   if (!LHSResult.isUsable()) return QualType();
6715   LHS = LHSResult;
6716 
6717   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6718   if (!RHSResult.isUsable()) return QualType();
6719   RHS = RHSResult;
6720 
6721   // C++ is sufficiently different to merit its own checker.
6722   if (getLangOpts().CPlusPlus)
6723     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6724 
6725   VK = VK_RValue;
6726   OK = OK_Ordinary;
6727 
6728   // The OpenCL operator with a vector condition is sufficiently
6729   // different to merit its own checker.
6730   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6731     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6732 
6733   // First, check the condition.
6734   Cond = UsualUnaryConversions(Cond.get());
6735   if (Cond.isInvalid())
6736     return QualType();
6737   if (checkCondition(*this, Cond.get(), QuestionLoc))
6738     return QualType();
6739 
6740   // Now check the two expressions.
6741   if (LHS.get()->getType()->isVectorType() ||
6742       RHS.get()->getType()->isVectorType())
6743     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6744                                /*AllowBothBool*/true,
6745                                /*AllowBoolConversions*/false);
6746 
6747   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6748   if (LHS.isInvalid() || RHS.isInvalid())
6749     return QualType();
6750 
6751   QualType LHSTy = LHS.get()->getType();
6752   QualType RHSTy = RHS.get()->getType();
6753 
6754   // Diagnose attempts to convert between __float128 and long double where
6755   // such conversions currently can't be handled.
6756   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6757     Diag(QuestionLoc,
6758          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6759       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6760     return QualType();
6761   }
6762 
6763   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6764   // selection operator (?:).
6765   if (getLangOpts().OpenCL &&
6766       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6767     return QualType();
6768   }
6769 
6770   // If both operands have arithmetic type, do the usual arithmetic conversions
6771   // to find a common type: C99 6.5.15p3,5.
6772   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6773     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6774     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6775 
6776     return ResTy;
6777   }
6778 
6779   // If both operands are the same structure or union type, the result is that
6780   // type.
6781   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6782     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6783       if (LHSRT->getDecl() == RHSRT->getDecl())
6784         // "If both the operands have structure or union type, the result has
6785         // that type."  This implies that CV qualifiers are dropped.
6786         return LHSTy.getUnqualifiedType();
6787     // FIXME: Type of conditional expression must be complete in C mode.
6788   }
6789 
6790   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6791   // The following || allows only one side to be void (a GCC-ism).
6792   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6793     return checkConditionalVoidType(*this, LHS, RHS);
6794   }
6795 
6796   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6797   // the type of the other operand."
6798   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6799   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6800 
6801   // All objective-c pointer type analysis is done here.
6802   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6803                                                         QuestionLoc);
6804   if (LHS.isInvalid() || RHS.isInvalid())
6805     return QualType();
6806   if (!compositeType.isNull())
6807     return compositeType;
6808 
6809 
6810   // Handle block pointer types.
6811   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6812     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6813                                                      QuestionLoc);
6814 
6815   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6816   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6817     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6818                                                        QuestionLoc);
6819 
6820   // GCC compatibility: soften pointer/integer mismatch.  Note that
6821   // null pointers have been filtered out by this point.
6822   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6823       /*isIntFirstExpr=*/true))
6824     return RHSTy;
6825   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6826       /*isIntFirstExpr=*/false))
6827     return LHSTy;
6828 
6829   // Emit a better diagnostic if one of the expressions is a null pointer
6830   // constant and the other is not a pointer type. In this case, the user most
6831   // likely forgot to take the address of the other expression.
6832   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6833     return QualType();
6834 
6835   // Otherwise, the operands are not compatible.
6836   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6837     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6838     << RHS.get()->getSourceRange();
6839   return QualType();
6840 }
6841 
6842 /// FindCompositeObjCPointerType - Helper method to find composite type of
6843 /// two objective-c pointer types of the two input expressions.
6844 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6845                                             SourceLocation QuestionLoc) {
6846   QualType LHSTy = LHS.get()->getType();
6847   QualType RHSTy = RHS.get()->getType();
6848 
6849   // Handle things like Class and struct objc_class*.  Here we case the result
6850   // to the pseudo-builtin, because that will be implicitly cast back to the
6851   // redefinition type if an attempt is made to access its fields.
6852   if (LHSTy->isObjCClassType() &&
6853       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6854     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6855     return LHSTy;
6856   }
6857   if (RHSTy->isObjCClassType() &&
6858       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6859     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6860     return RHSTy;
6861   }
6862   // And the same for struct objc_object* / id
6863   if (LHSTy->isObjCIdType() &&
6864       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6865     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6866     return LHSTy;
6867   }
6868   if (RHSTy->isObjCIdType() &&
6869       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6870     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6871     return RHSTy;
6872   }
6873   // And the same for struct objc_selector* / SEL
6874   if (Context.isObjCSelType(LHSTy) &&
6875       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6876     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6877     return LHSTy;
6878   }
6879   if (Context.isObjCSelType(RHSTy) &&
6880       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6881     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6882     return RHSTy;
6883   }
6884   // Check constraints for Objective-C object pointers types.
6885   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6886 
6887     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6888       // Two identical object pointer types are always compatible.
6889       return LHSTy;
6890     }
6891     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6892     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6893     QualType compositeType = LHSTy;
6894 
6895     // If both operands are interfaces and either operand can be
6896     // assigned to the other, use that type as the composite
6897     // type. This allows
6898     //   xxx ? (A*) a : (B*) b
6899     // where B is a subclass of A.
6900     //
6901     // Additionally, as for assignment, if either type is 'id'
6902     // allow silent coercion. Finally, if the types are
6903     // incompatible then make sure to use 'id' as the composite
6904     // type so the result is acceptable for sending messages to.
6905 
6906     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6907     // It could return the composite type.
6908     if (!(compositeType =
6909           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6910       // Nothing more to do.
6911     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6912       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6913     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6914       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6915     } else if ((LHSTy->isObjCQualifiedIdType() ||
6916                 RHSTy->isObjCQualifiedIdType()) &&
6917                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6918       // Need to handle "id<xx>" explicitly.
6919       // GCC allows qualified id and any Objective-C type to devolve to
6920       // id. Currently localizing to here until clear this should be
6921       // part of ObjCQualifiedIdTypesAreCompatible.
6922       compositeType = Context.getObjCIdType();
6923     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6924       compositeType = Context.getObjCIdType();
6925     } else {
6926       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6927       << LHSTy << RHSTy
6928       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6929       QualType incompatTy = Context.getObjCIdType();
6930       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6931       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6932       return incompatTy;
6933     }
6934     // The object pointer types are compatible.
6935     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6936     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6937     return compositeType;
6938   }
6939   // Check Objective-C object pointer types and 'void *'
6940   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6941     if (getLangOpts().ObjCAutoRefCount) {
6942       // ARC forbids the implicit conversion of object pointers to 'void *',
6943       // so these types are not compatible.
6944       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6945           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6946       LHS = RHS = true;
6947       return QualType();
6948     }
6949     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6950     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6951     QualType destPointee
6952     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6953     QualType destType = Context.getPointerType(destPointee);
6954     // Add qualifiers if necessary.
6955     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6956     // Promote to void*.
6957     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6958     return destType;
6959   }
6960   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6961     if (getLangOpts().ObjCAutoRefCount) {
6962       // ARC forbids the implicit conversion of object pointers to 'void *',
6963       // so these types are not compatible.
6964       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6965           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6966       LHS = RHS = true;
6967       return QualType();
6968     }
6969     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6970     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6971     QualType destPointee
6972     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6973     QualType destType = Context.getPointerType(destPointee);
6974     // Add qualifiers if necessary.
6975     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6976     // Promote to void*.
6977     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6978     return destType;
6979   }
6980   return QualType();
6981 }
6982 
6983 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6984 /// ParenRange in parentheses.
6985 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6986                                const PartialDiagnostic &Note,
6987                                SourceRange ParenRange) {
6988   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6989   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6990       EndLoc.isValid()) {
6991     Self.Diag(Loc, Note)
6992       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6993       << FixItHint::CreateInsertion(EndLoc, ")");
6994   } else {
6995     // We can't display the parentheses, so just show the bare note.
6996     Self.Diag(Loc, Note) << ParenRange;
6997   }
6998 }
6999 
7000 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7001   return BinaryOperator::isAdditiveOp(Opc) ||
7002          BinaryOperator::isMultiplicativeOp(Opc) ||
7003          BinaryOperator::isShiftOp(Opc);
7004 }
7005 
7006 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7007 /// expression, either using a built-in or overloaded operator,
7008 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7009 /// expression.
7010 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7011                                    Expr **RHSExprs) {
7012   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7013   E = E->IgnoreImpCasts();
7014   E = E->IgnoreConversionOperator();
7015   E = E->IgnoreImpCasts();
7016 
7017   // Built-in binary operator.
7018   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7019     if (IsArithmeticOp(OP->getOpcode())) {
7020       *Opcode = OP->getOpcode();
7021       *RHSExprs = OP->getRHS();
7022       return true;
7023     }
7024   }
7025 
7026   // Overloaded operator.
7027   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7028     if (Call->getNumArgs() != 2)
7029       return false;
7030 
7031     // Make sure this is really a binary operator that is safe to pass into
7032     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7033     OverloadedOperatorKind OO = Call->getOperator();
7034     if (OO < OO_Plus || OO > OO_Arrow ||
7035         OO == OO_PlusPlus || OO == OO_MinusMinus)
7036       return false;
7037 
7038     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7039     if (IsArithmeticOp(OpKind)) {
7040       *Opcode = OpKind;
7041       *RHSExprs = Call->getArg(1);
7042       return true;
7043     }
7044   }
7045 
7046   return false;
7047 }
7048 
7049 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7050 /// or is a logical expression such as (x==y) which has int type, but is
7051 /// commonly interpreted as boolean.
7052 static bool ExprLooksBoolean(Expr *E) {
7053   E = E->IgnoreParenImpCasts();
7054 
7055   if (E->getType()->isBooleanType())
7056     return true;
7057   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7058     return OP->isComparisonOp() || OP->isLogicalOp();
7059   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7060     return OP->getOpcode() == UO_LNot;
7061   if (E->getType()->isPointerType())
7062     return true;
7063 
7064   return false;
7065 }
7066 
7067 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7068 /// and binary operator are mixed in a way that suggests the programmer assumed
7069 /// the conditional operator has higher precedence, for example:
7070 /// "int x = a + someBinaryCondition ? 1 : 2".
7071 static void DiagnoseConditionalPrecedence(Sema &Self,
7072                                           SourceLocation OpLoc,
7073                                           Expr *Condition,
7074                                           Expr *LHSExpr,
7075                                           Expr *RHSExpr) {
7076   BinaryOperatorKind CondOpcode;
7077   Expr *CondRHS;
7078 
7079   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7080     return;
7081   if (!ExprLooksBoolean(CondRHS))
7082     return;
7083 
7084   // The condition is an arithmetic binary expression, with a right-
7085   // hand side that looks boolean, so warn.
7086 
7087   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7088       << Condition->getSourceRange()
7089       << BinaryOperator::getOpcodeStr(CondOpcode);
7090 
7091   SuggestParentheses(Self, OpLoc,
7092     Self.PDiag(diag::note_precedence_silence)
7093       << BinaryOperator::getOpcodeStr(CondOpcode),
7094     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7095 
7096   SuggestParentheses(Self, OpLoc,
7097     Self.PDiag(diag::note_precedence_conditional_first),
7098     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7099 }
7100 
7101 /// Compute the nullability of a conditional expression.
7102 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7103                                               QualType LHSTy, QualType RHSTy,
7104                                               ASTContext &Ctx) {
7105   if (!ResTy->isAnyPointerType())
7106     return ResTy;
7107 
7108   auto GetNullability = [&Ctx](QualType Ty) {
7109     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7110     if (Kind)
7111       return *Kind;
7112     return NullabilityKind::Unspecified;
7113   };
7114 
7115   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7116   NullabilityKind MergedKind;
7117 
7118   // Compute nullability of a binary conditional expression.
7119   if (IsBin) {
7120     if (LHSKind == NullabilityKind::NonNull)
7121       MergedKind = NullabilityKind::NonNull;
7122     else
7123       MergedKind = RHSKind;
7124   // Compute nullability of a normal conditional expression.
7125   } else {
7126     if (LHSKind == NullabilityKind::Nullable ||
7127         RHSKind == NullabilityKind::Nullable)
7128       MergedKind = NullabilityKind::Nullable;
7129     else if (LHSKind == NullabilityKind::NonNull)
7130       MergedKind = RHSKind;
7131     else if (RHSKind == NullabilityKind::NonNull)
7132       MergedKind = LHSKind;
7133     else
7134       MergedKind = NullabilityKind::Unspecified;
7135   }
7136 
7137   // Return if ResTy already has the correct nullability.
7138   if (GetNullability(ResTy) == MergedKind)
7139     return ResTy;
7140 
7141   // Strip all nullability from ResTy.
7142   while (ResTy->getNullability(Ctx))
7143     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7144 
7145   // Create a new AttributedType with the new nullability kind.
7146   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7147   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7148 }
7149 
7150 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7151 /// in the case of a the GNU conditional expr extension.
7152 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7153                                     SourceLocation ColonLoc,
7154                                     Expr *CondExpr, Expr *LHSExpr,
7155                                     Expr *RHSExpr) {
7156   if (!getLangOpts().CPlusPlus) {
7157     // C cannot handle TypoExpr nodes in the condition because it
7158     // doesn't handle dependent types properly, so make sure any TypoExprs have
7159     // been dealt with before checking the operands.
7160     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7161     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7162     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7163 
7164     if (!CondResult.isUsable())
7165       return ExprError();
7166 
7167     if (LHSExpr) {
7168       if (!LHSResult.isUsable())
7169         return ExprError();
7170     }
7171 
7172     if (!RHSResult.isUsable())
7173       return ExprError();
7174 
7175     CondExpr = CondResult.get();
7176     LHSExpr = LHSResult.get();
7177     RHSExpr = RHSResult.get();
7178   }
7179 
7180   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7181   // was the condition.
7182   OpaqueValueExpr *opaqueValue = nullptr;
7183   Expr *commonExpr = nullptr;
7184   if (!LHSExpr) {
7185     commonExpr = CondExpr;
7186     // Lower out placeholder types first.  This is important so that we don't
7187     // try to capture a placeholder. This happens in few cases in C++; such
7188     // as Objective-C++'s dictionary subscripting syntax.
7189     if (commonExpr->hasPlaceholderType()) {
7190       ExprResult result = CheckPlaceholderExpr(commonExpr);
7191       if (!result.isUsable()) return ExprError();
7192       commonExpr = result.get();
7193     }
7194     // We usually want to apply unary conversions *before* saving, except
7195     // in the special case of a C++ l-value conditional.
7196     if (!(getLangOpts().CPlusPlus
7197           && !commonExpr->isTypeDependent()
7198           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7199           && commonExpr->isGLValue()
7200           && commonExpr->isOrdinaryOrBitFieldObject()
7201           && RHSExpr->isOrdinaryOrBitFieldObject()
7202           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7203       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7204       if (commonRes.isInvalid())
7205         return ExprError();
7206       commonExpr = commonRes.get();
7207     }
7208 
7209     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7210                                                 commonExpr->getType(),
7211                                                 commonExpr->getValueKind(),
7212                                                 commonExpr->getObjectKind(),
7213                                                 commonExpr);
7214     LHSExpr = CondExpr = opaqueValue;
7215   }
7216 
7217   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7218   ExprValueKind VK = VK_RValue;
7219   ExprObjectKind OK = OK_Ordinary;
7220   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7221   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7222                                              VK, OK, QuestionLoc);
7223   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7224       RHS.isInvalid())
7225     return ExprError();
7226 
7227   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7228                                 RHS.get());
7229 
7230   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7231 
7232   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7233                                          Context);
7234 
7235   if (!commonExpr)
7236     return new (Context)
7237         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7238                             RHS.get(), result, VK, OK);
7239 
7240   return new (Context) BinaryConditionalOperator(
7241       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7242       ColonLoc, result, VK, OK);
7243 }
7244 
7245 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7246 // being closely modeled after the C99 spec:-). The odd characteristic of this
7247 // routine is it effectively iqnores the qualifiers on the top level pointee.
7248 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7249 // FIXME: add a couple examples in this comment.
7250 static Sema::AssignConvertType
7251 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7252   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7253   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7254 
7255   // get the "pointed to" type (ignoring qualifiers at the top level)
7256   const Type *lhptee, *rhptee;
7257   Qualifiers lhq, rhq;
7258   std::tie(lhptee, lhq) =
7259       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7260   std::tie(rhptee, rhq) =
7261       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7262 
7263   Sema::AssignConvertType ConvTy = Sema::Compatible;
7264 
7265   // C99 6.5.16.1p1: This following citation is common to constraints
7266   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7267   // qualifiers of the type *pointed to* by the right;
7268 
7269   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7270   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7271       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7272     // Ignore lifetime for further calculation.
7273     lhq.removeObjCLifetime();
7274     rhq.removeObjCLifetime();
7275   }
7276 
7277   if (!lhq.compatiblyIncludes(rhq)) {
7278     // Treat address-space mismatches as fatal.  TODO: address subspaces
7279     if (!lhq.isAddressSpaceSupersetOf(rhq))
7280       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7281 
7282     // It's okay to add or remove GC or lifetime qualifiers when converting to
7283     // and from void*.
7284     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7285                         .compatiblyIncludes(
7286                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7287              && (lhptee->isVoidType() || rhptee->isVoidType()))
7288       ; // keep old
7289 
7290     // Treat lifetime mismatches as fatal.
7291     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7292       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7293 
7294     // For GCC/MS compatibility, other qualifier mismatches are treated
7295     // as still compatible in C.
7296     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7297   }
7298 
7299   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7300   // incomplete type and the other is a pointer to a qualified or unqualified
7301   // version of void...
7302   if (lhptee->isVoidType()) {
7303     if (rhptee->isIncompleteOrObjectType())
7304       return ConvTy;
7305 
7306     // As an extension, we allow cast to/from void* to function pointer.
7307     assert(rhptee->isFunctionType());
7308     return Sema::FunctionVoidPointer;
7309   }
7310 
7311   if (rhptee->isVoidType()) {
7312     if (lhptee->isIncompleteOrObjectType())
7313       return ConvTy;
7314 
7315     // As an extension, we allow cast to/from void* to function pointer.
7316     assert(lhptee->isFunctionType());
7317     return Sema::FunctionVoidPointer;
7318   }
7319 
7320   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7321   // unqualified versions of compatible types, ...
7322   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7323   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7324     // Check if the pointee types are compatible ignoring the sign.
7325     // We explicitly check for char so that we catch "char" vs
7326     // "unsigned char" on systems where "char" is unsigned.
7327     if (lhptee->isCharType())
7328       ltrans = S.Context.UnsignedCharTy;
7329     else if (lhptee->hasSignedIntegerRepresentation())
7330       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7331 
7332     if (rhptee->isCharType())
7333       rtrans = S.Context.UnsignedCharTy;
7334     else if (rhptee->hasSignedIntegerRepresentation())
7335       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7336 
7337     if (ltrans == rtrans) {
7338       // Types are compatible ignoring the sign. Qualifier incompatibility
7339       // takes priority over sign incompatibility because the sign
7340       // warning can be disabled.
7341       if (ConvTy != Sema::Compatible)
7342         return ConvTy;
7343 
7344       return Sema::IncompatiblePointerSign;
7345     }
7346 
7347     // If we are a multi-level pointer, it's possible that our issue is simply
7348     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7349     // the eventual target type is the same and the pointers have the same
7350     // level of indirection, this must be the issue.
7351     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7352       do {
7353         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7354         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7355       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7356 
7357       if (lhptee == rhptee)
7358         return Sema::IncompatibleNestedPointerQualifiers;
7359     }
7360 
7361     // General pointer incompatibility takes priority over qualifiers.
7362     return Sema::IncompatiblePointer;
7363   }
7364   if (!S.getLangOpts().CPlusPlus &&
7365       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7366     return Sema::IncompatiblePointer;
7367   return ConvTy;
7368 }
7369 
7370 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7371 /// block pointer types are compatible or whether a block and normal pointer
7372 /// are compatible. It is more restrict than comparing two function pointer
7373 // types.
7374 static Sema::AssignConvertType
7375 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7376                                     QualType RHSType) {
7377   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7378   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7379 
7380   QualType lhptee, rhptee;
7381 
7382   // get the "pointed to" type (ignoring qualifiers at the top level)
7383   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7384   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7385 
7386   // In C++, the types have to match exactly.
7387   if (S.getLangOpts().CPlusPlus)
7388     return Sema::IncompatibleBlockPointer;
7389 
7390   Sema::AssignConvertType ConvTy = Sema::Compatible;
7391 
7392   // For blocks we enforce that qualifiers are identical.
7393   Qualifiers LQuals = lhptee.getLocalQualifiers();
7394   Qualifiers RQuals = rhptee.getLocalQualifiers();
7395   if (S.getLangOpts().OpenCL) {
7396     LQuals.removeAddressSpace();
7397     RQuals.removeAddressSpace();
7398   }
7399   if (LQuals != RQuals)
7400     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7401 
7402   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7403     return Sema::IncompatibleBlockPointer;
7404 
7405   return ConvTy;
7406 }
7407 
7408 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7409 /// for assignment compatibility.
7410 static Sema::AssignConvertType
7411 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7412                                    QualType RHSType) {
7413   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7414   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7415 
7416   if (LHSType->isObjCBuiltinType()) {
7417     // Class is not compatible with ObjC object pointers.
7418     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7419         !RHSType->isObjCQualifiedClassType())
7420       return Sema::IncompatiblePointer;
7421     return Sema::Compatible;
7422   }
7423   if (RHSType->isObjCBuiltinType()) {
7424     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7425         !LHSType->isObjCQualifiedClassType())
7426       return Sema::IncompatiblePointer;
7427     return Sema::Compatible;
7428   }
7429   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7430   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7431 
7432   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7433       // make an exception for id<P>
7434       !LHSType->isObjCQualifiedIdType())
7435     return Sema::CompatiblePointerDiscardsQualifiers;
7436 
7437   if (S.Context.typesAreCompatible(LHSType, RHSType))
7438     return Sema::Compatible;
7439   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7440     return Sema::IncompatibleObjCQualifiedId;
7441   return Sema::IncompatiblePointer;
7442 }
7443 
7444 Sema::AssignConvertType
7445 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7446                                  QualType LHSType, QualType RHSType) {
7447   // Fake up an opaque expression.  We don't actually care about what
7448   // cast operations are required, so if CheckAssignmentConstraints
7449   // adds casts to this they'll be wasted, but fortunately that doesn't
7450   // usually happen on valid code.
7451   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7452   ExprResult RHSPtr = &RHSExpr;
7453   CastKind K = CK_Invalid;
7454 
7455   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7456 }
7457 
7458 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7459 /// has code to accommodate several GCC extensions when type checking
7460 /// pointers. Here are some objectionable examples that GCC considers warnings:
7461 ///
7462 ///  int a, *pint;
7463 ///  short *pshort;
7464 ///  struct foo *pfoo;
7465 ///
7466 ///  pint = pshort; // warning: assignment from incompatible pointer type
7467 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7468 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7469 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7470 ///
7471 /// As a result, the code for dealing with pointers is more complex than the
7472 /// C99 spec dictates.
7473 ///
7474 /// Sets 'Kind' for any result kind except Incompatible.
7475 Sema::AssignConvertType
7476 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7477                                  CastKind &Kind, bool ConvertRHS) {
7478   QualType RHSType = RHS.get()->getType();
7479   QualType OrigLHSType = LHSType;
7480 
7481   // Get canonical types.  We're not formatting these types, just comparing
7482   // them.
7483   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7484   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7485 
7486   // Common case: no conversion required.
7487   if (LHSType == RHSType) {
7488     Kind = CK_NoOp;
7489     return Compatible;
7490   }
7491 
7492   // If we have an atomic type, try a non-atomic assignment, then just add an
7493   // atomic qualification step.
7494   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7495     Sema::AssignConvertType result =
7496       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7497     if (result != Compatible)
7498       return result;
7499     if (Kind != CK_NoOp && ConvertRHS)
7500       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7501     Kind = CK_NonAtomicToAtomic;
7502     return Compatible;
7503   }
7504 
7505   // If the left-hand side is a reference type, then we are in a
7506   // (rare!) case where we've allowed the use of references in C,
7507   // e.g., as a parameter type in a built-in function. In this case,
7508   // just make sure that the type referenced is compatible with the
7509   // right-hand side type. The caller is responsible for adjusting
7510   // LHSType so that the resulting expression does not have reference
7511   // type.
7512   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7513     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7514       Kind = CK_LValueBitCast;
7515       return Compatible;
7516     }
7517     return Incompatible;
7518   }
7519 
7520   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7521   // to the same ExtVector type.
7522   if (LHSType->isExtVectorType()) {
7523     if (RHSType->isExtVectorType())
7524       return Incompatible;
7525     if (RHSType->isArithmeticType()) {
7526       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7527       if (ConvertRHS)
7528         RHS = prepareVectorSplat(LHSType, RHS.get());
7529       Kind = CK_VectorSplat;
7530       return Compatible;
7531     }
7532   }
7533 
7534   // Conversions to or from vector type.
7535   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7536     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7537       // Allow assignments of an AltiVec vector type to an equivalent GCC
7538       // vector type and vice versa
7539       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7540         Kind = CK_BitCast;
7541         return Compatible;
7542       }
7543 
7544       // If we are allowing lax vector conversions, and LHS and RHS are both
7545       // vectors, the total size only needs to be the same. This is a bitcast;
7546       // no bits are changed but the result type is different.
7547       if (isLaxVectorConversion(RHSType, LHSType)) {
7548         Kind = CK_BitCast;
7549         return IncompatibleVectors;
7550       }
7551     }
7552 
7553     // When the RHS comes from another lax conversion (e.g. binops between
7554     // scalars and vectors) the result is canonicalized as a vector. When the
7555     // LHS is also a vector, the lax is allowed by the condition above. Handle
7556     // the case where LHS is a scalar.
7557     if (LHSType->isScalarType()) {
7558       const VectorType *VecType = RHSType->getAs<VectorType>();
7559       if (VecType && VecType->getNumElements() == 1 &&
7560           isLaxVectorConversion(RHSType, LHSType)) {
7561         ExprResult *VecExpr = &RHS;
7562         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7563         Kind = CK_BitCast;
7564         return Compatible;
7565       }
7566     }
7567 
7568     return Incompatible;
7569   }
7570 
7571   // Diagnose attempts to convert between __float128 and long double where
7572   // such conversions currently can't be handled.
7573   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7574     return Incompatible;
7575 
7576   // Arithmetic conversions.
7577   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7578       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7579     if (ConvertRHS)
7580       Kind = PrepareScalarCast(RHS, LHSType);
7581     return Compatible;
7582   }
7583 
7584   // Conversions to normal pointers.
7585   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7586     // U* -> T*
7587     if (isa<PointerType>(RHSType)) {
7588       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7589       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7590       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7591       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7592     }
7593 
7594     // int -> T*
7595     if (RHSType->isIntegerType()) {
7596       Kind = CK_IntegralToPointer; // FIXME: null?
7597       return IntToPointer;
7598     }
7599 
7600     // C pointers are not compatible with ObjC object pointers,
7601     // with two exceptions:
7602     if (isa<ObjCObjectPointerType>(RHSType)) {
7603       //  - conversions to void*
7604       if (LHSPointer->getPointeeType()->isVoidType()) {
7605         Kind = CK_BitCast;
7606         return Compatible;
7607       }
7608 
7609       //  - conversions from 'Class' to the redefinition type
7610       if (RHSType->isObjCClassType() &&
7611           Context.hasSameType(LHSType,
7612                               Context.getObjCClassRedefinitionType())) {
7613         Kind = CK_BitCast;
7614         return Compatible;
7615       }
7616 
7617       Kind = CK_BitCast;
7618       return IncompatiblePointer;
7619     }
7620 
7621     // U^ -> void*
7622     if (RHSType->getAs<BlockPointerType>()) {
7623       if (LHSPointer->getPointeeType()->isVoidType()) {
7624         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7625         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7626                                   ->getPointeeType()
7627                                   .getAddressSpace();
7628         Kind =
7629             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7630         return Compatible;
7631       }
7632     }
7633 
7634     return Incompatible;
7635   }
7636 
7637   // Conversions to block pointers.
7638   if (isa<BlockPointerType>(LHSType)) {
7639     // U^ -> T^
7640     if (RHSType->isBlockPointerType()) {
7641       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7642                                 ->getPointeeType()
7643                                 .getAddressSpace();
7644       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7645                                 ->getPointeeType()
7646                                 .getAddressSpace();
7647       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7648       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7649     }
7650 
7651     // int or null -> T^
7652     if (RHSType->isIntegerType()) {
7653       Kind = CK_IntegralToPointer; // FIXME: null
7654       return IntToBlockPointer;
7655     }
7656 
7657     // id -> T^
7658     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7659       Kind = CK_AnyPointerToBlockPointerCast;
7660       return Compatible;
7661     }
7662 
7663     // void* -> T^
7664     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7665       if (RHSPT->getPointeeType()->isVoidType()) {
7666         Kind = CK_AnyPointerToBlockPointerCast;
7667         return Compatible;
7668       }
7669 
7670     return Incompatible;
7671   }
7672 
7673   // Conversions to Objective-C pointers.
7674   if (isa<ObjCObjectPointerType>(LHSType)) {
7675     // A* -> B*
7676     if (RHSType->isObjCObjectPointerType()) {
7677       Kind = CK_BitCast;
7678       Sema::AssignConvertType result =
7679         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7680       if (getLangOpts().ObjCAutoRefCount &&
7681           result == Compatible &&
7682           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7683         result = IncompatibleObjCWeakRef;
7684       return result;
7685     }
7686 
7687     // int or null -> A*
7688     if (RHSType->isIntegerType()) {
7689       Kind = CK_IntegralToPointer; // FIXME: null
7690       return IntToPointer;
7691     }
7692 
7693     // In general, C pointers are not compatible with ObjC object pointers,
7694     // with two exceptions:
7695     if (isa<PointerType>(RHSType)) {
7696       Kind = CK_CPointerToObjCPointerCast;
7697 
7698       //  - conversions from 'void*'
7699       if (RHSType->isVoidPointerType()) {
7700         return Compatible;
7701       }
7702 
7703       //  - conversions to 'Class' from its redefinition type
7704       if (LHSType->isObjCClassType() &&
7705           Context.hasSameType(RHSType,
7706                               Context.getObjCClassRedefinitionType())) {
7707         return Compatible;
7708       }
7709 
7710       return IncompatiblePointer;
7711     }
7712 
7713     // Only under strict condition T^ is compatible with an Objective-C pointer.
7714     if (RHSType->isBlockPointerType() &&
7715         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7716       if (ConvertRHS)
7717         maybeExtendBlockObject(RHS);
7718       Kind = CK_BlockPointerToObjCPointerCast;
7719       return Compatible;
7720     }
7721 
7722     return Incompatible;
7723   }
7724 
7725   // Conversions from pointers that are not covered by the above.
7726   if (isa<PointerType>(RHSType)) {
7727     // T* -> _Bool
7728     if (LHSType == Context.BoolTy) {
7729       Kind = CK_PointerToBoolean;
7730       return Compatible;
7731     }
7732 
7733     // T* -> int
7734     if (LHSType->isIntegerType()) {
7735       Kind = CK_PointerToIntegral;
7736       return PointerToInt;
7737     }
7738 
7739     return Incompatible;
7740   }
7741 
7742   // Conversions from Objective-C pointers that are not covered by the above.
7743   if (isa<ObjCObjectPointerType>(RHSType)) {
7744     // T* -> _Bool
7745     if (LHSType == Context.BoolTy) {
7746       Kind = CK_PointerToBoolean;
7747       return Compatible;
7748     }
7749 
7750     // T* -> int
7751     if (LHSType->isIntegerType()) {
7752       Kind = CK_PointerToIntegral;
7753       return PointerToInt;
7754     }
7755 
7756     return Incompatible;
7757   }
7758 
7759   // struct A -> struct B
7760   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7761     if (Context.typesAreCompatible(LHSType, RHSType)) {
7762       Kind = CK_NoOp;
7763       return Compatible;
7764     }
7765   }
7766 
7767   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7768     Kind = CK_IntToOCLSampler;
7769     return Compatible;
7770   }
7771 
7772   return Incompatible;
7773 }
7774 
7775 /// \brief Constructs a transparent union from an expression that is
7776 /// used to initialize the transparent union.
7777 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7778                                       ExprResult &EResult, QualType UnionType,
7779                                       FieldDecl *Field) {
7780   // Build an initializer list that designates the appropriate member
7781   // of the transparent union.
7782   Expr *E = EResult.get();
7783   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7784                                                    E, SourceLocation());
7785   Initializer->setType(UnionType);
7786   Initializer->setInitializedFieldInUnion(Field);
7787 
7788   // Build a compound literal constructing a value of the transparent
7789   // union type from this initializer list.
7790   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7791   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7792                                         VK_RValue, Initializer, false);
7793 }
7794 
7795 Sema::AssignConvertType
7796 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7797                                                ExprResult &RHS) {
7798   QualType RHSType = RHS.get()->getType();
7799 
7800   // If the ArgType is a Union type, we want to handle a potential
7801   // transparent_union GCC extension.
7802   const RecordType *UT = ArgType->getAsUnionType();
7803   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7804     return Incompatible;
7805 
7806   // The field to initialize within the transparent union.
7807   RecordDecl *UD = UT->getDecl();
7808   FieldDecl *InitField = nullptr;
7809   // It's compatible if the expression matches any of the fields.
7810   for (auto *it : UD->fields()) {
7811     if (it->getType()->isPointerType()) {
7812       // If the transparent union contains a pointer type, we allow:
7813       // 1) void pointer
7814       // 2) null pointer constant
7815       if (RHSType->isPointerType())
7816         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7817           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7818           InitField = it;
7819           break;
7820         }
7821 
7822       if (RHS.get()->isNullPointerConstant(Context,
7823                                            Expr::NPC_ValueDependentIsNull)) {
7824         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7825                                 CK_NullToPointer);
7826         InitField = it;
7827         break;
7828       }
7829     }
7830 
7831     CastKind Kind = CK_Invalid;
7832     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7833           == Compatible) {
7834       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7835       InitField = it;
7836       break;
7837     }
7838   }
7839 
7840   if (!InitField)
7841     return Incompatible;
7842 
7843   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7844   return Compatible;
7845 }
7846 
7847 Sema::AssignConvertType
7848 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7849                                        bool Diagnose,
7850                                        bool DiagnoseCFAudited,
7851                                        bool ConvertRHS) {
7852   // We need to be able to tell the caller whether we diagnosed a problem, if
7853   // they ask us to issue diagnostics.
7854   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7855 
7856   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7857   // we can't avoid *all* modifications at the moment, so we need some somewhere
7858   // to put the updated value.
7859   ExprResult LocalRHS = CallerRHS;
7860   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7861 
7862   if (getLangOpts().CPlusPlus) {
7863     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7864       // C++ 5.17p3: If the left operand is not of class type, the
7865       // expression is implicitly converted (C++ 4) to the
7866       // cv-unqualified type of the left operand.
7867       QualType RHSType = RHS.get()->getType();
7868       if (Diagnose) {
7869         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7870                                         AA_Assigning);
7871       } else {
7872         ImplicitConversionSequence ICS =
7873             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7874                                   /*SuppressUserConversions=*/false,
7875                                   /*AllowExplicit=*/false,
7876                                   /*InOverloadResolution=*/false,
7877                                   /*CStyle=*/false,
7878                                   /*AllowObjCWritebackConversion=*/false);
7879         if (ICS.isFailure())
7880           return Incompatible;
7881         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7882                                         ICS, AA_Assigning);
7883       }
7884       if (RHS.isInvalid())
7885         return Incompatible;
7886       Sema::AssignConvertType result = Compatible;
7887       if (getLangOpts().ObjCAutoRefCount &&
7888           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7889         result = IncompatibleObjCWeakRef;
7890       return result;
7891     }
7892 
7893     // FIXME: Currently, we fall through and treat C++ classes like C
7894     // structures.
7895     // FIXME: We also fall through for atomics; not sure what should
7896     // happen there, though.
7897   } else if (RHS.get()->getType() == Context.OverloadTy) {
7898     // As a set of extensions to C, we support overloading on functions. These
7899     // functions need to be resolved here.
7900     DeclAccessPair DAP;
7901     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7902             RHS.get(), LHSType, /*Complain=*/false, DAP))
7903       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7904     else
7905       return Incompatible;
7906   }
7907 
7908   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7909   // a null pointer constant.
7910   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7911        LHSType->isBlockPointerType()) &&
7912       RHS.get()->isNullPointerConstant(Context,
7913                                        Expr::NPC_ValueDependentIsNull)) {
7914     if (Diagnose || ConvertRHS) {
7915       CastKind Kind;
7916       CXXCastPath Path;
7917       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7918                              /*IgnoreBaseAccess=*/false, Diagnose);
7919       if (ConvertRHS)
7920         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7921     }
7922     return Compatible;
7923   }
7924 
7925   // This check seems unnatural, however it is necessary to ensure the proper
7926   // conversion of functions/arrays. If the conversion were done for all
7927   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7928   // expressions that suppress this implicit conversion (&, sizeof).
7929   //
7930   // Suppress this for references: C++ 8.5.3p5.
7931   if (!LHSType->isReferenceType()) {
7932     // FIXME: We potentially allocate here even if ConvertRHS is false.
7933     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7934     if (RHS.isInvalid())
7935       return Incompatible;
7936   }
7937 
7938   Expr *PRE = RHS.get()->IgnoreParenCasts();
7939   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7940     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7941     if (PDecl && !PDecl->hasDefinition()) {
7942       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7943       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7944     }
7945   }
7946 
7947   CastKind Kind = CK_Invalid;
7948   Sema::AssignConvertType result =
7949     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7950 
7951   // C99 6.5.16.1p2: The value of the right operand is converted to the
7952   // type of the assignment expression.
7953   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7954   // so that we can use references in built-in functions even in C.
7955   // The getNonReferenceType() call makes sure that the resulting expression
7956   // does not have reference type.
7957   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7958     QualType Ty = LHSType.getNonLValueExprType(Context);
7959     Expr *E = RHS.get();
7960 
7961     // Check for various Objective-C errors. If we are not reporting
7962     // diagnostics and just checking for errors, e.g., during overload
7963     // resolution, return Incompatible to indicate the failure.
7964     if (getLangOpts().ObjCAutoRefCount &&
7965         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7966                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7967       if (!Diagnose)
7968         return Incompatible;
7969     }
7970     if (getLangOpts().ObjC1 &&
7971         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7972                                            E->getType(), E, Diagnose) ||
7973          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7974       if (!Diagnose)
7975         return Incompatible;
7976       // Replace the expression with a corrected version and continue so we
7977       // can find further errors.
7978       RHS = E;
7979       return Compatible;
7980     }
7981 
7982     if (ConvertRHS)
7983       RHS = ImpCastExprToType(E, Ty, Kind);
7984   }
7985   return result;
7986 }
7987 
7988 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7989                                ExprResult &RHS) {
7990   Diag(Loc, diag::err_typecheck_invalid_operands)
7991     << LHS.get()->getType() << RHS.get()->getType()
7992     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7993   return QualType();
7994 }
7995 
7996 /// Try to convert a value of non-vector type to a vector type by converting
7997 /// the type to the element type of the vector and then performing a splat.
7998 /// If the language is OpenCL, we only use conversions that promote scalar
7999 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8000 /// for float->int.
8001 ///
8002 /// \param scalar - if non-null, actually perform the conversions
8003 /// \return true if the operation fails (but without diagnosing the failure)
8004 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8005                                      QualType scalarTy,
8006                                      QualType vectorEltTy,
8007                                      QualType vectorTy) {
8008   // The conversion to apply to the scalar before splatting it,
8009   // if necessary.
8010   CastKind scalarCast = CK_Invalid;
8011 
8012   if (vectorEltTy->isIntegralType(S.Context)) {
8013     if (!scalarTy->isIntegralType(S.Context))
8014       return true;
8015     if (S.getLangOpts().OpenCL &&
8016         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8017       return true;
8018     scalarCast = CK_IntegralCast;
8019   } else if (vectorEltTy->isRealFloatingType()) {
8020     if (scalarTy->isRealFloatingType()) {
8021       if (S.getLangOpts().OpenCL &&
8022           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8023         return true;
8024       scalarCast = CK_FloatingCast;
8025     }
8026     else if (scalarTy->isIntegralType(S.Context))
8027       scalarCast = CK_IntegralToFloating;
8028     else
8029       return true;
8030   } else {
8031     return true;
8032   }
8033 
8034   // Adjust scalar if desired.
8035   if (scalar) {
8036     if (scalarCast != CK_Invalid)
8037       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8038     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8039   }
8040   return false;
8041 }
8042 
8043 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8044                                    SourceLocation Loc, bool IsCompAssign,
8045                                    bool AllowBothBool,
8046                                    bool AllowBoolConversions) {
8047   if (!IsCompAssign) {
8048     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8049     if (LHS.isInvalid())
8050       return QualType();
8051   }
8052   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8053   if (RHS.isInvalid())
8054     return QualType();
8055 
8056   // For conversion purposes, we ignore any qualifiers.
8057   // For example, "const float" and "float" are equivalent.
8058   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8059   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8060 
8061   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8062   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8063   assert(LHSVecType || RHSVecType);
8064 
8065   // AltiVec-style "vector bool op vector bool" combinations are allowed
8066   // for some operators but not others.
8067   if (!AllowBothBool &&
8068       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8069       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8070     return InvalidOperands(Loc, LHS, RHS);
8071 
8072   // If the vector types are identical, return.
8073   if (Context.hasSameType(LHSType, RHSType))
8074     return LHSType;
8075 
8076   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8077   if (LHSVecType && RHSVecType &&
8078       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8079     if (isa<ExtVectorType>(LHSVecType)) {
8080       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8081       return LHSType;
8082     }
8083 
8084     if (!IsCompAssign)
8085       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8086     return RHSType;
8087   }
8088 
8089   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8090   // can be mixed, with the result being the non-bool type.  The non-bool
8091   // operand must have integer element type.
8092   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8093       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8094       (Context.getTypeSize(LHSVecType->getElementType()) ==
8095        Context.getTypeSize(RHSVecType->getElementType()))) {
8096     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8097         LHSVecType->getElementType()->isIntegerType() &&
8098         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8099       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8100       return LHSType;
8101     }
8102     if (!IsCompAssign &&
8103         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8104         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8105         RHSVecType->getElementType()->isIntegerType()) {
8106       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8107       return RHSType;
8108     }
8109   }
8110 
8111   // If there's an ext-vector type and a scalar, try to convert the scalar to
8112   // the vector element type and splat.
8113   // FIXME: this should also work for regular vector types as supported in GCC.
8114   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8115     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8116                                   LHSVecType->getElementType(), LHSType))
8117       return LHSType;
8118   }
8119   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8120     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8121                                   LHSType, RHSVecType->getElementType(),
8122                                   RHSType))
8123       return RHSType;
8124   }
8125 
8126   // FIXME: The code below also handles convertion between vectors and
8127   // non-scalars, we should break this down into fine grained specific checks
8128   // and emit proper diagnostics.
8129   QualType VecType = LHSVecType ? LHSType : RHSType;
8130   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8131   QualType OtherType = LHSVecType ? RHSType : LHSType;
8132   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8133   if (isLaxVectorConversion(OtherType, VecType)) {
8134     // If we're allowing lax vector conversions, only the total (data) size
8135     // needs to be the same. For non compound assignment, if one of the types is
8136     // scalar, the result is always the vector type.
8137     if (!IsCompAssign) {
8138       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8139       return VecType;
8140     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8141     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8142     // type. Note that this is already done by non-compound assignments in
8143     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8144     // <1 x T> -> T. The result is also a vector type.
8145     } else if (OtherType->isExtVectorType() ||
8146                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8147       ExprResult *RHSExpr = &RHS;
8148       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8149       return VecType;
8150     }
8151   }
8152 
8153   // Okay, the expression is invalid.
8154 
8155   // If there's a non-vector, non-real operand, diagnose that.
8156   if ((!RHSVecType && !RHSType->isRealType()) ||
8157       (!LHSVecType && !LHSType->isRealType())) {
8158     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8159       << LHSType << RHSType
8160       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8161     return QualType();
8162   }
8163 
8164   // OpenCL V1.1 6.2.6.p1:
8165   // If the operands are of more than one vector type, then an error shall
8166   // occur. Implicit conversions between vector types are not permitted, per
8167   // section 6.2.1.
8168   if (getLangOpts().OpenCL &&
8169       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8170       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8171     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8172                                                            << RHSType;
8173     return QualType();
8174   }
8175 
8176   // Otherwise, use the generic diagnostic.
8177   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8178     << LHSType << RHSType
8179     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8180   return QualType();
8181 }
8182 
8183 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8184 // expression.  These are mainly cases where the null pointer is used as an
8185 // integer instead of a pointer.
8186 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8187                                 SourceLocation Loc, bool IsCompare) {
8188   // The canonical way to check for a GNU null is with isNullPointerConstant,
8189   // but we use a bit of a hack here for speed; this is a relatively
8190   // hot path, and isNullPointerConstant is slow.
8191   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8192   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8193 
8194   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8195 
8196   // Avoid analyzing cases where the result will either be invalid (and
8197   // diagnosed as such) or entirely valid and not something to warn about.
8198   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8199       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8200     return;
8201 
8202   // Comparison operations would not make sense with a null pointer no matter
8203   // what the other expression is.
8204   if (!IsCompare) {
8205     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8206         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8207         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8208     return;
8209   }
8210 
8211   // The rest of the operations only make sense with a null pointer
8212   // if the other expression is a pointer.
8213   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8214       NonNullType->canDecayToPointerType())
8215     return;
8216 
8217   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8218       << LHSNull /* LHS is NULL */ << NonNullType
8219       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8220 }
8221 
8222 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8223                                                ExprResult &RHS,
8224                                                SourceLocation Loc, bool IsDiv) {
8225   // Check for division/remainder by zero.
8226   llvm::APSInt RHSValue;
8227   if (!RHS.get()->isValueDependent() &&
8228       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8229     S.DiagRuntimeBehavior(Loc, RHS.get(),
8230                           S.PDiag(diag::warn_remainder_division_by_zero)
8231                             << IsDiv << RHS.get()->getSourceRange());
8232 }
8233 
8234 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8235                                            SourceLocation Loc,
8236                                            bool IsCompAssign, bool IsDiv) {
8237   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8238 
8239   if (LHS.get()->getType()->isVectorType() ||
8240       RHS.get()->getType()->isVectorType())
8241     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8242                                /*AllowBothBool*/getLangOpts().AltiVec,
8243                                /*AllowBoolConversions*/false);
8244 
8245   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8246   if (LHS.isInvalid() || RHS.isInvalid())
8247     return QualType();
8248 
8249 
8250   if (compType.isNull() || !compType->isArithmeticType())
8251     return InvalidOperands(Loc, LHS, RHS);
8252   if (IsDiv)
8253     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8254   return compType;
8255 }
8256 
8257 QualType Sema::CheckRemainderOperands(
8258   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8259   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8260 
8261   if (LHS.get()->getType()->isVectorType() ||
8262       RHS.get()->getType()->isVectorType()) {
8263     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8264         RHS.get()->getType()->hasIntegerRepresentation())
8265       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8266                                  /*AllowBothBool*/getLangOpts().AltiVec,
8267                                  /*AllowBoolConversions*/false);
8268     return InvalidOperands(Loc, LHS, RHS);
8269   }
8270 
8271   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8272   if (LHS.isInvalid() || RHS.isInvalid())
8273     return QualType();
8274 
8275   if (compType.isNull() || !compType->isIntegerType())
8276     return InvalidOperands(Loc, LHS, RHS);
8277   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8278   return compType;
8279 }
8280 
8281 /// \brief Diagnose invalid arithmetic on two void pointers.
8282 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8283                                                 Expr *LHSExpr, Expr *RHSExpr) {
8284   S.Diag(Loc, S.getLangOpts().CPlusPlus
8285                 ? diag::err_typecheck_pointer_arith_void_type
8286                 : diag::ext_gnu_void_ptr)
8287     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8288                             << RHSExpr->getSourceRange();
8289 }
8290 
8291 /// \brief Diagnose invalid arithmetic on a void pointer.
8292 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8293                                             Expr *Pointer) {
8294   S.Diag(Loc, S.getLangOpts().CPlusPlus
8295                 ? diag::err_typecheck_pointer_arith_void_type
8296                 : diag::ext_gnu_void_ptr)
8297     << 0 /* one pointer */ << Pointer->getSourceRange();
8298 }
8299 
8300 /// \brief Diagnose invalid arithmetic on two function pointers.
8301 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8302                                                     Expr *LHS, Expr *RHS) {
8303   assert(LHS->getType()->isAnyPointerType());
8304   assert(RHS->getType()->isAnyPointerType());
8305   S.Diag(Loc, S.getLangOpts().CPlusPlus
8306                 ? diag::err_typecheck_pointer_arith_function_type
8307                 : diag::ext_gnu_ptr_func_arith)
8308     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8309     // We only show the second type if it differs from the first.
8310     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8311                                                    RHS->getType())
8312     << RHS->getType()->getPointeeType()
8313     << LHS->getSourceRange() << RHS->getSourceRange();
8314 }
8315 
8316 /// \brief Diagnose invalid arithmetic on a function pointer.
8317 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8318                                                 Expr *Pointer) {
8319   assert(Pointer->getType()->isAnyPointerType());
8320   S.Diag(Loc, S.getLangOpts().CPlusPlus
8321                 ? diag::err_typecheck_pointer_arith_function_type
8322                 : diag::ext_gnu_ptr_func_arith)
8323     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8324     << 0 /* one pointer, so only one type */
8325     << Pointer->getSourceRange();
8326 }
8327 
8328 /// \brief Emit error if Operand is incomplete pointer type
8329 ///
8330 /// \returns True if pointer has incomplete type
8331 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8332                                                  Expr *Operand) {
8333   QualType ResType = Operand->getType();
8334   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8335     ResType = ResAtomicType->getValueType();
8336 
8337   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8338   QualType PointeeTy = ResType->getPointeeType();
8339   return S.RequireCompleteType(Loc, PointeeTy,
8340                                diag::err_typecheck_arithmetic_incomplete_type,
8341                                PointeeTy, Operand->getSourceRange());
8342 }
8343 
8344 /// \brief Check the validity of an arithmetic pointer operand.
8345 ///
8346 /// If the operand has pointer type, this code will check for pointer types
8347 /// which are invalid in arithmetic operations. These will be diagnosed
8348 /// appropriately, including whether or not the use is supported as an
8349 /// extension.
8350 ///
8351 /// \returns True when the operand is valid to use (even if as an extension).
8352 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8353                                             Expr *Operand) {
8354   QualType ResType = Operand->getType();
8355   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8356     ResType = ResAtomicType->getValueType();
8357 
8358   if (!ResType->isAnyPointerType()) return true;
8359 
8360   QualType PointeeTy = ResType->getPointeeType();
8361   if (PointeeTy->isVoidType()) {
8362     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8363     return !S.getLangOpts().CPlusPlus;
8364   }
8365   if (PointeeTy->isFunctionType()) {
8366     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8367     return !S.getLangOpts().CPlusPlus;
8368   }
8369 
8370   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8371 
8372   return true;
8373 }
8374 
8375 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8376 /// operands.
8377 ///
8378 /// This routine will diagnose any invalid arithmetic on pointer operands much
8379 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8380 /// for emitting a single diagnostic even for operations where both LHS and RHS
8381 /// are (potentially problematic) pointers.
8382 ///
8383 /// \returns True when the operand is valid to use (even if as an extension).
8384 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8385                                                 Expr *LHSExpr, Expr *RHSExpr) {
8386   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8387   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8388   if (!isLHSPointer && !isRHSPointer) return true;
8389 
8390   QualType LHSPointeeTy, RHSPointeeTy;
8391   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8392   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8393 
8394   // if both are pointers check if operation is valid wrt address spaces
8395   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8396     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8397     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8398     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8399       S.Diag(Loc,
8400              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8401           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8402           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8403       return false;
8404     }
8405   }
8406 
8407   // Check for arithmetic on pointers to incomplete types.
8408   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8409   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8410   if (isLHSVoidPtr || isRHSVoidPtr) {
8411     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8412     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8413     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8414 
8415     return !S.getLangOpts().CPlusPlus;
8416   }
8417 
8418   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8419   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8420   if (isLHSFuncPtr || isRHSFuncPtr) {
8421     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8422     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8423                                                                 RHSExpr);
8424     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8425 
8426     return !S.getLangOpts().CPlusPlus;
8427   }
8428 
8429   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8430     return false;
8431   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8432     return false;
8433 
8434   return true;
8435 }
8436 
8437 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8438 /// literal.
8439 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8440                                   Expr *LHSExpr, Expr *RHSExpr) {
8441   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8442   Expr* IndexExpr = RHSExpr;
8443   if (!StrExpr) {
8444     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8445     IndexExpr = LHSExpr;
8446   }
8447 
8448   bool IsStringPlusInt = StrExpr &&
8449       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8450   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8451     return;
8452 
8453   llvm::APSInt index;
8454   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8455     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8456     if (index.isNonNegative() &&
8457         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8458                               index.isUnsigned()))
8459       return;
8460   }
8461 
8462   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8463   Self.Diag(OpLoc, diag::warn_string_plus_int)
8464       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8465 
8466   // Only print a fixit for "str" + int, not for int + "str".
8467   if (IndexExpr == RHSExpr) {
8468     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8469     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8470         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8471         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8472         << FixItHint::CreateInsertion(EndLoc, "]");
8473   } else
8474     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8475 }
8476 
8477 /// \brief Emit a warning when adding a char literal to a string.
8478 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8479                                    Expr *LHSExpr, Expr *RHSExpr) {
8480   const Expr *StringRefExpr = LHSExpr;
8481   const CharacterLiteral *CharExpr =
8482       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8483 
8484   if (!CharExpr) {
8485     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8486     StringRefExpr = RHSExpr;
8487   }
8488 
8489   if (!CharExpr || !StringRefExpr)
8490     return;
8491 
8492   const QualType StringType = StringRefExpr->getType();
8493 
8494   // Return if not a PointerType.
8495   if (!StringType->isAnyPointerType())
8496     return;
8497 
8498   // Return if not a CharacterType.
8499   if (!StringType->getPointeeType()->isAnyCharacterType())
8500     return;
8501 
8502   ASTContext &Ctx = Self.getASTContext();
8503   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8504 
8505   const QualType CharType = CharExpr->getType();
8506   if (!CharType->isAnyCharacterType() &&
8507       CharType->isIntegerType() &&
8508       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8509     Self.Diag(OpLoc, diag::warn_string_plus_char)
8510         << DiagRange << Ctx.CharTy;
8511   } else {
8512     Self.Diag(OpLoc, diag::warn_string_plus_char)
8513         << DiagRange << CharExpr->getType();
8514   }
8515 
8516   // Only print a fixit for str + char, not for char + str.
8517   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8518     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8519     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8520         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8521         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8522         << FixItHint::CreateInsertion(EndLoc, "]");
8523   } else {
8524     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8525   }
8526 }
8527 
8528 /// \brief Emit error when two pointers are incompatible.
8529 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8530                                            Expr *LHSExpr, Expr *RHSExpr) {
8531   assert(LHSExpr->getType()->isAnyPointerType());
8532   assert(RHSExpr->getType()->isAnyPointerType());
8533   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8534     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8535     << RHSExpr->getSourceRange();
8536 }
8537 
8538 // C99 6.5.6
8539 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8540                                      SourceLocation Loc, BinaryOperatorKind Opc,
8541                                      QualType* CompLHSTy) {
8542   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8543 
8544   if (LHS.get()->getType()->isVectorType() ||
8545       RHS.get()->getType()->isVectorType()) {
8546     QualType compType = CheckVectorOperands(
8547         LHS, RHS, Loc, CompLHSTy,
8548         /*AllowBothBool*/getLangOpts().AltiVec,
8549         /*AllowBoolConversions*/getLangOpts().ZVector);
8550     if (CompLHSTy) *CompLHSTy = compType;
8551     return compType;
8552   }
8553 
8554   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8555   if (LHS.isInvalid() || RHS.isInvalid())
8556     return QualType();
8557 
8558   // Diagnose "string literal" '+' int and string '+' "char literal".
8559   if (Opc == BO_Add) {
8560     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8561     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8562   }
8563 
8564   // handle the common case first (both operands are arithmetic).
8565   if (!compType.isNull() && compType->isArithmeticType()) {
8566     if (CompLHSTy) *CompLHSTy = compType;
8567     return compType;
8568   }
8569 
8570   // Type-checking.  Ultimately the pointer's going to be in PExp;
8571   // note that we bias towards the LHS being the pointer.
8572   Expr *PExp = LHS.get(), *IExp = RHS.get();
8573 
8574   bool isObjCPointer;
8575   if (PExp->getType()->isPointerType()) {
8576     isObjCPointer = false;
8577   } else if (PExp->getType()->isObjCObjectPointerType()) {
8578     isObjCPointer = true;
8579   } else {
8580     std::swap(PExp, IExp);
8581     if (PExp->getType()->isPointerType()) {
8582       isObjCPointer = false;
8583     } else if (PExp->getType()->isObjCObjectPointerType()) {
8584       isObjCPointer = true;
8585     } else {
8586       return InvalidOperands(Loc, LHS, RHS);
8587     }
8588   }
8589   assert(PExp->getType()->isAnyPointerType());
8590 
8591   if (!IExp->getType()->isIntegerType())
8592     return InvalidOperands(Loc, LHS, RHS);
8593 
8594   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8595     return QualType();
8596 
8597   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8598     return QualType();
8599 
8600   // Check array bounds for pointer arithemtic
8601   CheckArrayAccess(PExp, IExp);
8602 
8603   if (CompLHSTy) {
8604     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8605     if (LHSTy.isNull()) {
8606       LHSTy = LHS.get()->getType();
8607       if (LHSTy->isPromotableIntegerType())
8608         LHSTy = Context.getPromotedIntegerType(LHSTy);
8609     }
8610     *CompLHSTy = LHSTy;
8611   }
8612 
8613   return PExp->getType();
8614 }
8615 
8616 // C99 6.5.6
8617 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8618                                         SourceLocation Loc,
8619                                         QualType* CompLHSTy) {
8620   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8621 
8622   if (LHS.get()->getType()->isVectorType() ||
8623       RHS.get()->getType()->isVectorType()) {
8624     QualType compType = CheckVectorOperands(
8625         LHS, RHS, Loc, CompLHSTy,
8626         /*AllowBothBool*/getLangOpts().AltiVec,
8627         /*AllowBoolConversions*/getLangOpts().ZVector);
8628     if (CompLHSTy) *CompLHSTy = compType;
8629     return compType;
8630   }
8631 
8632   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8633   if (LHS.isInvalid() || RHS.isInvalid())
8634     return QualType();
8635 
8636   // Enforce type constraints: C99 6.5.6p3.
8637 
8638   // Handle the common case first (both operands are arithmetic).
8639   if (!compType.isNull() && compType->isArithmeticType()) {
8640     if (CompLHSTy) *CompLHSTy = compType;
8641     return compType;
8642   }
8643 
8644   // Either ptr - int   or   ptr - ptr.
8645   if (LHS.get()->getType()->isAnyPointerType()) {
8646     QualType lpointee = LHS.get()->getType()->getPointeeType();
8647 
8648     // Diagnose bad cases where we step over interface counts.
8649     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8650         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8651       return QualType();
8652 
8653     // The result type of a pointer-int computation is the pointer type.
8654     if (RHS.get()->getType()->isIntegerType()) {
8655       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8656         return QualType();
8657 
8658       // Check array bounds for pointer arithemtic
8659       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8660                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8661 
8662       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8663       return LHS.get()->getType();
8664     }
8665 
8666     // Handle pointer-pointer subtractions.
8667     if (const PointerType *RHSPTy
8668           = RHS.get()->getType()->getAs<PointerType>()) {
8669       QualType rpointee = RHSPTy->getPointeeType();
8670 
8671       if (getLangOpts().CPlusPlus) {
8672         // Pointee types must be the same: C++ [expr.add]
8673         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8674           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8675         }
8676       } else {
8677         // Pointee types must be compatible C99 6.5.6p3
8678         if (!Context.typesAreCompatible(
8679                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8680                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8681           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8682           return QualType();
8683         }
8684       }
8685 
8686       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8687                                                LHS.get(), RHS.get()))
8688         return QualType();
8689 
8690       // The pointee type may have zero size.  As an extension, a structure or
8691       // union may have zero size or an array may have zero length.  In this
8692       // case subtraction does not make sense.
8693       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8694         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8695         if (ElementSize.isZero()) {
8696           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8697             << rpointee.getUnqualifiedType()
8698             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8699         }
8700       }
8701 
8702       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8703       return Context.getPointerDiffType();
8704     }
8705   }
8706 
8707   return InvalidOperands(Loc, LHS, RHS);
8708 }
8709 
8710 static bool isScopedEnumerationType(QualType T) {
8711   if (const EnumType *ET = T->getAs<EnumType>())
8712     return ET->getDecl()->isScoped();
8713   return false;
8714 }
8715 
8716 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8717                                    SourceLocation Loc, BinaryOperatorKind Opc,
8718                                    QualType LHSType) {
8719   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8720   // so skip remaining warnings as we don't want to modify values within Sema.
8721   if (S.getLangOpts().OpenCL)
8722     return;
8723 
8724   llvm::APSInt Right;
8725   // Check right/shifter operand
8726   if (RHS.get()->isValueDependent() ||
8727       !RHS.get()->EvaluateAsInt(Right, S.Context))
8728     return;
8729 
8730   if (Right.isNegative()) {
8731     S.DiagRuntimeBehavior(Loc, RHS.get(),
8732                           S.PDiag(diag::warn_shift_negative)
8733                             << RHS.get()->getSourceRange());
8734     return;
8735   }
8736   llvm::APInt LeftBits(Right.getBitWidth(),
8737                        S.Context.getTypeSize(LHS.get()->getType()));
8738   if (Right.uge(LeftBits)) {
8739     S.DiagRuntimeBehavior(Loc, RHS.get(),
8740                           S.PDiag(diag::warn_shift_gt_typewidth)
8741                             << RHS.get()->getSourceRange());
8742     return;
8743   }
8744   if (Opc != BO_Shl)
8745     return;
8746 
8747   // When left shifting an ICE which is signed, we can check for overflow which
8748   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8749   // integers have defined behavior modulo one more than the maximum value
8750   // representable in the result type, so never warn for those.
8751   llvm::APSInt Left;
8752   if (LHS.get()->isValueDependent() ||
8753       LHSType->hasUnsignedIntegerRepresentation() ||
8754       !LHS.get()->EvaluateAsInt(Left, S.Context))
8755     return;
8756 
8757   // If LHS does not have a signed type and non-negative value
8758   // then, the behavior is undefined. Warn about it.
8759   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8760     S.DiagRuntimeBehavior(Loc, LHS.get(),
8761                           S.PDiag(diag::warn_shift_lhs_negative)
8762                             << LHS.get()->getSourceRange());
8763     return;
8764   }
8765 
8766   llvm::APInt ResultBits =
8767       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8768   if (LeftBits.uge(ResultBits))
8769     return;
8770   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8771   Result = Result.shl(Right);
8772 
8773   // Print the bit representation of the signed integer as an unsigned
8774   // hexadecimal number.
8775   SmallString<40> HexResult;
8776   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8777 
8778   // If we are only missing a sign bit, this is less likely to result in actual
8779   // bugs -- if the result is cast back to an unsigned type, it will have the
8780   // expected value. Thus we place this behind a different warning that can be
8781   // turned off separately if needed.
8782   if (LeftBits == ResultBits - 1) {
8783     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8784         << HexResult << LHSType
8785         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8786     return;
8787   }
8788 
8789   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8790     << HexResult.str() << Result.getMinSignedBits() << LHSType
8791     << Left.getBitWidth() << LHS.get()->getSourceRange()
8792     << RHS.get()->getSourceRange();
8793 }
8794 
8795 /// \brief Return the resulting type when a vector is shifted
8796 ///        by a scalar or vector shift amount.
8797 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8798                                  SourceLocation Loc, bool IsCompAssign) {
8799   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8800   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8801       !LHS.get()->getType()->isVectorType()) {
8802     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8803       << RHS.get()->getType() << LHS.get()->getType()
8804       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8805     return QualType();
8806   }
8807 
8808   if (!IsCompAssign) {
8809     LHS = S.UsualUnaryConversions(LHS.get());
8810     if (LHS.isInvalid()) return QualType();
8811   }
8812 
8813   RHS = S.UsualUnaryConversions(RHS.get());
8814   if (RHS.isInvalid()) return QualType();
8815 
8816   QualType LHSType = LHS.get()->getType();
8817   // Note that LHS might be a scalar because the routine calls not only in
8818   // OpenCL case.
8819   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8820   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8821 
8822   // Note that RHS might not be a vector.
8823   QualType RHSType = RHS.get()->getType();
8824   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8825   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8826 
8827   // The operands need to be integers.
8828   if (!LHSEleType->isIntegerType()) {
8829     S.Diag(Loc, diag::err_typecheck_expect_int)
8830       << LHS.get()->getType() << LHS.get()->getSourceRange();
8831     return QualType();
8832   }
8833 
8834   if (!RHSEleType->isIntegerType()) {
8835     S.Diag(Loc, diag::err_typecheck_expect_int)
8836       << RHS.get()->getType() << RHS.get()->getSourceRange();
8837     return QualType();
8838   }
8839 
8840   if (!LHSVecTy) {
8841     assert(RHSVecTy);
8842     if (IsCompAssign)
8843       return RHSType;
8844     if (LHSEleType != RHSEleType) {
8845       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8846       LHSEleType = RHSEleType;
8847     }
8848     QualType VecTy =
8849         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8850     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8851     LHSType = VecTy;
8852   } else if (RHSVecTy) {
8853     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8854     // are applied component-wise. So if RHS is a vector, then ensure
8855     // that the number of elements is the same as LHS...
8856     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8857       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8858         << LHS.get()->getType() << RHS.get()->getType()
8859         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8860       return QualType();
8861     }
8862     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8863       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8864       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8865       if (LHSBT != RHSBT &&
8866           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8867         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8868             << LHS.get()->getType() << RHS.get()->getType()
8869             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8870       }
8871     }
8872   } else {
8873     // ...else expand RHS to match the number of elements in LHS.
8874     QualType VecTy =
8875       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8876     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8877   }
8878 
8879   return LHSType;
8880 }
8881 
8882 // C99 6.5.7
8883 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8884                                   SourceLocation Loc, BinaryOperatorKind Opc,
8885                                   bool IsCompAssign) {
8886   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8887 
8888   // Vector shifts promote their scalar inputs to vector type.
8889   if (LHS.get()->getType()->isVectorType() ||
8890       RHS.get()->getType()->isVectorType()) {
8891     if (LangOpts.ZVector) {
8892       // The shift operators for the z vector extensions work basically
8893       // like general shifts, except that neither the LHS nor the RHS is
8894       // allowed to be a "vector bool".
8895       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8896         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8897           return InvalidOperands(Loc, LHS, RHS);
8898       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8899         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8900           return InvalidOperands(Loc, LHS, RHS);
8901     }
8902     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8903   }
8904 
8905   // Shifts don't perform usual arithmetic conversions, they just do integer
8906   // promotions on each operand. C99 6.5.7p3
8907 
8908   // For the LHS, do usual unary conversions, but then reset them away
8909   // if this is a compound assignment.
8910   ExprResult OldLHS = LHS;
8911   LHS = UsualUnaryConversions(LHS.get());
8912   if (LHS.isInvalid())
8913     return QualType();
8914   QualType LHSType = LHS.get()->getType();
8915   if (IsCompAssign) LHS = OldLHS;
8916 
8917   // The RHS is simpler.
8918   RHS = UsualUnaryConversions(RHS.get());
8919   if (RHS.isInvalid())
8920     return QualType();
8921   QualType RHSType = RHS.get()->getType();
8922 
8923   // C99 6.5.7p2: Each of the operands shall have integer type.
8924   if (!LHSType->hasIntegerRepresentation() ||
8925       !RHSType->hasIntegerRepresentation())
8926     return InvalidOperands(Loc, LHS, RHS);
8927 
8928   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8929   // hasIntegerRepresentation() above instead of this.
8930   if (isScopedEnumerationType(LHSType) ||
8931       isScopedEnumerationType(RHSType)) {
8932     return InvalidOperands(Loc, LHS, RHS);
8933   }
8934   // Sanity-check shift operands
8935   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8936 
8937   // "The type of the result is that of the promoted left operand."
8938   return LHSType;
8939 }
8940 
8941 static bool IsWithinTemplateSpecialization(Decl *D) {
8942   if (DeclContext *DC = D->getDeclContext()) {
8943     if (isa<ClassTemplateSpecializationDecl>(DC))
8944       return true;
8945     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8946       return FD->isFunctionTemplateSpecialization();
8947   }
8948   return false;
8949 }
8950 
8951 /// If two different enums are compared, raise a warning.
8952 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8953                                 Expr *RHS) {
8954   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8955   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8956 
8957   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8958   if (!LHSEnumType)
8959     return;
8960   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8961   if (!RHSEnumType)
8962     return;
8963 
8964   // Ignore anonymous enums.
8965   if (!LHSEnumType->getDecl()->getIdentifier())
8966     return;
8967   if (!RHSEnumType->getDecl()->getIdentifier())
8968     return;
8969 
8970   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8971     return;
8972 
8973   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8974       << LHSStrippedType << RHSStrippedType
8975       << LHS->getSourceRange() << RHS->getSourceRange();
8976 }
8977 
8978 /// \brief Diagnose bad pointer comparisons.
8979 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8980                                               ExprResult &LHS, ExprResult &RHS,
8981                                               bool IsError) {
8982   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8983                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8984     << LHS.get()->getType() << RHS.get()->getType()
8985     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8986 }
8987 
8988 /// \brief Returns false if the pointers are converted to a composite type,
8989 /// true otherwise.
8990 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8991                                            ExprResult &LHS, ExprResult &RHS) {
8992   // C++ [expr.rel]p2:
8993   //   [...] Pointer conversions (4.10) and qualification
8994   //   conversions (4.4) are performed on pointer operands (or on
8995   //   a pointer operand and a null pointer constant) to bring
8996   //   them to their composite pointer type. [...]
8997   //
8998   // C++ [expr.eq]p1 uses the same notion for (in)equality
8999   // comparisons of pointers.
9000 
9001   QualType LHSType = LHS.get()->getType();
9002   QualType RHSType = RHS.get()->getType();
9003   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9004          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9005 
9006   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9007   if (T.isNull()) {
9008     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9009         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9010       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9011     else
9012       S.InvalidOperands(Loc, LHS, RHS);
9013     return true;
9014   }
9015 
9016   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9017   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9018   return false;
9019 }
9020 
9021 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9022                                                     ExprResult &LHS,
9023                                                     ExprResult &RHS,
9024                                                     bool IsError) {
9025   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9026                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9027     << LHS.get()->getType() << RHS.get()->getType()
9028     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9029 }
9030 
9031 static bool isObjCObjectLiteral(ExprResult &E) {
9032   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9033   case Stmt::ObjCArrayLiteralClass:
9034   case Stmt::ObjCDictionaryLiteralClass:
9035   case Stmt::ObjCStringLiteralClass:
9036   case Stmt::ObjCBoxedExprClass:
9037     return true;
9038   default:
9039     // Note that ObjCBoolLiteral is NOT an object literal!
9040     return false;
9041   }
9042 }
9043 
9044 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9045   const ObjCObjectPointerType *Type =
9046     LHS->getType()->getAs<ObjCObjectPointerType>();
9047 
9048   // If this is not actually an Objective-C object, bail out.
9049   if (!Type)
9050     return false;
9051 
9052   // Get the LHS object's interface type.
9053   QualType InterfaceType = Type->getPointeeType();
9054 
9055   // If the RHS isn't an Objective-C object, bail out.
9056   if (!RHS->getType()->isObjCObjectPointerType())
9057     return false;
9058 
9059   // Try to find the -isEqual: method.
9060   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9061   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9062                                                       InterfaceType,
9063                                                       /*instance=*/true);
9064   if (!Method) {
9065     if (Type->isObjCIdType()) {
9066       // For 'id', just check the global pool.
9067       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9068                                                   /*receiverId=*/true);
9069     } else {
9070       // Check protocols.
9071       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9072                                              /*instance=*/true);
9073     }
9074   }
9075 
9076   if (!Method)
9077     return false;
9078 
9079   QualType T = Method->parameters()[0]->getType();
9080   if (!T->isObjCObjectPointerType())
9081     return false;
9082 
9083   QualType R = Method->getReturnType();
9084   if (!R->isScalarType())
9085     return false;
9086 
9087   return true;
9088 }
9089 
9090 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9091   FromE = FromE->IgnoreParenImpCasts();
9092   switch (FromE->getStmtClass()) {
9093     default:
9094       break;
9095     case Stmt::ObjCStringLiteralClass:
9096       // "string literal"
9097       return LK_String;
9098     case Stmt::ObjCArrayLiteralClass:
9099       // "array literal"
9100       return LK_Array;
9101     case Stmt::ObjCDictionaryLiteralClass:
9102       // "dictionary literal"
9103       return LK_Dictionary;
9104     case Stmt::BlockExprClass:
9105       return LK_Block;
9106     case Stmt::ObjCBoxedExprClass: {
9107       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9108       switch (Inner->getStmtClass()) {
9109         case Stmt::IntegerLiteralClass:
9110         case Stmt::FloatingLiteralClass:
9111         case Stmt::CharacterLiteralClass:
9112         case Stmt::ObjCBoolLiteralExprClass:
9113         case Stmt::CXXBoolLiteralExprClass:
9114           // "numeric literal"
9115           return LK_Numeric;
9116         case Stmt::ImplicitCastExprClass: {
9117           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9118           // Boolean literals can be represented by implicit casts.
9119           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9120             return LK_Numeric;
9121           break;
9122         }
9123         default:
9124           break;
9125       }
9126       return LK_Boxed;
9127     }
9128   }
9129   return LK_None;
9130 }
9131 
9132 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9133                                           ExprResult &LHS, ExprResult &RHS,
9134                                           BinaryOperator::Opcode Opc){
9135   Expr *Literal;
9136   Expr *Other;
9137   if (isObjCObjectLiteral(LHS)) {
9138     Literal = LHS.get();
9139     Other = RHS.get();
9140   } else {
9141     Literal = RHS.get();
9142     Other = LHS.get();
9143   }
9144 
9145   // Don't warn on comparisons against nil.
9146   Other = Other->IgnoreParenCasts();
9147   if (Other->isNullPointerConstant(S.getASTContext(),
9148                                    Expr::NPC_ValueDependentIsNotNull))
9149     return;
9150 
9151   // This should be kept in sync with warn_objc_literal_comparison.
9152   // LK_String should always be after the other literals, since it has its own
9153   // warning flag.
9154   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9155   assert(LiteralKind != Sema::LK_Block);
9156   if (LiteralKind == Sema::LK_None) {
9157     llvm_unreachable("Unknown Objective-C object literal kind");
9158   }
9159 
9160   if (LiteralKind == Sema::LK_String)
9161     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9162       << Literal->getSourceRange();
9163   else
9164     S.Diag(Loc, diag::warn_objc_literal_comparison)
9165       << LiteralKind << Literal->getSourceRange();
9166 
9167   if (BinaryOperator::isEqualityOp(Opc) &&
9168       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9169     SourceLocation Start = LHS.get()->getLocStart();
9170     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9171     CharSourceRange OpRange =
9172       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9173 
9174     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9175       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9176       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9177       << FixItHint::CreateInsertion(End, "]");
9178   }
9179 }
9180 
9181 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9182 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9183                                            ExprResult &RHS, SourceLocation Loc,
9184                                            BinaryOperatorKind Opc) {
9185   // Check that left hand side is !something.
9186   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9187   if (!UO || UO->getOpcode() != UO_LNot) return;
9188 
9189   // Only check if the right hand side is non-bool arithmetic type.
9190   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9191 
9192   // Make sure that the something in !something is not bool.
9193   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9194   if (SubExpr->isKnownToHaveBooleanValue()) return;
9195 
9196   // Emit warning.
9197   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9198   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9199       << Loc << IsBitwiseOp;
9200 
9201   // First note suggest !(x < y)
9202   SourceLocation FirstOpen = SubExpr->getLocStart();
9203   SourceLocation FirstClose = RHS.get()->getLocEnd();
9204   FirstClose = S.getLocForEndOfToken(FirstClose);
9205   if (FirstClose.isInvalid())
9206     FirstOpen = SourceLocation();
9207   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9208       << IsBitwiseOp
9209       << FixItHint::CreateInsertion(FirstOpen, "(")
9210       << FixItHint::CreateInsertion(FirstClose, ")");
9211 
9212   // Second note suggests (!x) < y
9213   SourceLocation SecondOpen = LHS.get()->getLocStart();
9214   SourceLocation SecondClose = LHS.get()->getLocEnd();
9215   SecondClose = S.getLocForEndOfToken(SecondClose);
9216   if (SecondClose.isInvalid())
9217     SecondOpen = SourceLocation();
9218   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9219       << FixItHint::CreateInsertion(SecondOpen, "(")
9220       << FixItHint::CreateInsertion(SecondClose, ")");
9221 }
9222 
9223 // Get the decl for a simple expression: a reference to a variable,
9224 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9225 static ValueDecl *getCompareDecl(Expr *E) {
9226   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9227     return DR->getDecl();
9228   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9229     if (Ivar->isFreeIvar())
9230       return Ivar->getDecl();
9231   }
9232   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9233     if (Mem->isImplicitAccess())
9234       return Mem->getMemberDecl();
9235   }
9236   return nullptr;
9237 }
9238 
9239 // C99 6.5.8, C++ [expr.rel]
9240 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9241                                     SourceLocation Loc, BinaryOperatorKind Opc,
9242                                     bool IsRelational) {
9243   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9244 
9245   // Handle vector comparisons separately.
9246   if (LHS.get()->getType()->isVectorType() ||
9247       RHS.get()->getType()->isVectorType())
9248     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9249 
9250   QualType LHSType = LHS.get()->getType();
9251   QualType RHSType = RHS.get()->getType();
9252 
9253   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9254   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9255 
9256   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9257   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9258 
9259   if (!LHSType->hasFloatingRepresentation() &&
9260       !(LHSType->isBlockPointerType() && IsRelational) &&
9261       !LHS.get()->getLocStart().isMacroID() &&
9262       !RHS.get()->getLocStart().isMacroID() &&
9263       !inTemplateInstantiation()) {
9264     // For non-floating point types, check for self-comparisons of the form
9265     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9266     // often indicate logic errors in the program.
9267     //
9268     // NOTE: Don't warn about comparison expressions resulting from macro
9269     // expansion. Also don't warn about comparisons which are only self
9270     // comparisons within a template specialization. The warnings should catch
9271     // obvious cases in the definition of the template anyways. The idea is to
9272     // warn when the typed comparison operator will always evaluate to the same
9273     // result.
9274     ValueDecl *DL = getCompareDecl(LHSStripped);
9275     ValueDecl *DR = getCompareDecl(RHSStripped);
9276     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9277       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9278                           << 0 // self-
9279                           << (Opc == BO_EQ
9280                               || Opc == BO_LE
9281                               || Opc == BO_GE));
9282     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9283                !DL->getType()->isReferenceType() &&
9284                !DR->getType()->isReferenceType()) {
9285         // what is it always going to eval to?
9286         char always_evals_to;
9287         switch(Opc) {
9288         case BO_EQ: // e.g. array1 == array2
9289           always_evals_to = 0; // false
9290           break;
9291         case BO_NE: // e.g. array1 != array2
9292           always_evals_to = 1; // true
9293           break;
9294         default:
9295           // best we can say is 'a constant'
9296           always_evals_to = 2; // e.g. array1 <= array2
9297           break;
9298         }
9299         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9300                             << 1 // array
9301                             << always_evals_to);
9302     }
9303 
9304     if (isa<CastExpr>(LHSStripped))
9305       LHSStripped = LHSStripped->IgnoreParenCasts();
9306     if (isa<CastExpr>(RHSStripped))
9307       RHSStripped = RHSStripped->IgnoreParenCasts();
9308 
9309     // Warn about comparisons against a string constant (unless the other
9310     // operand is null), the user probably wants strcmp.
9311     Expr *literalString = nullptr;
9312     Expr *literalStringStripped = nullptr;
9313     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9314         !RHSStripped->isNullPointerConstant(Context,
9315                                             Expr::NPC_ValueDependentIsNull)) {
9316       literalString = LHS.get();
9317       literalStringStripped = LHSStripped;
9318     } else if ((isa<StringLiteral>(RHSStripped) ||
9319                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9320                !LHSStripped->isNullPointerConstant(Context,
9321                                             Expr::NPC_ValueDependentIsNull)) {
9322       literalString = RHS.get();
9323       literalStringStripped = RHSStripped;
9324     }
9325 
9326     if (literalString) {
9327       DiagRuntimeBehavior(Loc, nullptr,
9328         PDiag(diag::warn_stringcompare)
9329           << isa<ObjCEncodeExpr>(literalStringStripped)
9330           << literalString->getSourceRange());
9331     }
9332   }
9333 
9334   // C99 6.5.8p3 / C99 6.5.9p4
9335   UsualArithmeticConversions(LHS, RHS);
9336   if (LHS.isInvalid() || RHS.isInvalid())
9337     return QualType();
9338 
9339   LHSType = LHS.get()->getType();
9340   RHSType = RHS.get()->getType();
9341 
9342   // The result of comparisons is 'bool' in C++, 'int' in C.
9343   QualType ResultTy = Context.getLogicalOperationType();
9344 
9345   if (IsRelational) {
9346     if (LHSType->isRealType() && RHSType->isRealType())
9347       return ResultTy;
9348   } else {
9349     // Check for comparisons of floating point operands using != and ==.
9350     if (LHSType->hasFloatingRepresentation())
9351       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9352 
9353     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9354       return ResultTy;
9355   }
9356 
9357   const Expr::NullPointerConstantKind LHSNullKind =
9358       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9359   const Expr::NullPointerConstantKind RHSNullKind =
9360       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9361   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9362   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9363 
9364   if (!IsRelational && LHSIsNull != RHSIsNull) {
9365     bool IsEquality = Opc == BO_EQ;
9366     if (RHSIsNull)
9367       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9368                                    RHS.get()->getSourceRange());
9369     else
9370       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9371                                    LHS.get()->getSourceRange());
9372   }
9373 
9374   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9375       (RHSType->isIntegerType() && !RHSIsNull)) {
9376     // Skip normal pointer conversion checks in this case; we have better
9377     // diagnostics for this below.
9378   } else if (getLangOpts().CPlusPlus) {
9379     // Equality comparison of a function pointer to a void pointer is invalid,
9380     // but we allow it as an extension.
9381     // FIXME: If we really want to allow this, should it be part of composite
9382     // pointer type computation so it works in conditionals too?
9383     if (!IsRelational &&
9384         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9385          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9386       // This is a gcc extension compatibility comparison.
9387       // In a SFINAE context, we treat this as a hard error to maintain
9388       // conformance with the C++ standard.
9389       diagnoseFunctionPointerToVoidComparison(
9390           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9391 
9392       if (isSFINAEContext())
9393         return QualType();
9394 
9395       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9396       return ResultTy;
9397     }
9398 
9399     // C++ [expr.eq]p2:
9400     //   If at least one operand is a pointer [...] bring them to their
9401     //   composite pointer type.
9402     // C++ [expr.rel]p2:
9403     //   If both operands are pointers, [...] bring them to their composite
9404     //   pointer type.
9405     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9406         (IsRelational ? 2 : 1)) {
9407       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9408         return QualType();
9409       else
9410         return ResultTy;
9411     }
9412   } else if (LHSType->isPointerType() &&
9413              RHSType->isPointerType()) { // C99 6.5.8p2
9414     // All of the following pointer-related warnings are GCC extensions, except
9415     // when handling null pointer constants.
9416     QualType LCanPointeeTy =
9417       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9418     QualType RCanPointeeTy =
9419       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9420 
9421     // C99 6.5.9p2 and C99 6.5.8p2
9422     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9423                                    RCanPointeeTy.getUnqualifiedType())) {
9424       // Valid unless a relational comparison of function pointers
9425       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9426         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9427           << LHSType << RHSType << LHS.get()->getSourceRange()
9428           << RHS.get()->getSourceRange();
9429       }
9430     } else if (!IsRelational &&
9431                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9432       // Valid unless comparison between non-null pointer and function pointer
9433       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9434           && !LHSIsNull && !RHSIsNull)
9435         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9436                                                 /*isError*/false);
9437     } else {
9438       // Invalid
9439       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9440     }
9441     if (LCanPointeeTy != RCanPointeeTy) {
9442       // Treat NULL constant as a special case in OpenCL.
9443       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9444         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9445         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9446           Diag(Loc,
9447                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9448               << LHSType << RHSType << 0 /* comparison */
9449               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9450         }
9451       }
9452       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9453       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9454       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9455                                                : CK_BitCast;
9456       if (LHSIsNull && !RHSIsNull)
9457         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9458       else
9459         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9460     }
9461     return ResultTy;
9462   }
9463 
9464   if (getLangOpts().CPlusPlus) {
9465     // C++ [expr.eq]p4:
9466     //   Two operands of type std::nullptr_t or one operand of type
9467     //   std::nullptr_t and the other a null pointer constant compare equal.
9468     if (!IsRelational && LHSIsNull && RHSIsNull) {
9469       if (LHSType->isNullPtrType()) {
9470         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9471         return ResultTy;
9472       }
9473       if (RHSType->isNullPtrType()) {
9474         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9475         return ResultTy;
9476       }
9477     }
9478 
9479     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9480     // These aren't covered by the composite pointer type rules.
9481     if (!IsRelational && RHSType->isNullPtrType() &&
9482         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9483       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9484       return ResultTy;
9485     }
9486     if (!IsRelational && LHSType->isNullPtrType() &&
9487         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9488       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9489       return ResultTy;
9490     }
9491 
9492     if (IsRelational &&
9493         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9494          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9495       // HACK: Relational comparison of nullptr_t against a pointer type is
9496       // invalid per DR583, but we allow it within std::less<> and friends,
9497       // since otherwise common uses of it break.
9498       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9499       // friends to have std::nullptr_t overload candidates.
9500       DeclContext *DC = CurContext;
9501       if (isa<FunctionDecl>(DC))
9502         DC = DC->getParent();
9503       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9504         if (CTSD->isInStdNamespace() &&
9505             llvm::StringSwitch<bool>(CTSD->getName())
9506                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9507                 .Default(false)) {
9508           if (RHSType->isNullPtrType())
9509             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9510           else
9511             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9512           return ResultTy;
9513         }
9514       }
9515     }
9516 
9517     // C++ [expr.eq]p2:
9518     //   If at least one operand is a pointer to member, [...] bring them to
9519     //   their composite pointer type.
9520     if (!IsRelational &&
9521         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9522       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9523         return QualType();
9524       else
9525         return ResultTy;
9526     }
9527 
9528     // Handle scoped enumeration types specifically, since they don't promote
9529     // to integers.
9530     if (LHS.get()->getType()->isEnumeralType() &&
9531         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9532                                        RHS.get()->getType()))
9533       return ResultTy;
9534   }
9535 
9536   // Handle block pointer types.
9537   if (!IsRelational && LHSType->isBlockPointerType() &&
9538       RHSType->isBlockPointerType()) {
9539     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9540     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9541 
9542     if (!LHSIsNull && !RHSIsNull &&
9543         !Context.typesAreCompatible(lpointee, rpointee)) {
9544       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9545         << LHSType << RHSType << LHS.get()->getSourceRange()
9546         << RHS.get()->getSourceRange();
9547     }
9548     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9549     return ResultTy;
9550   }
9551 
9552   // Allow block pointers to be compared with null pointer constants.
9553   if (!IsRelational
9554       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9555           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9556     if (!LHSIsNull && !RHSIsNull) {
9557       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9558              ->getPointeeType()->isVoidType())
9559             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9560                 ->getPointeeType()->isVoidType())))
9561         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9562           << LHSType << RHSType << LHS.get()->getSourceRange()
9563           << RHS.get()->getSourceRange();
9564     }
9565     if (LHSIsNull && !RHSIsNull)
9566       LHS = ImpCastExprToType(LHS.get(), RHSType,
9567                               RHSType->isPointerType() ? CK_BitCast
9568                                 : CK_AnyPointerToBlockPointerCast);
9569     else
9570       RHS = ImpCastExprToType(RHS.get(), LHSType,
9571                               LHSType->isPointerType() ? CK_BitCast
9572                                 : CK_AnyPointerToBlockPointerCast);
9573     return ResultTy;
9574   }
9575 
9576   if (LHSType->isObjCObjectPointerType() ||
9577       RHSType->isObjCObjectPointerType()) {
9578     const PointerType *LPT = LHSType->getAs<PointerType>();
9579     const PointerType *RPT = RHSType->getAs<PointerType>();
9580     if (LPT || RPT) {
9581       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9582       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9583 
9584       if (!LPtrToVoid && !RPtrToVoid &&
9585           !Context.typesAreCompatible(LHSType, RHSType)) {
9586         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9587                                           /*isError*/false);
9588       }
9589       if (LHSIsNull && !RHSIsNull) {
9590         Expr *E = LHS.get();
9591         if (getLangOpts().ObjCAutoRefCount)
9592           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9593         LHS = ImpCastExprToType(E, RHSType,
9594                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9595       }
9596       else {
9597         Expr *E = RHS.get();
9598         if (getLangOpts().ObjCAutoRefCount)
9599           CheckObjCARCConversion(SourceRange(), LHSType, E,
9600                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9601                                  /*DiagnoseCFAudited=*/false, Opc);
9602         RHS = ImpCastExprToType(E, LHSType,
9603                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9604       }
9605       return ResultTy;
9606     }
9607     if (LHSType->isObjCObjectPointerType() &&
9608         RHSType->isObjCObjectPointerType()) {
9609       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9610         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9611                                           /*isError*/false);
9612       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9613         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9614 
9615       if (LHSIsNull && !RHSIsNull)
9616         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9617       else
9618         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9619       return ResultTy;
9620     }
9621   }
9622   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9623       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9624     unsigned DiagID = 0;
9625     bool isError = false;
9626     if (LangOpts.DebuggerSupport) {
9627       // Under a debugger, allow the comparison of pointers to integers,
9628       // since users tend to want to compare addresses.
9629     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9630                (RHSIsNull && RHSType->isIntegerType())) {
9631       if (IsRelational) {
9632         isError = getLangOpts().CPlusPlus;
9633         DiagID =
9634           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9635                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9636       }
9637     } else if (getLangOpts().CPlusPlus) {
9638       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9639       isError = true;
9640     } else if (IsRelational)
9641       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9642     else
9643       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9644 
9645     if (DiagID) {
9646       Diag(Loc, DiagID)
9647         << LHSType << RHSType << LHS.get()->getSourceRange()
9648         << RHS.get()->getSourceRange();
9649       if (isError)
9650         return QualType();
9651     }
9652 
9653     if (LHSType->isIntegerType())
9654       LHS = ImpCastExprToType(LHS.get(), RHSType,
9655                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9656     else
9657       RHS = ImpCastExprToType(RHS.get(), LHSType,
9658                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9659     return ResultTy;
9660   }
9661 
9662   // Handle block pointers.
9663   if (!IsRelational && RHSIsNull
9664       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9665     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9666     return ResultTy;
9667   }
9668   if (!IsRelational && LHSIsNull
9669       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9670     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9671     return ResultTy;
9672   }
9673 
9674   if (getLangOpts().OpenCLVersion >= 200) {
9675     if (LHSIsNull && RHSType->isQueueT()) {
9676       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9677       return ResultTy;
9678     }
9679 
9680     if (LHSType->isQueueT() && RHSIsNull) {
9681       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9682       return ResultTy;
9683     }
9684   }
9685 
9686   return InvalidOperands(Loc, LHS, RHS);
9687 }
9688 
9689 
9690 // Return a signed type that is of identical size and number of elements.
9691 // For floating point vectors, return an integer type of identical size
9692 // and number of elements.
9693 QualType Sema::GetSignedVectorType(QualType V) {
9694   const VectorType *VTy = V->getAs<VectorType>();
9695   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9696   if (TypeSize == Context.getTypeSize(Context.CharTy))
9697     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9698   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9699     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9700   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9701     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9702   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9703     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9704   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9705          "Unhandled vector element size in vector compare");
9706   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9707 }
9708 
9709 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9710 /// operates on extended vector types.  Instead of producing an IntTy result,
9711 /// like a scalar comparison, a vector comparison produces a vector of integer
9712 /// types.
9713 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9714                                           SourceLocation Loc,
9715                                           bool IsRelational) {
9716   // Check to make sure we're operating on vectors of the same type and width,
9717   // Allowing one side to be a scalar of element type.
9718   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9719                               /*AllowBothBool*/true,
9720                               /*AllowBoolConversions*/getLangOpts().ZVector);
9721   if (vType.isNull())
9722     return vType;
9723 
9724   QualType LHSType = LHS.get()->getType();
9725 
9726   // If AltiVec, the comparison results in a numeric type, i.e.
9727   // bool for C++, int for C
9728   if (getLangOpts().AltiVec &&
9729       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9730     return Context.getLogicalOperationType();
9731 
9732   // For non-floating point types, check for self-comparisons of the form
9733   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9734   // often indicate logic errors in the program.
9735   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9736     if (DeclRefExpr* DRL
9737           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9738       if (DeclRefExpr* DRR
9739             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9740         if (DRL->getDecl() == DRR->getDecl())
9741           DiagRuntimeBehavior(Loc, nullptr,
9742                               PDiag(diag::warn_comparison_always)
9743                                 << 0 // self-
9744                                 << 2 // "a constant"
9745                               );
9746   }
9747 
9748   // Check for comparisons of floating point operands using != and ==.
9749   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9750     assert (RHS.get()->getType()->hasFloatingRepresentation());
9751     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9752   }
9753 
9754   // Return a signed type for the vector.
9755   return GetSignedVectorType(vType);
9756 }
9757 
9758 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9759                                           SourceLocation Loc) {
9760   // Ensure that either both operands are of the same vector type, or
9761   // one operand is of a vector type and the other is of its element type.
9762   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9763                                        /*AllowBothBool*/true,
9764                                        /*AllowBoolConversions*/false);
9765   if (vType.isNull())
9766     return InvalidOperands(Loc, LHS, RHS);
9767   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9768       vType->hasFloatingRepresentation())
9769     return InvalidOperands(Loc, LHS, RHS);
9770 
9771   return GetSignedVectorType(LHS.get()->getType());
9772 }
9773 
9774 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9775                                            SourceLocation Loc,
9776                                            BinaryOperatorKind Opc) {
9777   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9778 
9779   bool IsCompAssign =
9780       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9781 
9782   if (LHS.get()->getType()->isVectorType() ||
9783       RHS.get()->getType()->isVectorType()) {
9784     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9785         RHS.get()->getType()->hasIntegerRepresentation())
9786       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9787                         /*AllowBothBool*/true,
9788                         /*AllowBoolConversions*/getLangOpts().ZVector);
9789     return InvalidOperands(Loc, LHS, RHS);
9790   }
9791 
9792   if (Opc == BO_And)
9793     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9794 
9795   ExprResult LHSResult = LHS, RHSResult = RHS;
9796   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9797                                                  IsCompAssign);
9798   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9799     return QualType();
9800   LHS = LHSResult.get();
9801   RHS = RHSResult.get();
9802 
9803   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9804     return compType;
9805   return InvalidOperands(Loc, LHS, RHS);
9806 }
9807 
9808 // C99 6.5.[13,14]
9809 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9810                                            SourceLocation Loc,
9811                                            BinaryOperatorKind Opc) {
9812   // Check vector operands differently.
9813   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9814     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9815 
9816   // Diagnose cases where the user write a logical and/or but probably meant a
9817   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9818   // is a constant.
9819   if (LHS.get()->getType()->isIntegerType() &&
9820       !LHS.get()->getType()->isBooleanType() &&
9821       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9822       // Don't warn in macros or template instantiations.
9823       !Loc.isMacroID() && !inTemplateInstantiation()) {
9824     // If the RHS can be constant folded, and if it constant folds to something
9825     // that isn't 0 or 1 (which indicate a potential logical operation that
9826     // happened to fold to true/false) then warn.
9827     // Parens on the RHS are ignored.
9828     llvm::APSInt Result;
9829     if (RHS.get()->EvaluateAsInt(Result, Context))
9830       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9831            !RHS.get()->getExprLoc().isMacroID()) ||
9832           (Result != 0 && Result != 1)) {
9833         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9834           << RHS.get()->getSourceRange()
9835           << (Opc == BO_LAnd ? "&&" : "||");
9836         // Suggest replacing the logical operator with the bitwise version
9837         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9838             << (Opc == BO_LAnd ? "&" : "|")
9839             << FixItHint::CreateReplacement(SourceRange(
9840                                                  Loc, getLocForEndOfToken(Loc)),
9841                                             Opc == BO_LAnd ? "&" : "|");
9842         if (Opc == BO_LAnd)
9843           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9844           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9845               << FixItHint::CreateRemoval(
9846                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9847                               RHS.get()->getLocEnd()));
9848       }
9849   }
9850 
9851   if (!Context.getLangOpts().CPlusPlus) {
9852     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9853     // not operate on the built-in scalar and vector float types.
9854     if (Context.getLangOpts().OpenCL &&
9855         Context.getLangOpts().OpenCLVersion < 120) {
9856       if (LHS.get()->getType()->isFloatingType() ||
9857           RHS.get()->getType()->isFloatingType())
9858         return InvalidOperands(Loc, LHS, RHS);
9859     }
9860 
9861     LHS = UsualUnaryConversions(LHS.get());
9862     if (LHS.isInvalid())
9863       return QualType();
9864 
9865     RHS = UsualUnaryConversions(RHS.get());
9866     if (RHS.isInvalid())
9867       return QualType();
9868 
9869     if (!LHS.get()->getType()->isScalarType() ||
9870         !RHS.get()->getType()->isScalarType())
9871       return InvalidOperands(Loc, LHS, RHS);
9872 
9873     return Context.IntTy;
9874   }
9875 
9876   // The following is safe because we only use this method for
9877   // non-overloadable operands.
9878 
9879   // C++ [expr.log.and]p1
9880   // C++ [expr.log.or]p1
9881   // The operands are both contextually converted to type bool.
9882   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9883   if (LHSRes.isInvalid())
9884     return InvalidOperands(Loc, LHS, RHS);
9885   LHS = LHSRes;
9886 
9887   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9888   if (RHSRes.isInvalid())
9889     return InvalidOperands(Loc, LHS, RHS);
9890   RHS = RHSRes;
9891 
9892   // C++ [expr.log.and]p2
9893   // C++ [expr.log.or]p2
9894   // The result is a bool.
9895   return Context.BoolTy;
9896 }
9897 
9898 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9899   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9900   if (!ME) return false;
9901   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9902   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9903       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9904   if (!Base) return false;
9905   return Base->getMethodDecl() != nullptr;
9906 }
9907 
9908 /// Is the given expression (which must be 'const') a reference to a
9909 /// variable which was originally non-const, but which has become
9910 /// 'const' due to being captured within a block?
9911 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9912 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9913   assert(E->isLValue() && E->getType().isConstQualified());
9914   E = E->IgnoreParens();
9915 
9916   // Must be a reference to a declaration from an enclosing scope.
9917   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9918   if (!DRE) return NCCK_None;
9919   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9920 
9921   // The declaration must be a variable which is not declared 'const'.
9922   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9923   if (!var) return NCCK_None;
9924   if (var->getType().isConstQualified()) return NCCK_None;
9925   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9926 
9927   // Decide whether the first capture was for a block or a lambda.
9928   DeclContext *DC = S.CurContext, *Prev = nullptr;
9929   // Decide whether the first capture was for a block or a lambda.
9930   while (DC) {
9931     // For init-capture, it is possible that the variable belongs to the
9932     // template pattern of the current context.
9933     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9934       if (var->isInitCapture() &&
9935           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9936         break;
9937     if (DC == var->getDeclContext())
9938       break;
9939     Prev = DC;
9940     DC = DC->getParent();
9941   }
9942   // Unless we have an init-capture, we've gone one step too far.
9943   if (!var->isInitCapture())
9944     DC = Prev;
9945   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9946 }
9947 
9948 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9949   Ty = Ty.getNonReferenceType();
9950   if (IsDereference && Ty->isPointerType())
9951     Ty = Ty->getPointeeType();
9952   return !Ty.isConstQualified();
9953 }
9954 
9955 /// Emit the "read-only variable not assignable" error and print notes to give
9956 /// more information about why the variable is not assignable, such as pointing
9957 /// to the declaration of a const variable, showing that a method is const, or
9958 /// that the function is returning a const reference.
9959 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9960                                     SourceLocation Loc) {
9961   // Update err_typecheck_assign_const and note_typecheck_assign_const
9962   // when this enum is changed.
9963   enum {
9964     ConstFunction,
9965     ConstVariable,
9966     ConstMember,
9967     ConstMethod,
9968     ConstUnknown,  // Keep as last element
9969   };
9970 
9971   SourceRange ExprRange = E->getSourceRange();
9972 
9973   // Only emit one error on the first const found.  All other consts will emit
9974   // a note to the error.
9975   bool DiagnosticEmitted = false;
9976 
9977   // Track if the current expression is the result of a dereference, and if the
9978   // next checked expression is the result of a dereference.
9979   bool IsDereference = false;
9980   bool NextIsDereference = false;
9981 
9982   // Loop to process MemberExpr chains.
9983   while (true) {
9984     IsDereference = NextIsDereference;
9985 
9986     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9987     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9988       NextIsDereference = ME->isArrow();
9989       const ValueDecl *VD = ME->getMemberDecl();
9990       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9991         // Mutable fields can be modified even if the class is const.
9992         if (Field->isMutable()) {
9993           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9994           break;
9995         }
9996 
9997         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9998           if (!DiagnosticEmitted) {
9999             S.Diag(Loc, diag::err_typecheck_assign_const)
10000                 << ExprRange << ConstMember << false /*static*/ << Field
10001                 << Field->getType();
10002             DiagnosticEmitted = true;
10003           }
10004           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10005               << ConstMember << false /*static*/ << Field << Field->getType()
10006               << Field->getSourceRange();
10007         }
10008         E = ME->getBase();
10009         continue;
10010       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10011         if (VDecl->getType().isConstQualified()) {
10012           if (!DiagnosticEmitted) {
10013             S.Diag(Loc, diag::err_typecheck_assign_const)
10014                 << ExprRange << ConstMember << true /*static*/ << VDecl
10015                 << VDecl->getType();
10016             DiagnosticEmitted = true;
10017           }
10018           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10019               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10020               << VDecl->getSourceRange();
10021         }
10022         // Static fields do not inherit constness from parents.
10023         break;
10024       }
10025       break;
10026     } // End MemberExpr
10027     break;
10028   }
10029 
10030   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10031     // Function calls
10032     const FunctionDecl *FD = CE->getDirectCallee();
10033     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10034       if (!DiagnosticEmitted) {
10035         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10036                                                       << ConstFunction << FD;
10037         DiagnosticEmitted = true;
10038       }
10039       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10040              diag::note_typecheck_assign_const)
10041           << ConstFunction << FD << FD->getReturnType()
10042           << FD->getReturnTypeSourceRange();
10043     }
10044   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10045     // Point to variable declaration.
10046     if (const ValueDecl *VD = DRE->getDecl()) {
10047       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10048         if (!DiagnosticEmitted) {
10049           S.Diag(Loc, diag::err_typecheck_assign_const)
10050               << ExprRange << ConstVariable << VD << VD->getType();
10051           DiagnosticEmitted = true;
10052         }
10053         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10054             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10055       }
10056     }
10057   } else if (isa<CXXThisExpr>(E)) {
10058     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10059       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10060         if (MD->isConst()) {
10061           if (!DiagnosticEmitted) {
10062             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10063                                                           << ConstMethod << MD;
10064             DiagnosticEmitted = true;
10065           }
10066           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10067               << ConstMethod << MD << MD->getSourceRange();
10068         }
10069       }
10070     }
10071   }
10072 
10073   if (DiagnosticEmitted)
10074     return;
10075 
10076   // Can't determine a more specific message, so display the generic error.
10077   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10078 }
10079 
10080 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10081 /// emit an error and return true.  If so, return false.
10082 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10083   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10084 
10085   S.CheckShadowingDeclModification(E, Loc);
10086 
10087   SourceLocation OrigLoc = Loc;
10088   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10089                                                               &Loc);
10090   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10091     IsLV = Expr::MLV_InvalidMessageExpression;
10092   if (IsLV == Expr::MLV_Valid)
10093     return false;
10094 
10095   unsigned DiagID = 0;
10096   bool NeedType = false;
10097   switch (IsLV) { // C99 6.5.16p2
10098   case Expr::MLV_ConstQualified:
10099     // Use a specialized diagnostic when we're assigning to an object
10100     // from an enclosing function or block.
10101     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10102       if (NCCK == NCCK_Block)
10103         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10104       else
10105         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10106       break;
10107     }
10108 
10109     // In ARC, use some specialized diagnostics for occasions where we
10110     // infer 'const'.  These are always pseudo-strong variables.
10111     if (S.getLangOpts().ObjCAutoRefCount) {
10112       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10113       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10114         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10115 
10116         // Use the normal diagnostic if it's pseudo-__strong but the
10117         // user actually wrote 'const'.
10118         if (var->isARCPseudoStrong() &&
10119             (!var->getTypeSourceInfo() ||
10120              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10121           // There are two pseudo-strong cases:
10122           //  - self
10123           ObjCMethodDecl *method = S.getCurMethodDecl();
10124           if (method && var == method->getSelfDecl())
10125             DiagID = method->isClassMethod()
10126               ? diag::err_typecheck_arc_assign_self_class_method
10127               : diag::err_typecheck_arc_assign_self;
10128 
10129           //  - fast enumeration variables
10130           else
10131             DiagID = diag::err_typecheck_arr_assign_enumeration;
10132 
10133           SourceRange Assign;
10134           if (Loc != OrigLoc)
10135             Assign = SourceRange(OrigLoc, OrigLoc);
10136           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10137           // We need to preserve the AST regardless, so migration tool
10138           // can do its job.
10139           return false;
10140         }
10141       }
10142     }
10143 
10144     // If none of the special cases above are triggered, then this is a
10145     // simple const assignment.
10146     if (DiagID == 0) {
10147       DiagnoseConstAssignment(S, E, Loc);
10148       return true;
10149     }
10150 
10151     break;
10152   case Expr::MLV_ConstAddrSpace:
10153     DiagnoseConstAssignment(S, E, Loc);
10154     return true;
10155   case Expr::MLV_ArrayType:
10156   case Expr::MLV_ArrayTemporary:
10157     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10158     NeedType = true;
10159     break;
10160   case Expr::MLV_NotObjectType:
10161     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10162     NeedType = true;
10163     break;
10164   case Expr::MLV_LValueCast:
10165     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10166     break;
10167   case Expr::MLV_Valid:
10168     llvm_unreachable("did not take early return for MLV_Valid");
10169   case Expr::MLV_InvalidExpression:
10170   case Expr::MLV_MemberFunction:
10171   case Expr::MLV_ClassTemporary:
10172     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10173     break;
10174   case Expr::MLV_IncompleteType:
10175   case Expr::MLV_IncompleteVoidType:
10176     return S.RequireCompleteType(Loc, E->getType(),
10177              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10178   case Expr::MLV_DuplicateVectorComponents:
10179     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10180     break;
10181   case Expr::MLV_NoSetterProperty:
10182     llvm_unreachable("readonly properties should be processed differently");
10183   case Expr::MLV_InvalidMessageExpression:
10184     DiagID = diag::err_readonly_message_assignment;
10185     break;
10186   case Expr::MLV_SubObjCPropertySetting:
10187     DiagID = diag::err_no_subobject_property_setting;
10188     break;
10189   }
10190 
10191   SourceRange Assign;
10192   if (Loc != OrigLoc)
10193     Assign = SourceRange(OrigLoc, OrigLoc);
10194   if (NeedType)
10195     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10196   else
10197     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10198   return true;
10199 }
10200 
10201 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10202                                          SourceLocation Loc,
10203                                          Sema &Sema) {
10204   // C / C++ fields
10205   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10206   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10207   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10208     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10209       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10210   }
10211 
10212   // Objective-C instance variables
10213   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10214   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10215   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10216     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10217     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10218     if (RL && RR && RL->getDecl() == RR->getDecl())
10219       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10220   }
10221 }
10222 
10223 // C99 6.5.16.1
10224 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10225                                        SourceLocation Loc,
10226                                        QualType CompoundType) {
10227   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10228 
10229   // Verify that LHS is a modifiable lvalue, and emit error if not.
10230   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10231     return QualType();
10232 
10233   QualType LHSType = LHSExpr->getType();
10234   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10235                                              CompoundType;
10236   // OpenCL v1.2 s6.1.1.1 p2:
10237   // The half data type can only be used to declare a pointer to a buffer that
10238   // contains half values
10239   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10240     LHSType->isHalfType()) {
10241     Diag(Loc, diag::err_opencl_half_load_store) << 1
10242         << LHSType.getUnqualifiedType();
10243     return QualType();
10244   }
10245 
10246   AssignConvertType ConvTy;
10247   if (CompoundType.isNull()) {
10248     Expr *RHSCheck = RHS.get();
10249 
10250     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10251 
10252     QualType LHSTy(LHSType);
10253     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10254     if (RHS.isInvalid())
10255       return QualType();
10256     // Special case of NSObject attributes on c-style pointer types.
10257     if (ConvTy == IncompatiblePointer &&
10258         ((Context.isObjCNSObjectType(LHSType) &&
10259           RHSType->isObjCObjectPointerType()) ||
10260          (Context.isObjCNSObjectType(RHSType) &&
10261           LHSType->isObjCObjectPointerType())))
10262       ConvTy = Compatible;
10263 
10264     if (ConvTy == Compatible &&
10265         LHSType->isObjCObjectType())
10266         Diag(Loc, diag::err_objc_object_assignment)
10267           << LHSType;
10268 
10269     // If the RHS is a unary plus or minus, check to see if they = and + are
10270     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10271     // instead of "x += 4".
10272     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10273       RHSCheck = ICE->getSubExpr();
10274     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10275       if ((UO->getOpcode() == UO_Plus ||
10276            UO->getOpcode() == UO_Minus) &&
10277           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10278           // Only if the two operators are exactly adjacent.
10279           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10280           // And there is a space or other character before the subexpr of the
10281           // unary +/-.  We don't want to warn on "x=-1".
10282           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10283           UO->getSubExpr()->getLocStart().isFileID()) {
10284         Diag(Loc, diag::warn_not_compound_assign)
10285           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10286           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10287       }
10288     }
10289 
10290     if (ConvTy == Compatible) {
10291       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10292         // Warn about retain cycles where a block captures the LHS, but
10293         // not if the LHS is a simple variable into which the block is
10294         // being stored...unless that variable can be captured by reference!
10295         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10296         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10297         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10298           checkRetainCycles(LHSExpr, RHS.get());
10299 
10300         // It is safe to assign a weak reference into a strong variable.
10301         // Although this code can still have problems:
10302         //   id x = self.weakProp;
10303         //   id y = self.weakProp;
10304         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10305         // paths through the function. This should be revisited if
10306         // -Wrepeated-use-of-weak is made flow-sensitive.
10307         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10308                              RHS.get()->getLocStart()))
10309           getCurFunction()->markSafeWeakUse(RHS.get());
10310 
10311       } else if (getLangOpts().ObjCAutoRefCount) {
10312         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10313       }
10314     }
10315   } else {
10316     // Compound assignment "x += y"
10317     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10318   }
10319 
10320   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10321                                RHS.get(), AA_Assigning))
10322     return QualType();
10323 
10324   CheckForNullPointerDereference(*this, LHSExpr);
10325 
10326   // C99 6.5.16p3: The type of an assignment expression is the type of the
10327   // left operand unless the left operand has qualified type, in which case
10328   // it is the unqualified version of the type of the left operand.
10329   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10330   // is converted to the type of the assignment expression (above).
10331   // C++ 5.17p1: the type of the assignment expression is that of its left
10332   // operand.
10333   return (getLangOpts().CPlusPlus
10334           ? LHSType : LHSType.getUnqualifiedType());
10335 }
10336 
10337 // Only ignore explicit casts to void.
10338 static bool IgnoreCommaOperand(const Expr *E) {
10339   E = E->IgnoreParens();
10340 
10341   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10342     if (CE->getCastKind() == CK_ToVoid) {
10343       return true;
10344     }
10345   }
10346 
10347   return false;
10348 }
10349 
10350 // Look for instances where it is likely the comma operator is confused with
10351 // another operator.  There is a whitelist of acceptable expressions for the
10352 // left hand side of the comma operator, otherwise emit a warning.
10353 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10354   // No warnings in macros
10355   if (Loc.isMacroID())
10356     return;
10357 
10358   // Don't warn in template instantiations.
10359   if (inTemplateInstantiation())
10360     return;
10361 
10362   // Scope isn't fine-grained enough to whitelist the specific cases, so
10363   // instead, skip more than needed, then call back into here with the
10364   // CommaVisitor in SemaStmt.cpp.
10365   // The whitelisted locations are the initialization and increment portions
10366   // of a for loop.  The additional checks are on the condition of
10367   // if statements, do/while loops, and for loops.
10368   const unsigned ForIncrementFlags =
10369       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10370   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10371   const unsigned ScopeFlags = getCurScope()->getFlags();
10372   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10373       (ScopeFlags & ForInitFlags) == ForInitFlags)
10374     return;
10375 
10376   // If there are multiple comma operators used together, get the RHS of the
10377   // of the comma operator as the LHS.
10378   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10379     if (BO->getOpcode() != BO_Comma)
10380       break;
10381     LHS = BO->getRHS();
10382   }
10383 
10384   // Only allow some expressions on LHS to not warn.
10385   if (IgnoreCommaOperand(LHS))
10386     return;
10387 
10388   Diag(Loc, diag::warn_comma_operator);
10389   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10390       << LHS->getSourceRange()
10391       << FixItHint::CreateInsertion(LHS->getLocStart(),
10392                                     LangOpts.CPlusPlus ? "static_cast<void>("
10393                                                        : "(void)(")
10394       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10395                                     ")");
10396 }
10397 
10398 // C99 6.5.17
10399 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10400                                    SourceLocation Loc) {
10401   LHS = S.CheckPlaceholderExpr(LHS.get());
10402   RHS = S.CheckPlaceholderExpr(RHS.get());
10403   if (LHS.isInvalid() || RHS.isInvalid())
10404     return QualType();
10405 
10406   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10407   // operands, but not unary promotions.
10408   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10409 
10410   // So we treat the LHS as a ignored value, and in C++ we allow the
10411   // containing site to determine what should be done with the RHS.
10412   LHS = S.IgnoredValueConversions(LHS.get());
10413   if (LHS.isInvalid())
10414     return QualType();
10415 
10416   S.DiagnoseUnusedExprResult(LHS.get());
10417 
10418   if (!S.getLangOpts().CPlusPlus) {
10419     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10420     if (RHS.isInvalid())
10421       return QualType();
10422     if (!RHS.get()->getType()->isVoidType())
10423       S.RequireCompleteType(Loc, RHS.get()->getType(),
10424                             diag::err_incomplete_type);
10425   }
10426 
10427   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10428     S.DiagnoseCommaOperator(LHS.get(), Loc);
10429 
10430   return RHS.get()->getType();
10431 }
10432 
10433 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10434 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10435 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10436                                                ExprValueKind &VK,
10437                                                ExprObjectKind &OK,
10438                                                SourceLocation OpLoc,
10439                                                bool IsInc, bool IsPrefix) {
10440   if (Op->isTypeDependent())
10441     return S.Context.DependentTy;
10442 
10443   QualType ResType = Op->getType();
10444   // Atomic types can be used for increment / decrement where the non-atomic
10445   // versions can, so ignore the _Atomic() specifier for the purpose of
10446   // checking.
10447   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10448     ResType = ResAtomicType->getValueType();
10449 
10450   assert(!ResType.isNull() && "no type for increment/decrement expression");
10451 
10452   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10453     // Decrement of bool is not allowed.
10454     if (!IsInc) {
10455       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10456       return QualType();
10457     }
10458     // Increment of bool sets it to true, but is deprecated.
10459     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10460                                               : diag::warn_increment_bool)
10461       << Op->getSourceRange();
10462   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10463     // Error on enum increments and decrements in C++ mode
10464     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10465     return QualType();
10466   } else if (ResType->isRealType()) {
10467     // OK!
10468   } else if (ResType->isPointerType()) {
10469     // C99 6.5.2.4p2, 6.5.6p2
10470     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10471       return QualType();
10472   } else if (ResType->isObjCObjectPointerType()) {
10473     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10474     // Otherwise, we just need a complete type.
10475     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10476         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10477       return QualType();
10478   } else if (ResType->isAnyComplexType()) {
10479     // C99 does not support ++/-- on complex types, we allow as an extension.
10480     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10481       << ResType << Op->getSourceRange();
10482   } else if (ResType->isPlaceholderType()) {
10483     ExprResult PR = S.CheckPlaceholderExpr(Op);
10484     if (PR.isInvalid()) return QualType();
10485     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10486                                           IsInc, IsPrefix);
10487   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10488     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10489   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10490              (ResType->getAs<VectorType>()->getVectorKind() !=
10491               VectorType::AltiVecBool)) {
10492     // The z vector extensions allow ++ and -- for non-bool vectors.
10493   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10494             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10495     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10496   } else {
10497     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10498       << ResType << int(IsInc) << Op->getSourceRange();
10499     return QualType();
10500   }
10501   // At this point, we know we have a real, complex or pointer type.
10502   // Now make sure the operand is a modifiable lvalue.
10503   if (CheckForModifiableLvalue(Op, OpLoc, S))
10504     return QualType();
10505   // In C++, a prefix increment is the same type as the operand. Otherwise
10506   // (in C or with postfix), the increment is the unqualified type of the
10507   // operand.
10508   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10509     VK = VK_LValue;
10510     OK = Op->getObjectKind();
10511     return ResType;
10512   } else {
10513     VK = VK_RValue;
10514     return ResType.getUnqualifiedType();
10515   }
10516 }
10517 
10518 
10519 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10520 /// This routine allows us to typecheck complex/recursive expressions
10521 /// where the declaration is needed for type checking. We only need to
10522 /// handle cases when the expression references a function designator
10523 /// or is an lvalue. Here are some examples:
10524 ///  - &(x) => x
10525 ///  - &*****f => f for f a function designator.
10526 ///  - &s.xx => s
10527 ///  - &s.zz[1].yy -> s, if zz is an array
10528 ///  - *(x + 1) -> x, if x is an array
10529 ///  - &"123"[2] -> 0
10530 ///  - & __real__ x -> x
10531 static ValueDecl *getPrimaryDecl(Expr *E) {
10532   switch (E->getStmtClass()) {
10533   case Stmt::DeclRefExprClass:
10534     return cast<DeclRefExpr>(E)->getDecl();
10535   case Stmt::MemberExprClass:
10536     // If this is an arrow operator, the address is an offset from
10537     // the base's value, so the object the base refers to is
10538     // irrelevant.
10539     if (cast<MemberExpr>(E)->isArrow())
10540       return nullptr;
10541     // Otherwise, the expression refers to a part of the base
10542     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10543   case Stmt::ArraySubscriptExprClass: {
10544     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10545     // promotion of register arrays earlier.
10546     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10547     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10548       if (ICE->getSubExpr()->getType()->isArrayType())
10549         return getPrimaryDecl(ICE->getSubExpr());
10550     }
10551     return nullptr;
10552   }
10553   case Stmt::UnaryOperatorClass: {
10554     UnaryOperator *UO = cast<UnaryOperator>(E);
10555 
10556     switch(UO->getOpcode()) {
10557     case UO_Real:
10558     case UO_Imag:
10559     case UO_Extension:
10560       return getPrimaryDecl(UO->getSubExpr());
10561     default:
10562       return nullptr;
10563     }
10564   }
10565   case Stmt::ParenExprClass:
10566     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10567   case Stmt::ImplicitCastExprClass:
10568     // If the result of an implicit cast is an l-value, we care about
10569     // the sub-expression; otherwise, the result here doesn't matter.
10570     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10571   default:
10572     return nullptr;
10573   }
10574 }
10575 
10576 namespace {
10577   enum {
10578     AO_Bit_Field = 0,
10579     AO_Vector_Element = 1,
10580     AO_Property_Expansion = 2,
10581     AO_Register_Variable = 3,
10582     AO_No_Error = 4
10583   };
10584 }
10585 /// \brief Diagnose invalid operand for address of operations.
10586 ///
10587 /// \param Type The type of operand which cannot have its address taken.
10588 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10589                                          Expr *E, unsigned Type) {
10590   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10591 }
10592 
10593 /// CheckAddressOfOperand - The operand of & must be either a function
10594 /// designator or an lvalue designating an object. If it is an lvalue, the
10595 /// object cannot be declared with storage class register or be a bit field.
10596 /// Note: The usual conversions are *not* applied to the operand of the &
10597 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10598 /// In C++, the operand might be an overloaded function name, in which case
10599 /// we allow the '&' but retain the overloaded-function type.
10600 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10601   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10602     if (PTy->getKind() == BuiltinType::Overload) {
10603       Expr *E = OrigOp.get()->IgnoreParens();
10604       if (!isa<OverloadExpr>(E)) {
10605         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10606         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10607           << OrigOp.get()->getSourceRange();
10608         return QualType();
10609       }
10610 
10611       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10612       if (isa<UnresolvedMemberExpr>(Ovl))
10613         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10614           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10615             << OrigOp.get()->getSourceRange();
10616           return QualType();
10617         }
10618 
10619       return Context.OverloadTy;
10620     }
10621 
10622     if (PTy->getKind() == BuiltinType::UnknownAny)
10623       return Context.UnknownAnyTy;
10624 
10625     if (PTy->getKind() == BuiltinType::BoundMember) {
10626       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10627         << OrigOp.get()->getSourceRange();
10628       return QualType();
10629     }
10630 
10631     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10632     if (OrigOp.isInvalid()) return QualType();
10633   }
10634 
10635   if (OrigOp.get()->isTypeDependent())
10636     return Context.DependentTy;
10637 
10638   assert(!OrigOp.get()->getType()->isPlaceholderType());
10639 
10640   // Make sure to ignore parentheses in subsequent checks
10641   Expr *op = OrigOp.get()->IgnoreParens();
10642 
10643   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10644   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10645     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10646     return QualType();
10647   }
10648 
10649   if (getLangOpts().C99) {
10650     // Implement C99-only parts of addressof rules.
10651     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10652       if (uOp->getOpcode() == UO_Deref)
10653         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10654         // (assuming the deref expression is valid).
10655         return uOp->getSubExpr()->getType();
10656     }
10657     // Technically, there should be a check for array subscript
10658     // expressions here, but the result of one is always an lvalue anyway.
10659   }
10660   ValueDecl *dcl = getPrimaryDecl(op);
10661 
10662   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10663     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10664                                            op->getLocStart()))
10665       return QualType();
10666 
10667   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10668   unsigned AddressOfError = AO_No_Error;
10669 
10670   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10671     bool sfinae = (bool)isSFINAEContext();
10672     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10673                                   : diag::ext_typecheck_addrof_temporary)
10674       << op->getType() << op->getSourceRange();
10675     if (sfinae)
10676       return QualType();
10677     // Materialize the temporary as an lvalue so that we can take its address.
10678     OrigOp = op =
10679         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10680   } else if (isa<ObjCSelectorExpr>(op)) {
10681     return Context.getPointerType(op->getType());
10682   } else if (lval == Expr::LV_MemberFunction) {
10683     // If it's an instance method, make a member pointer.
10684     // The expression must have exactly the form &A::foo.
10685 
10686     // If the underlying expression isn't a decl ref, give up.
10687     if (!isa<DeclRefExpr>(op)) {
10688       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10689         << OrigOp.get()->getSourceRange();
10690       return QualType();
10691     }
10692     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10693     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10694 
10695     // The id-expression was parenthesized.
10696     if (OrigOp.get() != DRE) {
10697       Diag(OpLoc, diag::err_parens_pointer_member_function)
10698         << OrigOp.get()->getSourceRange();
10699 
10700     // The method was named without a qualifier.
10701     } else if (!DRE->getQualifier()) {
10702       if (MD->getParent()->getName().empty())
10703         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10704           << op->getSourceRange();
10705       else {
10706         SmallString<32> Str;
10707         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10708         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10709           << op->getSourceRange()
10710           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10711       }
10712     }
10713 
10714     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10715     if (isa<CXXDestructorDecl>(MD))
10716       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10717 
10718     QualType MPTy = Context.getMemberPointerType(
10719         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10720     // Under the MS ABI, lock down the inheritance model now.
10721     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10722       (void)isCompleteType(OpLoc, MPTy);
10723     return MPTy;
10724   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10725     // C99 6.5.3.2p1
10726     // The operand must be either an l-value or a function designator
10727     if (!op->getType()->isFunctionType()) {
10728       // Use a special diagnostic for loads from property references.
10729       if (isa<PseudoObjectExpr>(op)) {
10730         AddressOfError = AO_Property_Expansion;
10731       } else {
10732         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10733           << op->getType() << op->getSourceRange();
10734         return QualType();
10735       }
10736     }
10737   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10738     // The operand cannot be a bit-field
10739     AddressOfError = AO_Bit_Field;
10740   } else if (op->getObjectKind() == OK_VectorComponent) {
10741     // The operand cannot be an element of a vector
10742     AddressOfError = AO_Vector_Element;
10743   } else if (dcl) { // C99 6.5.3.2p1
10744     // We have an lvalue with a decl. Make sure the decl is not declared
10745     // with the register storage-class specifier.
10746     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10747       // in C++ it is not error to take address of a register
10748       // variable (c++03 7.1.1P3)
10749       if (vd->getStorageClass() == SC_Register &&
10750           !getLangOpts().CPlusPlus) {
10751         AddressOfError = AO_Register_Variable;
10752       }
10753     } else if (isa<MSPropertyDecl>(dcl)) {
10754       AddressOfError = AO_Property_Expansion;
10755     } else if (isa<FunctionTemplateDecl>(dcl)) {
10756       return Context.OverloadTy;
10757     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10758       // Okay: we can take the address of a field.
10759       // Could be a pointer to member, though, if there is an explicit
10760       // scope qualifier for the class.
10761       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10762         DeclContext *Ctx = dcl->getDeclContext();
10763         if (Ctx && Ctx->isRecord()) {
10764           if (dcl->getType()->isReferenceType()) {
10765             Diag(OpLoc,
10766                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10767               << dcl->getDeclName() << dcl->getType();
10768             return QualType();
10769           }
10770 
10771           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10772             Ctx = Ctx->getParent();
10773 
10774           QualType MPTy = Context.getMemberPointerType(
10775               op->getType(),
10776               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10777           // Under the MS ABI, lock down the inheritance model now.
10778           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10779             (void)isCompleteType(OpLoc, MPTy);
10780           return MPTy;
10781         }
10782       }
10783     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10784                !isa<BindingDecl>(dcl))
10785       llvm_unreachable("Unknown/unexpected decl type");
10786   }
10787 
10788   if (AddressOfError != AO_No_Error) {
10789     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10790     return QualType();
10791   }
10792 
10793   if (lval == Expr::LV_IncompleteVoidType) {
10794     // Taking the address of a void variable is technically illegal, but we
10795     // allow it in cases which are otherwise valid.
10796     // Example: "extern void x; void* y = &x;".
10797     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10798   }
10799 
10800   // If the operand has type "type", the result has type "pointer to type".
10801   if (op->getType()->isObjCObjectType())
10802     return Context.getObjCObjectPointerType(op->getType());
10803 
10804   CheckAddressOfPackedMember(op);
10805 
10806   return Context.getPointerType(op->getType());
10807 }
10808 
10809 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10810   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10811   if (!DRE)
10812     return;
10813   const Decl *D = DRE->getDecl();
10814   if (!D)
10815     return;
10816   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10817   if (!Param)
10818     return;
10819   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10820     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10821       return;
10822   if (FunctionScopeInfo *FD = S.getCurFunction())
10823     if (!FD->ModifiedNonNullParams.count(Param))
10824       FD->ModifiedNonNullParams.insert(Param);
10825 }
10826 
10827 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10828 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10829                                         SourceLocation OpLoc) {
10830   if (Op->isTypeDependent())
10831     return S.Context.DependentTy;
10832 
10833   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10834   if (ConvResult.isInvalid())
10835     return QualType();
10836   Op = ConvResult.get();
10837   QualType OpTy = Op->getType();
10838   QualType Result;
10839 
10840   if (isa<CXXReinterpretCastExpr>(Op)) {
10841     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10842     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10843                                      Op->getSourceRange());
10844   }
10845 
10846   if (const PointerType *PT = OpTy->getAs<PointerType>())
10847   {
10848     Result = PT->getPointeeType();
10849   }
10850   else if (const ObjCObjectPointerType *OPT =
10851              OpTy->getAs<ObjCObjectPointerType>())
10852     Result = OPT->getPointeeType();
10853   else {
10854     ExprResult PR = S.CheckPlaceholderExpr(Op);
10855     if (PR.isInvalid()) return QualType();
10856     if (PR.get() != Op)
10857       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10858   }
10859 
10860   if (Result.isNull()) {
10861     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10862       << OpTy << Op->getSourceRange();
10863     return QualType();
10864   }
10865 
10866   // Note that per both C89 and C99, indirection is always legal, even if Result
10867   // is an incomplete type or void.  It would be possible to warn about
10868   // dereferencing a void pointer, but it's completely well-defined, and such a
10869   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10870   // for pointers to 'void' but is fine for any other pointer type:
10871   //
10872   // C++ [expr.unary.op]p1:
10873   //   [...] the expression to which [the unary * operator] is applied shall
10874   //   be a pointer to an object type, or a pointer to a function type
10875   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10876     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10877       << OpTy << Op->getSourceRange();
10878 
10879   // Dereferences are usually l-values...
10880   VK = VK_LValue;
10881 
10882   // ...except that certain expressions are never l-values in C.
10883   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10884     VK = VK_RValue;
10885 
10886   return Result;
10887 }
10888 
10889 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10890   BinaryOperatorKind Opc;
10891   switch (Kind) {
10892   default: llvm_unreachable("Unknown binop!");
10893   case tok::periodstar:           Opc = BO_PtrMemD; break;
10894   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10895   case tok::star:                 Opc = BO_Mul; break;
10896   case tok::slash:                Opc = BO_Div; break;
10897   case tok::percent:              Opc = BO_Rem; break;
10898   case tok::plus:                 Opc = BO_Add; break;
10899   case tok::minus:                Opc = BO_Sub; break;
10900   case tok::lessless:             Opc = BO_Shl; break;
10901   case tok::greatergreater:       Opc = BO_Shr; break;
10902   case tok::lessequal:            Opc = BO_LE; break;
10903   case tok::less:                 Opc = BO_LT; break;
10904   case tok::greaterequal:         Opc = BO_GE; break;
10905   case tok::greater:              Opc = BO_GT; break;
10906   case tok::exclaimequal:         Opc = BO_NE; break;
10907   case tok::equalequal:           Opc = BO_EQ; break;
10908   case tok::amp:                  Opc = BO_And; break;
10909   case tok::caret:                Opc = BO_Xor; break;
10910   case tok::pipe:                 Opc = BO_Or; break;
10911   case tok::ampamp:               Opc = BO_LAnd; break;
10912   case tok::pipepipe:             Opc = BO_LOr; break;
10913   case tok::equal:                Opc = BO_Assign; break;
10914   case tok::starequal:            Opc = BO_MulAssign; break;
10915   case tok::slashequal:           Opc = BO_DivAssign; break;
10916   case tok::percentequal:         Opc = BO_RemAssign; break;
10917   case tok::plusequal:            Opc = BO_AddAssign; break;
10918   case tok::minusequal:           Opc = BO_SubAssign; break;
10919   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10920   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10921   case tok::ampequal:             Opc = BO_AndAssign; break;
10922   case tok::caretequal:           Opc = BO_XorAssign; break;
10923   case tok::pipeequal:            Opc = BO_OrAssign; break;
10924   case tok::comma:                Opc = BO_Comma; break;
10925   }
10926   return Opc;
10927 }
10928 
10929 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10930   tok::TokenKind Kind) {
10931   UnaryOperatorKind Opc;
10932   switch (Kind) {
10933   default: llvm_unreachable("Unknown unary op!");
10934   case tok::plusplus:     Opc = UO_PreInc; break;
10935   case tok::minusminus:   Opc = UO_PreDec; break;
10936   case tok::amp:          Opc = UO_AddrOf; break;
10937   case tok::star:         Opc = UO_Deref; break;
10938   case tok::plus:         Opc = UO_Plus; break;
10939   case tok::minus:        Opc = UO_Minus; break;
10940   case tok::tilde:        Opc = UO_Not; break;
10941   case tok::exclaim:      Opc = UO_LNot; break;
10942   case tok::kw___real:    Opc = UO_Real; break;
10943   case tok::kw___imag:    Opc = UO_Imag; break;
10944   case tok::kw___extension__: Opc = UO_Extension; break;
10945   }
10946   return Opc;
10947 }
10948 
10949 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10950 /// This warning is only emitted for builtin assignment operations. It is also
10951 /// suppressed in the event of macro expansions.
10952 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10953                                    SourceLocation OpLoc) {
10954   if (S.inTemplateInstantiation())
10955     return;
10956   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10957     return;
10958   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10959   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10960   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10961   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10962   if (!LHSDeclRef || !RHSDeclRef ||
10963       LHSDeclRef->getLocation().isMacroID() ||
10964       RHSDeclRef->getLocation().isMacroID())
10965     return;
10966   const ValueDecl *LHSDecl =
10967     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10968   const ValueDecl *RHSDecl =
10969     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10970   if (LHSDecl != RHSDecl)
10971     return;
10972   if (LHSDecl->getType().isVolatileQualified())
10973     return;
10974   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10975     if (RefTy->getPointeeType().isVolatileQualified())
10976       return;
10977 
10978   S.Diag(OpLoc, diag::warn_self_assignment)
10979       << LHSDeclRef->getType()
10980       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10981 }
10982 
10983 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10984 /// is usually indicative of introspection within the Objective-C pointer.
10985 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10986                                           SourceLocation OpLoc) {
10987   if (!S.getLangOpts().ObjC1)
10988     return;
10989 
10990   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10991   const Expr *LHS = L.get();
10992   const Expr *RHS = R.get();
10993 
10994   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10995     ObjCPointerExpr = LHS;
10996     OtherExpr = RHS;
10997   }
10998   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10999     ObjCPointerExpr = RHS;
11000     OtherExpr = LHS;
11001   }
11002 
11003   // This warning is deliberately made very specific to reduce false
11004   // positives with logic that uses '&' for hashing.  This logic mainly
11005   // looks for code trying to introspect into tagged pointers, which
11006   // code should generally never do.
11007   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11008     unsigned Diag = diag::warn_objc_pointer_masking;
11009     // Determine if we are introspecting the result of performSelectorXXX.
11010     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11011     // Special case messages to -performSelector and friends, which
11012     // can return non-pointer values boxed in a pointer value.
11013     // Some clients may wish to silence warnings in this subcase.
11014     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11015       Selector S = ME->getSelector();
11016       StringRef SelArg0 = S.getNameForSlot(0);
11017       if (SelArg0.startswith("performSelector"))
11018         Diag = diag::warn_objc_pointer_masking_performSelector;
11019     }
11020 
11021     S.Diag(OpLoc, Diag)
11022       << ObjCPointerExpr->getSourceRange();
11023   }
11024 }
11025 
11026 static NamedDecl *getDeclFromExpr(Expr *E) {
11027   if (!E)
11028     return nullptr;
11029   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11030     return DRE->getDecl();
11031   if (auto *ME = dyn_cast<MemberExpr>(E))
11032     return ME->getMemberDecl();
11033   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11034     return IRE->getDecl();
11035   return nullptr;
11036 }
11037 
11038 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11039 /// operator @p Opc at location @c TokLoc. This routine only supports
11040 /// built-in operations; ActOnBinOp handles overloaded operators.
11041 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11042                                     BinaryOperatorKind Opc,
11043                                     Expr *LHSExpr, Expr *RHSExpr) {
11044   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11045     // The syntax only allows initializer lists on the RHS of assignment,
11046     // so we don't need to worry about accepting invalid code for
11047     // non-assignment operators.
11048     // C++11 5.17p9:
11049     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11050     //   of x = {} is x = T().
11051     InitializationKind Kind =
11052         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11053     InitializedEntity Entity =
11054         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11055     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11056     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11057     if (Init.isInvalid())
11058       return Init;
11059     RHSExpr = Init.get();
11060   }
11061 
11062   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11063   QualType ResultTy;     // Result type of the binary operator.
11064   // The following two variables are used for compound assignment operators
11065   QualType CompLHSTy;    // Type of LHS after promotions for computation
11066   QualType CompResultTy; // Type of computation result
11067   ExprValueKind VK = VK_RValue;
11068   ExprObjectKind OK = OK_Ordinary;
11069 
11070   if (!getLangOpts().CPlusPlus) {
11071     // C cannot handle TypoExpr nodes on either side of a binop because it
11072     // doesn't handle dependent types properly, so make sure any TypoExprs have
11073     // been dealt with before checking the operands.
11074     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11075     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11076       if (Opc != BO_Assign)
11077         return ExprResult(E);
11078       // Avoid correcting the RHS to the same Expr as the LHS.
11079       Decl *D = getDeclFromExpr(E);
11080       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11081     });
11082     if (!LHS.isUsable() || !RHS.isUsable())
11083       return ExprError();
11084   }
11085 
11086   if (getLangOpts().OpenCL) {
11087     QualType LHSTy = LHSExpr->getType();
11088     QualType RHSTy = RHSExpr->getType();
11089     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11090     // the ATOMIC_VAR_INIT macro.
11091     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11092       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11093       if (BO_Assign == Opc)
11094         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11095       else
11096         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11097       return ExprError();
11098     }
11099 
11100     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11101     // only with a builtin functions and therefore should be disallowed here.
11102     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11103         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11104         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11105         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11106       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11107       return ExprError();
11108     }
11109   }
11110 
11111   switch (Opc) {
11112   case BO_Assign:
11113     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11114     if (getLangOpts().CPlusPlus &&
11115         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11116       VK = LHS.get()->getValueKind();
11117       OK = LHS.get()->getObjectKind();
11118     }
11119     if (!ResultTy.isNull()) {
11120       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11121       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11122     }
11123     RecordModifiableNonNullParam(*this, LHS.get());
11124     break;
11125   case BO_PtrMemD:
11126   case BO_PtrMemI:
11127     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11128                                             Opc == BO_PtrMemI);
11129     break;
11130   case BO_Mul:
11131   case BO_Div:
11132     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11133                                            Opc == BO_Div);
11134     break;
11135   case BO_Rem:
11136     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11137     break;
11138   case BO_Add:
11139     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11140     break;
11141   case BO_Sub:
11142     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11143     break;
11144   case BO_Shl:
11145   case BO_Shr:
11146     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11147     break;
11148   case BO_LE:
11149   case BO_LT:
11150   case BO_GE:
11151   case BO_GT:
11152     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11153     break;
11154   case BO_EQ:
11155   case BO_NE:
11156     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11157     break;
11158   case BO_And:
11159     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11160   case BO_Xor:
11161   case BO_Or:
11162     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11163     break;
11164   case BO_LAnd:
11165   case BO_LOr:
11166     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11167     break;
11168   case BO_MulAssign:
11169   case BO_DivAssign:
11170     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11171                                                Opc == BO_DivAssign);
11172     CompLHSTy = CompResultTy;
11173     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11174       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11175     break;
11176   case BO_RemAssign:
11177     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11178     CompLHSTy = CompResultTy;
11179     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11180       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11181     break;
11182   case BO_AddAssign:
11183     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11184     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11185       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11186     break;
11187   case BO_SubAssign:
11188     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11189     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11190       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11191     break;
11192   case BO_ShlAssign:
11193   case BO_ShrAssign:
11194     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11195     CompLHSTy = CompResultTy;
11196     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11197       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11198     break;
11199   case BO_AndAssign:
11200   case BO_OrAssign: // fallthrough
11201     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11202   case BO_XorAssign:
11203     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11204     CompLHSTy = CompResultTy;
11205     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11206       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11207     break;
11208   case BO_Comma:
11209     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11210     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11211       VK = RHS.get()->getValueKind();
11212       OK = RHS.get()->getObjectKind();
11213     }
11214     break;
11215   }
11216   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11217     return ExprError();
11218 
11219   // Check for array bounds violations for both sides of the BinaryOperator
11220   CheckArrayAccess(LHS.get());
11221   CheckArrayAccess(RHS.get());
11222 
11223   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11224     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11225                                                  &Context.Idents.get("object_setClass"),
11226                                                  SourceLocation(), LookupOrdinaryName);
11227     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11228       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11229       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11230       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11231       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11232       FixItHint::CreateInsertion(RHSLocEnd, ")");
11233     }
11234     else
11235       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11236   }
11237   else if (const ObjCIvarRefExpr *OIRE =
11238            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11239     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11240 
11241   if (CompResultTy.isNull())
11242     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11243                                         OK, OpLoc, FPFeatures.fp_contract);
11244   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11245       OK_ObjCProperty) {
11246     VK = VK_LValue;
11247     OK = LHS.get()->getObjectKind();
11248   }
11249   return new (Context) CompoundAssignOperator(
11250       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11251       OpLoc, FPFeatures.fp_contract);
11252 }
11253 
11254 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11255 /// operators are mixed in a way that suggests that the programmer forgot that
11256 /// comparison operators have higher precedence. The most typical example of
11257 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11258 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11259                                       SourceLocation OpLoc, Expr *LHSExpr,
11260                                       Expr *RHSExpr) {
11261   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11262   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11263 
11264   // Check that one of the sides is a comparison operator and the other isn't.
11265   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11266   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11267   if (isLeftComp == isRightComp)
11268     return;
11269 
11270   // Bitwise operations are sometimes used as eager logical ops.
11271   // Don't diagnose this.
11272   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11273   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11274   if (isLeftBitwise || isRightBitwise)
11275     return;
11276 
11277   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11278                                                    OpLoc)
11279                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11280   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11281   SourceRange ParensRange = isLeftComp ?
11282       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11283     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11284 
11285   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11286     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11287   SuggestParentheses(Self, OpLoc,
11288     Self.PDiag(diag::note_precedence_silence) << OpStr,
11289     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11290   SuggestParentheses(Self, OpLoc,
11291     Self.PDiag(diag::note_precedence_bitwise_first)
11292       << BinaryOperator::getOpcodeStr(Opc),
11293     ParensRange);
11294 }
11295 
11296 /// \brief It accepts a '&&' expr that is inside a '||' one.
11297 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11298 /// in parentheses.
11299 static void
11300 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11301                                        BinaryOperator *Bop) {
11302   assert(Bop->getOpcode() == BO_LAnd);
11303   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11304       << Bop->getSourceRange() << OpLoc;
11305   SuggestParentheses(Self, Bop->getOperatorLoc(),
11306     Self.PDiag(diag::note_precedence_silence)
11307       << Bop->getOpcodeStr(),
11308     Bop->getSourceRange());
11309 }
11310 
11311 /// \brief Returns true if the given expression can be evaluated as a constant
11312 /// 'true'.
11313 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11314   bool Res;
11315   return !E->isValueDependent() &&
11316          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11317 }
11318 
11319 /// \brief Returns true if the given expression can be evaluated as a constant
11320 /// 'false'.
11321 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11322   bool Res;
11323   return !E->isValueDependent() &&
11324          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11325 }
11326 
11327 /// \brief Look for '&&' in the left hand of a '||' expr.
11328 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11329                                              Expr *LHSExpr, Expr *RHSExpr) {
11330   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11331     if (Bop->getOpcode() == BO_LAnd) {
11332       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11333       if (EvaluatesAsFalse(S, RHSExpr))
11334         return;
11335       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11336       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11337         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11338     } else if (Bop->getOpcode() == BO_LOr) {
11339       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11340         // If it's "a || b && 1 || c" we didn't warn earlier for
11341         // "a || b && 1", but warn now.
11342         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11343           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11344       }
11345     }
11346   }
11347 }
11348 
11349 /// \brief Look for '&&' in the right hand of a '||' expr.
11350 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11351                                              Expr *LHSExpr, Expr *RHSExpr) {
11352   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11353     if (Bop->getOpcode() == BO_LAnd) {
11354       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11355       if (EvaluatesAsFalse(S, LHSExpr))
11356         return;
11357       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11358       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11359         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11360     }
11361   }
11362 }
11363 
11364 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11365 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11366 /// the '&' expression in parentheses.
11367 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11368                                          SourceLocation OpLoc, Expr *SubExpr) {
11369   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11370     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11371       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11372         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11373         << Bop->getSourceRange() << OpLoc;
11374       SuggestParentheses(S, Bop->getOperatorLoc(),
11375         S.PDiag(diag::note_precedence_silence)
11376           << Bop->getOpcodeStr(),
11377         Bop->getSourceRange());
11378     }
11379   }
11380 }
11381 
11382 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11383                                     Expr *SubExpr, StringRef Shift) {
11384   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11385     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11386       StringRef Op = Bop->getOpcodeStr();
11387       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11388           << Bop->getSourceRange() << OpLoc << Shift << Op;
11389       SuggestParentheses(S, Bop->getOperatorLoc(),
11390           S.PDiag(diag::note_precedence_silence) << Op,
11391           Bop->getSourceRange());
11392     }
11393   }
11394 }
11395 
11396 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11397                                  Expr *LHSExpr, Expr *RHSExpr) {
11398   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11399   if (!OCE)
11400     return;
11401 
11402   FunctionDecl *FD = OCE->getDirectCallee();
11403   if (!FD || !FD->isOverloadedOperator())
11404     return;
11405 
11406   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11407   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11408     return;
11409 
11410   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11411       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11412       << (Kind == OO_LessLess);
11413   SuggestParentheses(S, OCE->getOperatorLoc(),
11414                      S.PDiag(diag::note_precedence_silence)
11415                          << (Kind == OO_LessLess ? "<<" : ">>"),
11416                      OCE->getSourceRange());
11417   SuggestParentheses(S, OpLoc,
11418                      S.PDiag(diag::note_evaluate_comparison_first),
11419                      SourceRange(OCE->getArg(1)->getLocStart(),
11420                                  RHSExpr->getLocEnd()));
11421 }
11422 
11423 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11424 /// precedence.
11425 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11426                                     SourceLocation OpLoc, Expr *LHSExpr,
11427                                     Expr *RHSExpr){
11428   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11429   if (BinaryOperator::isBitwiseOp(Opc))
11430     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11431 
11432   // Diagnose "arg1 & arg2 | arg3"
11433   if ((Opc == BO_Or || Opc == BO_Xor) &&
11434       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11435     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11436     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11437   }
11438 
11439   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11440   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11441   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11442     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11443     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11444   }
11445 
11446   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11447       || Opc == BO_Shr) {
11448     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11449     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11450     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11451   }
11452 
11453   // Warn on overloaded shift operators and comparisons, such as:
11454   // cout << 5 == 4;
11455   if (BinaryOperator::isComparisonOp(Opc))
11456     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11457 }
11458 
11459 // Binary Operators.  'Tok' is the token for the operator.
11460 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11461                             tok::TokenKind Kind,
11462                             Expr *LHSExpr, Expr *RHSExpr) {
11463   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11464   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11465   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11466 
11467   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11468   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11469 
11470   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11471 }
11472 
11473 /// Build an overloaded binary operator expression in the given scope.
11474 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11475                                        BinaryOperatorKind Opc,
11476                                        Expr *LHS, Expr *RHS) {
11477   // Find all of the overloaded operators visible from this
11478   // point. We perform both an operator-name lookup from the local
11479   // scope and an argument-dependent lookup based on the types of
11480   // the arguments.
11481   UnresolvedSet<16> Functions;
11482   OverloadedOperatorKind OverOp
11483     = BinaryOperator::getOverloadedOperator(Opc);
11484   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11485     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11486                                    RHS->getType(), Functions);
11487 
11488   // Build the (potentially-overloaded, potentially-dependent)
11489   // binary operation.
11490   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11491 }
11492 
11493 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11494                             BinaryOperatorKind Opc,
11495                             Expr *LHSExpr, Expr *RHSExpr) {
11496   // We want to end up calling one of checkPseudoObjectAssignment
11497   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11498   // both expressions are overloadable or either is type-dependent),
11499   // or CreateBuiltinBinOp (in any other case).  We also want to get
11500   // any placeholder types out of the way.
11501 
11502   // Handle pseudo-objects in the LHS.
11503   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11504     // Assignments with a pseudo-object l-value need special analysis.
11505     if (pty->getKind() == BuiltinType::PseudoObject &&
11506         BinaryOperator::isAssignmentOp(Opc))
11507       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11508 
11509     // Don't resolve overloads if the other type is overloadable.
11510     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11511       // We can't actually test that if we still have a placeholder,
11512       // though.  Fortunately, none of the exceptions we see in that
11513       // code below are valid when the LHS is an overload set.  Note
11514       // that an overload set can be dependently-typed, but it never
11515       // instantiates to having an overloadable type.
11516       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11517       if (resolvedRHS.isInvalid()) return ExprError();
11518       RHSExpr = resolvedRHS.get();
11519 
11520       if (RHSExpr->isTypeDependent() ||
11521           RHSExpr->getType()->isOverloadableType())
11522         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11523     }
11524 
11525     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11526     if (LHS.isInvalid()) return ExprError();
11527     LHSExpr = LHS.get();
11528   }
11529 
11530   // Handle pseudo-objects in the RHS.
11531   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11532     // An overload in the RHS can potentially be resolved by the type
11533     // being assigned to.
11534     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11535       if (getLangOpts().CPlusPlus &&
11536           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11537            LHSExpr->getType()->isOverloadableType()))
11538         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11539 
11540       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11541     }
11542 
11543     // Don't resolve overloads if the other type is overloadable.
11544     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11545         LHSExpr->getType()->isOverloadableType())
11546       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11547 
11548     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11549     if (!resolvedRHS.isUsable()) return ExprError();
11550     RHSExpr = resolvedRHS.get();
11551   }
11552 
11553   if (getLangOpts().CPlusPlus) {
11554     // If either expression is type-dependent, always build an
11555     // overloaded op.
11556     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11557       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11558 
11559     // Otherwise, build an overloaded op if either expression has an
11560     // overloadable type.
11561     if (LHSExpr->getType()->isOverloadableType() ||
11562         RHSExpr->getType()->isOverloadableType())
11563       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11564   }
11565 
11566   // Build a built-in binary operation.
11567   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11568 }
11569 
11570 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11571                                       UnaryOperatorKind Opc,
11572                                       Expr *InputExpr) {
11573   ExprResult Input = InputExpr;
11574   ExprValueKind VK = VK_RValue;
11575   ExprObjectKind OK = OK_Ordinary;
11576   QualType resultType;
11577   if (getLangOpts().OpenCL) {
11578     QualType Ty = InputExpr->getType();
11579     // The only legal unary operation for atomics is '&'.
11580     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11581     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11582     // only with a builtin functions and therefore should be disallowed here.
11583         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11584         || Ty->isBlockPointerType())) {
11585       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11586                        << InputExpr->getType()
11587                        << Input.get()->getSourceRange());
11588     }
11589   }
11590   switch (Opc) {
11591   case UO_PreInc:
11592   case UO_PreDec:
11593   case UO_PostInc:
11594   case UO_PostDec:
11595     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11596                                                 OpLoc,
11597                                                 Opc == UO_PreInc ||
11598                                                 Opc == UO_PostInc,
11599                                                 Opc == UO_PreInc ||
11600                                                 Opc == UO_PreDec);
11601     break;
11602   case UO_AddrOf:
11603     resultType = CheckAddressOfOperand(Input, OpLoc);
11604     RecordModifiableNonNullParam(*this, InputExpr);
11605     break;
11606   case UO_Deref: {
11607     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11608     if (Input.isInvalid()) return ExprError();
11609     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11610     break;
11611   }
11612   case UO_Plus:
11613   case UO_Minus:
11614     Input = UsualUnaryConversions(Input.get());
11615     if (Input.isInvalid()) return ExprError();
11616     resultType = Input.get()->getType();
11617     if (resultType->isDependentType())
11618       break;
11619     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11620       break;
11621     else if (resultType->isVectorType() &&
11622              // The z vector extensions don't allow + or - with bool vectors.
11623              (!Context.getLangOpts().ZVector ||
11624               resultType->getAs<VectorType>()->getVectorKind() !=
11625               VectorType::AltiVecBool))
11626       break;
11627     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11628              Opc == UO_Plus &&
11629              resultType->isPointerType())
11630       break;
11631 
11632     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11633       << resultType << Input.get()->getSourceRange());
11634 
11635   case UO_Not: // bitwise complement
11636     Input = UsualUnaryConversions(Input.get());
11637     if (Input.isInvalid())
11638       return ExprError();
11639     resultType = Input.get()->getType();
11640     if (resultType->isDependentType())
11641       break;
11642     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11643     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11644       // C99 does not support '~' for complex conjugation.
11645       Diag(OpLoc, diag::ext_integer_complement_complex)
11646           << resultType << Input.get()->getSourceRange();
11647     else if (resultType->hasIntegerRepresentation())
11648       break;
11649     else if (resultType->isExtVectorType()) {
11650       if (Context.getLangOpts().OpenCL) {
11651         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11652         // on vector float types.
11653         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11654         if (!T->isIntegerType())
11655           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11656                            << resultType << Input.get()->getSourceRange());
11657       }
11658       break;
11659     } else {
11660       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11661                        << resultType << Input.get()->getSourceRange());
11662     }
11663     break;
11664 
11665   case UO_LNot: // logical negation
11666     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11667     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11668     if (Input.isInvalid()) return ExprError();
11669     resultType = Input.get()->getType();
11670 
11671     // Though we still have to promote half FP to float...
11672     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11673       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11674       resultType = Context.FloatTy;
11675     }
11676 
11677     if (resultType->isDependentType())
11678       break;
11679     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11680       // C99 6.5.3.3p1: ok, fallthrough;
11681       if (Context.getLangOpts().CPlusPlus) {
11682         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11683         // operand contextually converted to bool.
11684         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11685                                   ScalarTypeToBooleanCastKind(resultType));
11686       } else if (Context.getLangOpts().OpenCL &&
11687                  Context.getLangOpts().OpenCLVersion < 120) {
11688         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11689         // operate on scalar float types.
11690         if (!resultType->isIntegerType() && !resultType->isPointerType())
11691           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11692                            << resultType << Input.get()->getSourceRange());
11693       }
11694     } else if (resultType->isExtVectorType()) {
11695       if (Context.getLangOpts().OpenCL &&
11696           Context.getLangOpts().OpenCLVersion < 120) {
11697         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11698         // operate on vector float types.
11699         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11700         if (!T->isIntegerType())
11701           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11702                            << resultType << Input.get()->getSourceRange());
11703       }
11704       // Vector logical not returns the signed variant of the operand type.
11705       resultType = GetSignedVectorType(resultType);
11706       break;
11707     } else {
11708       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11709         << resultType << Input.get()->getSourceRange());
11710     }
11711 
11712     // LNot always has type int. C99 6.5.3.3p5.
11713     // In C++, it's bool. C++ 5.3.1p8
11714     resultType = Context.getLogicalOperationType();
11715     break;
11716   case UO_Real:
11717   case UO_Imag:
11718     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11719     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11720     // complex l-values to ordinary l-values and all other values to r-values.
11721     if (Input.isInvalid()) return ExprError();
11722     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11723       if (Input.get()->getValueKind() != VK_RValue &&
11724           Input.get()->getObjectKind() == OK_Ordinary)
11725         VK = Input.get()->getValueKind();
11726     } else if (!getLangOpts().CPlusPlus) {
11727       // In C, a volatile scalar is read by __imag. In C++, it is not.
11728       Input = DefaultLvalueConversion(Input.get());
11729     }
11730     break;
11731   case UO_Extension:
11732   case UO_Coawait:
11733     resultType = Input.get()->getType();
11734     VK = Input.get()->getValueKind();
11735     OK = Input.get()->getObjectKind();
11736     break;
11737   }
11738   if (resultType.isNull() || Input.isInvalid())
11739     return ExprError();
11740 
11741   // Check for array bounds violations in the operand of the UnaryOperator,
11742   // except for the '*' and '&' operators that have to be handled specially
11743   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11744   // that are explicitly defined as valid by the standard).
11745   if (Opc != UO_AddrOf && Opc != UO_Deref)
11746     CheckArrayAccess(Input.get());
11747 
11748   return new (Context)
11749       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11750 }
11751 
11752 /// \brief Determine whether the given expression is a qualified member
11753 /// access expression, of a form that could be turned into a pointer to member
11754 /// with the address-of operator.
11755 static bool isQualifiedMemberAccess(Expr *E) {
11756   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11757     if (!DRE->getQualifier())
11758       return false;
11759 
11760     ValueDecl *VD = DRE->getDecl();
11761     if (!VD->isCXXClassMember())
11762       return false;
11763 
11764     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11765       return true;
11766     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11767       return Method->isInstance();
11768 
11769     return false;
11770   }
11771 
11772   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11773     if (!ULE->getQualifier())
11774       return false;
11775 
11776     for (NamedDecl *D : ULE->decls()) {
11777       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11778         if (Method->isInstance())
11779           return true;
11780       } else {
11781         // Overload set does not contain methods.
11782         break;
11783       }
11784     }
11785 
11786     return false;
11787   }
11788 
11789   return false;
11790 }
11791 
11792 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11793                               UnaryOperatorKind Opc, Expr *Input) {
11794   // First things first: handle placeholders so that the
11795   // overloaded-operator check considers the right type.
11796   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11797     // Increment and decrement of pseudo-object references.
11798     if (pty->getKind() == BuiltinType::PseudoObject &&
11799         UnaryOperator::isIncrementDecrementOp(Opc))
11800       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11801 
11802     // extension is always a builtin operator.
11803     if (Opc == UO_Extension)
11804       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11805 
11806     // & gets special logic for several kinds of placeholder.
11807     // The builtin code knows what to do.
11808     if (Opc == UO_AddrOf &&
11809         (pty->getKind() == BuiltinType::Overload ||
11810          pty->getKind() == BuiltinType::UnknownAny ||
11811          pty->getKind() == BuiltinType::BoundMember))
11812       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11813 
11814     // Anything else needs to be handled now.
11815     ExprResult Result = CheckPlaceholderExpr(Input);
11816     if (Result.isInvalid()) return ExprError();
11817     Input = Result.get();
11818   }
11819 
11820   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11821       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11822       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11823     // Find all of the overloaded operators visible from this
11824     // point. We perform both an operator-name lookup from the local
11825     // scope and an argument-dependent lookup based on the types of
11826     // the arguments.
11827     UnresolvedSet<16> Functions;
11828     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11829     if (S && OverOp != OO_None)
11830       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11831                                    Functions);
11832 
11833     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11834   }
11835 
11836   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11837 }
11838 
11839 // Unary Operators.  'Tok' is the token for the operator.
11840 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11841                               tok::TokenKind Op, Expr *Input) {
11842   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11843 }
11844 
11845 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11846 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11847                                 LabelDecl *TheDecl) {
11848   TheDecl->markUsed(Context);
11849   // Create the AST node.  The address of a label always has type 'void*'.
11850   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11851                                      Context.getPointerType(Context.VoidTy));
11852 }
11853 
11854 /// Given the last statement in a statement-expression, check whether
11855 /// the result is a producing expression (like a call to an
11856 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11857 /// release out of the full-expression.  Otherwise, return null.
11858 /// Cannot fail.
11859 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11860   // Should always be wrapped with one of these.
11861   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11862   if (!cleanups) return nullptr;
11863 
11864   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11865   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11866     return nullptr;
11867 
11868   // Splice out the cast.  This shouldn't modify any interesting
11869   // features of the statement.
11870   Expr *producer = cast->getSubExpr();
11871   assert(producer->getType() == cast->getType());
11872   assert(producer->getValueKind() == cast->getValueKind());
11873   cleanups->setSubExpr(producer);
11874   return cleanups;
11875 }
11876 
11877 void Sema::ActOnStartStmtExpr() {
11878   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11879 }
11880 
11881 void Sema::ActOnStmtExprError() {
11882   // Note that function is also called by TreeTransform when leaving a
11883   // StmtExpr scope without rebuilding anything.
11884 
11885   DiscardCleanupsInEvaluationContext();
11886   PopExpressionEvaluationContext();
11887 }
11888 
11889 ExprResult
11890 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11891                     SourceLocation RPLoc) { // "({..})"
11892   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11893   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11894 
11895   if (hasAnyUnrecoverableErrorsInThisFunction())
11896     DiscardCleanupsInEvaluationContext();
11897   assert(!Cleanup.exprNeedsCleanups() &&
11898          "cleanups within StmtExpr not correctly bound!");
11899   PopExpressionEvaluationContext();
11900 
11901   // FIXME: there are a variety of strange constraints to enforce here, for
11902   // example, it is not possible to goto into a stmt expression apparently.
11903   // More semantic analysis is needed.
11904 
11905   // If there are sub-stmts in the compound stmt, take the type of the last one
11906   // as the type of the stmtexpr.
11907   QualType Ty = Context.VoidTy;
11908   bool StmtExprMayBindToTemp = false;
11909   if (!Compound->body_empty()) {
11910     Stmt *LastStmt = Compound->body_back();
11911     LabelStmt *LastLabelStmt = nullptr;
11912     // If LastStmt is a label, skip down through into the body.
11913     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11914       LastLabelStmt = Label;
11915       LastStmt = Label->getSubStmt();
11916     }
11917 
11918     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11919       // Do function/array conversion on the last expression, but not
11920       // lvalue-to-rvalue.  However, initialize an unqualified type.
11921       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11922       if (LastExpr.isInvalid())
11923         return ExprError();
11924       Ty = LastExpr.get()->getType().getUnqualifiedType();
11925 
11926       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11927         // In ARC, if the final expression ends in a consume, splice
11928         // the consume out and bind it later.  In the alternate case
11929         // (when dealing with a retainable type), the result
11930         // initialization will create a produce.  In both cases the
11931         // result will be +1, and we'll need to balance that out with
11932         // a bind.
11933         if (Expr *rebuiltLastStmt
11934               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11935           LastExpr = rebuiltLastStmt;
11936         } else {
11937           LastExpr = PerformCopyInitialization(
11938                             InitializedEntity::InitializeResult(LPLoc,
11939                                                                 Ty,
11940                                                                 false),
11941                                                    SourceLocation(),
11942                                                LastExpr);
11943         }
11944 
11945         if (LastExpr.isInvalid())
11946           return ExprError();
11947         if (LastExpr.get() != nullptr) {
11948           if (!LastLabelStmt)
11949             Compound->setLastStmt(LastExpr.get());
11950           else
11951             LastLabelStmt->setSubStmt(LastExpr.get());
11952           StmtExprMayBindToTemp = true;
11953         }
11954       }
11955     }
11956   }
11957 
11958   // FIXME: Check that expression type is complete/non-abstract; statement
11959   // expressions are not lvalues.
11960   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11961   if (StmtExprMayBindToTemp)
11962     return MaybeBindToTemporary(ResStmtExpr);
11963   return ResStmtExpr;
11964 }
11965 
11966 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11967                                       TypeSourceInfo *TInfo,
11968                                       ArrayRef<OffsetOfComponent> Components,
11969                                       SourceLocation RParenLoc) {
11970   QualType ArgTy = TInfo->getType();
11971   bool Dependent = ArgTy->isDependentType();
11972   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11973 
11974   // We must have at least one component that refers to the type, and the first
11975   // one is known to be a field designator.  Verify that the ArgTy represents
11976   // a struct/union/class.
11977   if (!Dependent && !ArgTy->isRecordType())
11978     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11979                        << ArgTy << TypeRange);
11980 
11981   // Type must be complete per C99 7.17p3 because a declaring a variable
11982   // with an incomplete type would be ill-formed.
11983   if (!Dependent
11984       && RequireCompleteType(BuiltinLoc, ArgTy,
11985                              diag::err_offsetof_incomplete_type, TypeRange))
11986     return ExprError();
11987 
11988   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11989   // GCC extension, diagnose them.
11990   // FIXME: This diagnostic isn't actually visible because the location is in
11991   // a system header!
11992   if (Components.size() != 1)
11993     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11994       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11995 
11996   bool DidWarnAboutNonPOD = false;
11997   QualType CurrentType = ArgTy;
11998   SmallVector<OffsetOfNode, 4> Comps;
11999   SmallVector<Expr*, 4> Exprs;
12000   for (const OffsetOfComponent &OC : Components) {
12001     if (OC.isBrackets) {
12002       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12003       if (!CurrentType->isDependentType()) {
12004         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12005         if(!AT)
12006           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12007                            << CurrentType);
12008         CurrentType = AT->getElementType();
12009       } else
12010         CurrentType = Context.DependentTy;
12011 
12012       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12013       if (IdxRval.isInvalid())
12014         return ExprError();
12015       Expr *Idx = IdxRval.get();
12016 
12017       // The expression must be an integral expression.
12018       // FIXME: An integral constant expression?
12019       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12020           !Idx->getType()->isIntegerType())
12021         return ExprError(Diag(Idx->getLocStart(),
12022                               diag::err_typecheck_subscript_not_integer)
12023                          << Idx->getSourceRange());
12024 
12025       // Record this array index.
12026       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12027       Exprs.push_back(Idx);
12028       continue;
12029     }
12030 
12031     // Offset of a field.
12032     if (CurrentType->isDependentType()) {
12033       // We have the offset of a field, but we can't look into the dependent
12034       // type. Just record the identifier of the field.
12035       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12036       CurrentType = Context.DependentTy;
12037       continue;
12038     }
12039 
12040     // We need to have a complete type to look into.
12041     if (RequireCompleteType(OC.LocStart, CurrentType,
12042                             diag::err_offsetof_incomplete_type))
12043       return ExprError();
12044 
12045     // Look for the designated field.
12046     const RecordType *RC = CurrentType->getAs<RecordType>();
12047     if (!RC)
12048       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12049                        << CurrentType);
12050     RecordDecl *RD = RC->getDecl();
12051 
12052     // C++ [lib.support.types]p5:
12053     //   The macro offsetof accepts a restricted set of type arguments in this
12054     //   International Standard. type shall be a POD structure or a POD union
12055     //   (clause 9).
12056     // C++11 [support.types]p4:
12057     //   If type is not a standard-layout class (Clause 9), the results are
12058     //   undefined.
12059     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12060       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12061       unsigned DiagID =
12062         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12063                             : diag::ext_offsetof_non_pod_type;
12064 
12065       if (!IsSafe && !DidWarnAboutNonPOD &&
12066           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12067                               PDiag(DiagID)
12068                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12069                               << CurrentType))
12070         DidWarnAboutNonPOD = true;
12071     }
12072 
12073     // Look for the field.
12074     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12075     LookupQualifiedName(R, RD);
12076     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12077     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12078     if (!MemberDecl) {
12079       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12080         MemberDecl = IndirectMemberDecl->getAnonField();
12081     }
12082 
12083     if (!MemberDecl)
12084       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12085                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12086                                                               OC.LocEnd));
12087 
12088     // C99 7.17p3:
12089     //   (If the specified member is a bit-field, the behavior is undefined.)
12090     //
12091     // We diagnose this as an error.
12092     if (MemberDecl->isBitField()) {
12093       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12094         << MemberDecl->getDeclName()
12095         << SourceRange(BuiltinLoc, RParenLoc);
12096       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12097       return ExprError();
12098     }
12099 
12100     RecordDecl *Parent = MemberDecl->getParent();
12101     if (IndirectMemberDecl)
12102       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12103 
12104     // If the member was found in a base class, introduce OffsetOfNodes for
12105     // the base class indirections.
12106     CXXBasePaths Paths;
12107     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12108                       Paths)) {
12109       if (Paths.getDetectedVirtual()) {
12110         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12111           << MemberDecl->getDeclName()
12112           << SourceRange(BuiltinLoc, RParenLoc);
12113         return ExprError();
12114       }
12115 
12116       CXXBasePath &Path = Paths.front();
12117       for (const CXXBasePathElement &B : Path)
12118         Comps.push_back(OffsetOfNode(B.Base));
12119     }
12120 
12121     if (IndirectMemberDecl) {
12122       for (auto *FI : IndirectMemberDecl->chain()) {
12123         assert(isa<FieldDecl>(FI));
12124         Comps.push_back(OffsetOfNode(OC.LocStart,
12125                                      cast<FieldDecl>(FI), OC.LocEnd));
12126       }
12127     } else
12128       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12129 
12130     CurrentType = MemberDecl->getType().getNonReferenceType();
12131   }
12132 
12133   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12134                               Comps, Exprs, RParenLoc);
12135 }
12136 
12137 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12138                                       SourceLocation BuiltinLoc,
12139                                       SourceLocation TypeLoc,
12140                                       ParsedType ParsedArgTy,
12141                                       ArrayRef<OffsetOfComponent> Components,
12142                                       SourceLocation RParenLoc) {
12143 
12144   TypeSourceInfo *ArgTInfo;
12145   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12146   if (ArgTy.isNull())
12147     return ExprError();
12148 
12149   if (!ArgTInfo)
12150     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12151 
12152   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12153 }
12154 
12155 
12156 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12157                                  Expr *CondExpr,
12158                                  Expr *LHSExpr, Expr *RHSExpr,
12159                                  SourceLocation RPLoc) {
12160   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12161 
12162   ExprValueKind VK = VK_RValue;
12163   ExprObjectKind OK = OK_Ordinary;
12164   QualType resType;
12165   bool ValueDependent = false;
12166   bool CondIsTrue = false;
12167   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12168     resType = Context.DependentTy;
12169     ValueDependent = true;
12170   } else {
12171     // The conditional expression is required to be a constant expression.
12172     llvm::APSInt condEval(32);
12173     ExprResult CondICE
12174       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12175           diag::err_typecheck_choose_expr_requires_constant, false);
12176     if (CondICE.isInvalid())
12177       return ExprError();
12178     CondExpr = CondICE.get();
12179     CondIsTrue = condEval.getZExtValue();
12180 
12181     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12182     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12183 
12184     resType = ActiveExpr->getType();
12185     ValueDependent = ActiveExpr->isValueDependent();
12186     VK = ActiveExpr->getValueKind();
12187     OK = ActiveExpr->getObjectKind();
12188   }
12189 
12190   return new (Context)
12191       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12192                  CondIsTrue, resType->isDependentType(), ValueDependent);
12193 }
12194 
12195 //===----------------------------------------------------------------------===//
12196 // Clang Extensions.
12197 //===----------------------------------------------------------------------===//
12198 
12199 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12200 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12201   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12202 
12203   if (LangOpts.CPlusPlus) {
12204     Decl *ManglingContextDecl;
12205     if (MangleNumberingContext *MCtx =
12206             getCurrentMangleNumberContext(Block->getDeclContext(),
12207                                           ManglingContextDecl)) {
12208       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12209       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12210     }
12211   }
12212 
12213   PushBlockScope(CurScope, Block);
12214   CurContext->addDecl(Block);
12215   if (CurScope)
12216     PushDeclContext(CurScope, Block);
12217   else
12218     CurContext = Block;
12219 
12220   getCurBlock()->HasImplicitReturnType = true;
12221 
12222   // Enter a new evaluation context to insulate the block from any
12223   // cleanups from the enclosing full-expression.
12224   PushExpressionEvaluationContext(PotentiallyEvaluated);
12225 }
12226 
12227 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12228                                Scope *CurScope) {
12229   assert(ParamInfo.getIdentifier() == nullptr &&
12230          "block-id should have no identifier!");
12231   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12232   BlockScopeInfo *CurBlock = getCurBlock();
12233 
12234   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12235   QualType T = Sig->getType();
12236 
12237   // FIXME: We should allow unexpanded parameter packs here, but that would,
12238   // in turn, make the block expression contain unexpanded parameter packs.
12239   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12240     // Drop the parameters.
12241     FunctionProtoType::ExtProtoInfo EPI;
12242     EPI.HasTrailingReturn = false;
12243     EPI.TypeQuals |= DeclSpec::TQ_const;
12244     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12245     Sig = Context.getTrivialTypeSourceInfo(T);
12246   }
12247 
12248   // GetTypeForDeclarator always produces a function type for a block
12249   // literal signature.  Furthermore, it is always a FunctionProtoType
12250   // unless the function was written with a typedef.
12251   assert(T->isFunctionType() &&
12252          "GetTypeForDeclarator made a non-function block signature");
12253 
12254   // Look for an explicit signature in that function type.
12255   FunctionProtoTypeLoc ExplicitSignature;
12256 
12257   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12258   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12259 
12260     // Check whether that explicit signature was synthesized by
12261     // GetTypeForDeclarator.  If so, don't save that as part of the
12262     // written signature.
12263     if (ExplicitSignature.getLocalRangeBegin() ==
12264         ExplicitSignature.getLocalRangeEnd()) {
12265       // This would be much cheaper if we stored TypeLocs instead of
12266       // TypeSourceInfos.
12267       TypeLoc Result = ExplicitSignature.getReturnLoc();
12268       unsigned Size = Result.getFullDataSize();
12269       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12270       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12271 
12272       ExplicitSignature = FunctionProtoTypeLoc();
12273     }
12274   }
12275 
12276   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12277   CurBlock->FunctionType = T;
12278 
12279   const FunctionType *Fn = T->getAs<FunctionType>();
12280   QualType RetTy = Fn->getReturnType();
12281   bool isVariadic =
12282     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12283 
12284   CurBlock->TheDecl->setIsVariadic(isVariadic);
12285 
12286   // Context.DependentTy is used as a placeholder for a missing block
12287   // return type.  TODO:  what should we do with declarators like:
12288   //   ^ * { ... }
12289   // If the answer is "apply template argument deduction"....
12290   if (RetTy != Context.DependentTy) {
12291     CurBlock->ReturnType = RetTy;
12292     CurBlock->TheDecl->setBlockMissingReturnType(false);
12293     CurBlock->HasImplicitReturnType = false;
12294   }
12295 
12296   // Push block parameters from the declarator if we had them.
12297   SmallVector<ParmVarDecl*, 8> Params;
12298   if (ExplicitSignature) {
12299     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12300       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12301       if (Param->getIdentifier() == nullptr &&
12302           !Param->isImplicit() &&
12303           !Param->isInvalidDecl() &&
12304           !getLangOpts().CPlusPlus)
12305         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12306       Params.push_back(Param);
12307     }
12308 
12309   // Fake up parameter variables if we have a typedef, like
12310   //   ^ fntype { ... }
12311   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12312     for (const auto &I : Fn->param_types()) {
12313       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12314           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12315       Params.push_back(Param);
12316     }
12317   }
12318 
12319   // Set the parameters on the block decl.
12320   if (!Params.empty()) {
12321     CurBlock->TheDecl->setParams(Params);
12322     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12323                              /*CheckParameterNames=*/false);
12324   }
12325 
12326   // Finally we can process decl attributes.
12327   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12328 
12329   // Put the parameter variables in scope.
12330   for (auto AI : CurBlock->TheDecl->parameters()) {
12331     AI->setOwningFunction(CurBlock->TheDecl);
12332 
12333     // If this has an identifier, add it to the scope stack.
12334     if (AI->getIdentifier()) {
12335       CheckShadow(CurBlock->TheScope, AI);
12336 
12337       PushOnScopeChains(AI, CurBlock->TheScope);
12338     }
12339   }
12340 }
12341 
12342 /// ActOnBlockError - If there is an error parsing a block, this callback
12343 /// is invoked to pop the information about the block from the action impl.
12344 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12345   // Leave the expression-evaluation context.
12346   DiscardCleanupsInEvaluationContext();
12347   PopExpressionEvaluationContext();
12348 
12349   // Pop off CurBlock, handle nested blocks.
12350   PopDeclContext();
12351   PopFunctionScopeInfo();
12352 }
12353 
12354 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12355 /// literal was successfully completed.  ^(int x){...}
12356 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12357                                     Stmt *Body, Scope *CurScope) {
12358   // If blocks are disabled, emit an error.
12359   if (!LangOpts.Blocks)
12360     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12361 
12362   // Leave the expression-evaluation context.
12363   if (hasAnyUnrecoverableErrorsInThisFunction())
12364     DiscardCleanupsInEvaluationContext();
12365   assert(!Cleanup.exprNeedsCleanups() &&
12366          "cleanups within block not correctly bound!");
12367   PopExpressionEvaluationContext();
12368 
12369   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12370 
12371   if (BSI->HasImplicitReturnType)
12372     deduceClosureReturnType(*BSI);
12373 
12374   PopDeclContext();
12375 
12376   QualType RetTy = Context.VoidTy;
12377   if (!BSI->ReturnType.isNull())
12378     RetTy = BSI->ReturnType;
12379 
12380   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12381   QualType BlockTy;
12382 
12383   // Set the captured variables on the block.
12384   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12385   SmallVector<BlockDecl::Capture, 4> Captures;
12386   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12387     if (Cap.isThisCapture())
12388       continue;
12389     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12390                               Cap.isNested(), Cap.getInitExpr());
12391     Captures.push_back(NewCap);
12392   }
12393   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12394 
12395   // If the user wrote a function type in some form, try to use that.
12396   if (!BSI->FunctionType.isNull()) {
12397     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12398 
12399     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12400     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12401 
12402     // Turn protoless block types into nullary block types.
12403     if (isa<FunctionNoProtoType>(FTy)) {
12404       FunctionProtoType::ExtProtoInfo EPI;
12405       EPI.ExtInfo = Ext;
12406       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12407 
12408     // Otherwise, if we don't need to change anything about the function type,
12409     // preserve its sugar structure.
12410     } else if (FTy->getReturnType() == RetTy &&
12411                (!NoReturn || FTy->getNoReturnAttr())) {
12412       BlockTy = BSI->FunctionType;
12413 
12414     // Otherwise, make the minimal modifications to the function type.
12415     } else {
12416       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12417       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12418       EPI.TypeQuals = 0; // FIXME: silently?
12419       EPI.ExtInfo = Ext;
12420       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12421     }
12422 
12423   // If we don't have a function type, just build one from nothing.
12424   } else {
12425     FunctionProtoType::ExtProtoInfo EPI;
12426     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12427     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12428   }
12429 
12430   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12431   BlockTy = Context.getBlockPointerType(BlockTy);
12432 
12433   // If needed, diagnose invalid gotos and switches in the block.
12434   if (getCurFunction()->NeedsScopeChecking() &&
12435       !PP.isCodeCompletionEnabled())
12436     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12437 
12438   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12439 
12440   // Try to apply the named return value optimization. We have to check again
12441   // if we can do this, though, because blocks keep return statements around
12442   // to deduce an implicit return type.
12443   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12444       !BSI->TheDecl->isDependentContext())
12445     computeNRVO(Body, BSI);
12446 
12447   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12448   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12449   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12450 
12451   // If the block isn't obviously global, i.e. it captures anything at
12452   // all, then we need to do a few things in the surrounding context:
12453   if (Result->getBlockDecl()->hasCaptures()) {
12454     // First, this expression has a new cleanup object.
12455     ExprCleanupObjects.push_back(Result->getBlockDecl());
12456     Cleanup.setExprNeedsCleanups(true);
12457 
12458     // It also gets a branch-protected scope if any of the captured
12459     // variables needs destruction.
12460     for (const auto &CI : Result->getBlockDecl()->captures()) {
12461       const VarDecl *var = CI.getVariable();
12462       if (var->getType().isDestructedType() != QualType::DK_none) {
12463         getCurFunction()->setHasBranchProtectedScope();
12464         break;
12465       }
12466     }
12467   }
12468 
12469   return Result;
12470 }
12471 
12472 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12473                             SourceLocation RPLoc) {
12474   TypeSourceInfo *TInfo;
12475   GetTypeFromParser(Ty, &TInfo);
12476   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12477 }
12478 
12479 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12480                                 Expr *E, TypeSourceInfo *TInfo,
12481                                 SourceLocation RPLoc) {
12482   Expr *OrigExpr = E;
12483   bool IsMS = false;
12484 
12485   // CUDA device code does not support varargs.
12486   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12487     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12488       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12489       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12490         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12491     }
12492   }
12493 
12494   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12495   // as Microsoft ABI on an actual Microsoft platform, where
12496   // __builtin_ms_va_list and __builtin_va_list are the same.)
12497   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12498       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12499     QualType MSVaListType = Context.getBuiltinMSVaListType();
12500     if (Context.hasSameType(MSVaListType, E->getType())) {
12501       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12502         return ExprError();
12503       IsMS = true;
12504     }
12505   }
12506 
12507   // Get the va_list type
12508   QualType VaListType = Context.getBuiltinVaListType();
12509   if (!IsMS) {
12510     if (VaListType->isArrayType()) {
12511       // Deal with implicit array decay; for example, on x86-64,
12512       // va_list is an array, but it's supposed to decay to
12513       // a pointer for va_arg.
12514       VaListType = Context.getArrayDecayedType(VaListType);
12515       // Make sure the input expression also decays appropriately.
12516       ExprResult Result = UsualUnaryConversions(E);
12517       if (Result.isInvalid())
12518         return ExprError();
12519       E = Result.get();
12520     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12521       // If va_list is a record type and we are compiling in C++ mode,
12522       // check the argument using reference binding.
12523       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12524           Context, Context.getLValueReferenceType(VaListType), false);
12525       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12526       if (Init.isInvalid())
12527         return ExprError();
12528       E = Init.getAs<Expr>();
12529     } else {
12530       // Otherwise, the va_list argument must be an l-value because
12531       // it is modified by va_arg.
12532       if (!E->isTypeDependent() &&
12533           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12534         return ExprError();
12535     }
12536   }
12537 
12538   if (!IsMS && !E->isTypeDependent() &&
12539       !Context.hasSameType(VaListType, E->getType()))
12540     return ExprError(Diag(E->getLocStart(),
12541                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12542       << OrigExpr->getType() << E->getSourceRange());
12543 
12544   if (!TInfo->getType()->isDependentType()) {
12545     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12546                             diag::err_second_parameter_to_va_arg_incomplete,
12547                             TInfo->getTypeLoc()))
12548       return ExprError();
12549 
12550     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12551                                TInfo->getType(),
12552                                diag::err_second_parameter_to_va_arg_abstract,
12553                                TInfo->getTypeLoc()))
12554       return ExprError();
12555 
12556     if (!TInfo->getType().isPODType(Context)) {
12557       Diag(TInfo->getTypeLoc().getBeginLoc(),
12558            TInfo->getType()->isObjCLifetimeType()
12559              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12560              : diag::warn_second_parameter_to_va_arg_not_pod)
12561         << TInfo->getType()
12562         << TInfo->getTypeLoc().getSourceRange();
12563     }
12564 
12565     // Check for va_arg where arguments of the given type will be promoted
12566     // (i.e. this va_arg is guaranteed to have undefined behavior).
12567     QualType PromoteType;
12568     if (TInfo->getType()->isPromotableIntegerType()) {
12569       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12570       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12571         PromoteType = QualType();
12572     }
12573     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12574       PromoteType = Context.DoubleTy;
12575     if (!PromoteType.isNull())
12576       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12577                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12578                           << TInfo->getType()
12579                           << PromoteType
12580                           << TInfo->getTypeLoc().getSourceRange());
12581   }
12582 
12583   QualType T = TInfo->getType().getNonLValueExprType(Context);
12584   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12585 }
12586 
12587 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12588   // The type of __null will be int or long, depending on the size of
12589   // pointers on the target.
12590   QualType Ty;
12591   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12592   if (pw == Context.getTargetInfo().getIntWidth())
12593     Ty = Context.IntTy;
12594   else if (pw == Context.getTargetInfo().getLongWidth())
12595     Ty = Context.LongTy;
12596   else if (pw == Context.getTargetInfo().getLongLongWidth())
12597     Ty = Context.LongLongTy;
12598   else {
12599     llvm_unreachable("I don't know size of pointer!");
12600   }
12601 
12602   return new (Context) GNUNullExpr(Ty, TokenLoc);
12603 }
12604 
12605 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12606                                               bool Diagnose) {
12607   if (!getLangOpts().ObjC1)
12608     return false;
12609 
12610   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12611   if (!PT)
12612     return false;
12613 
12614   if (!PT->isObjCIdType()) {
12615     // Check if the destination is the 'NSString' interface.
12616     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12617     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12618       return false;
12619   }
12620 
12621   // Ignore any parens, implicit casts (should only be
12622   // array-to-pointer decays), and not-so-opaque values.  The last is
12623   // important for making this trigger for property assignments.
12624   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12625   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12626     if (OV->getSourceExpr())
12627       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12628 
12629   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12630   if (!SL || !SL->isAscii())
12631     return false;
12632   if (Diagnose) {
12633     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12634       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12635     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12636   }
12637   return true;
12638 }
12639 
12640 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12641                                               const Expr *SrcExpr) {
12642   if (!DstType->isFunctionPointerType() ||
12643       !SrcExpr->getType()->isFunctionType())
12644     return false;
12645 
12646   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12647   if (!DRE)
12648     return false;
12649 
12650   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12651   if (!FD)
12652     return false;
12653 
12654   return !S.checkAddressOfFunctionIsAvailable(FD,
12655                                               /*Complain=*/true,
12656                                               SrcExpr->getLocStart());
12657 }
12658 
12659 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12660                                     SourceLocation Loc,
12661                                     QualType DstType, QualType SrcType,
12662                                     Expr *SrcExpr, AssignmentAction Action,
12663                                     bool *Complained) {
12664   if (Complained)
12665     *Complained = false;
12666 
12667   // Decode the result (notice that AST's are still created for extensions).
12668   bool CheckInferredResultType = false;
12669   bool isInvalid = false;
12670   unsigned DiagKind = 0;
12671   FixItHint Hint;
12672   ConversionFixItGenerator ConvHints;
12673   bool MayHaveConvFixit = false;
12674   bool MayHaveFunctionDiff = false;
12675   const ObjCInterfaceDecl *IFace = nullptr;
12676   const ObjCProtocolDecl *PDecl = nullptr;
12677 
12678   switch (ConvTy) {
12679   case Compatible:
12680       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12681       return false;
12682 
12683   case PointerToInt:
12684     DiagKind = diag::ext_typecheck_convert_pointer_int;
12685     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12686     MayHaveConvFixit = true;
12687     break;
12688   case IntToPointer:
12689     DiagKind = diag::ext_typecheck_convert_int_pointer;
12690     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12691     MayHaveConvFixit = true;
12692     break;
12693   case IncompatiblePointer:
12694     if (Action == AA_Passing_CFAudited)
12695       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12696     else if (SrcType->isFunctionPointerType() &&
12697              DstType->isFunctionPointerType())
12698       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12699     else
12700       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12701 
12702     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12703       SrcType->isObjCObjectPointerType();
12704     if (Hint.isNull() && !CheckInferredResultType) {
12705       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12706     }
12707     else if (CheckInferredResultType) {
12708       SrcType = SrcType.getUnqualifiedType();
12709       DstType = DstType.getUnqualifiedType();
12710     }
12711     MayHaveConvFixit = true;
12712     break;
12713   case IncompatiblePointerSign:
12714     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12715     break;
12716   case FunctionVoidPointer:
12717     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12718     break;
12719   case IncompatiblePointerDiscardsQualifiers: {
12720     // Perform array-to-pointer decay if necessary.
12721     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12722 
12723     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12724     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12725     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12726       DiagKind = diag::err_typecheck_incompatible_address_space;
12727       break;
12728 
12729 
12730     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12731       DiagKind = diag::err_typecheck_incompatible_ownership;
12732       break;
12733     }
12734 
12735     llvm_unreachable("unknown error case for discarding qualifiers!");
12736     // fallthrough
12737   }
12738   case CompatiblePointerDiscardsQualifiers:
12739     // If the qualifiers lost were because we were applying the
12740     // (deprecated) C++ conversion from a string literal to a char*
12741     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12742     // Ideally, this check would be performed in
12743     // checkPointerTypesForAssignment. However, that would require a
12744     // bit of refactoring (so that the second argument is an
12745     // expression, rather than a type), which should be done as part
12746     // of a larger effort to fix checkPointerTypesForAssignment for
12747     // C++ semantics.
12748     if (getLangOpts().CPlusPlus &&
12749         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12750       return false;
12751     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12752     break;
12753   case IncompatibleNestedPointerQualifiers:
12754     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12755     break;
12756   case IntToBlockPointer:
12757     DiagKind = diag::err_int_to_block_pointer;
12758     break;
12759   case IncompatibleBlockPointer:
12760     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12761     break;
12762   case IncompatibleObjCQualifiedId: {
12763     if (SrcType->isObjCQualifiedIdType()) {
12764       const ObjCObjectPointerType *srcOPT =
12765                 SrcType->getAs<ObjCObjectPointerType>();
12766       for (auto *srcProto : srcOPT->quals()) {
12767         PDecl = srcProto;
12768         break;
12769       }
12770       if (const ObjCInterfaceType *IFaceT =
12771             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12772         IFace = IFaceT->getDecl();
12773     }
12774     else if (DstType->isObjCQualifiedIdType()) {
12775       const ObjCObjectPointerType *dstOPT =
12776         DstType->getAs<ObjCObjectPointerType>();
12777       for (auto *dstProto : dstOPT->quals()) {
12778         PDecl = dstProto;
12779         break;
12780       }
12781       if (const ObjCInterfaceType *IFaceT =
12782             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12783         IFace = IFaceT->getDecl();
12784     }
12785     DiagKind = diag::warn_incompatible_qualified_id;
12786     break;
12787   }
12788   case IncompatibleVectors:
12789     DiagKind = diag::warn_incompatible_vectors;
12790     break;
12791   case IncompatibleObjCWeakRef:
12792     DiagKind = diag::err_arc_weak_unavailable_assign;
12793     break;
12794   case Incompatible:
12795     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12796       if (Complained)
12797         *Complained = true;
12798       return true;
12799     }
12800 
12801     DiagKind = diag::err_typecheck_convert_incompatible;
12802     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12803     MayHaveConvFixit = true;
12804     isInvalid = true;
12805     MayHaveFunctionDiff = true;
12806     break;
12807   }
12808 
12809   QualType FirstType, SecondType;
12810   switch (Action) {
12811   case AA_Assigning:
12812   case AA_Initializing:
12813     // The destination type comes first.
12814     FirstType = DstType;
12815     SecondType = SrcType;
12816     break;
12817 
12818   case AA_Returning:
12819   case AA_Passing:
12820   case AA_Passing_CFAudited:
12821   case AA_Converting:
12822   case AA_Sending:
12823   case AA_Casting:
12824     // The source type comes first.
12825     FirstType = SrcType;
12826     SecondType = DstType;
12827     break;
12828   }
12829 
12830   PartialDiagnostic FDiag = PDiag(DiagKind);
12831   if (Action == AA_Passing_CFAudited)
12832     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12833   else
12834     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12835 
12836   // If we can fix the conversion, suggest the FixIts.
12837   assert(ConvHints.isNull() || Hint.isNull());
12838   if (!ConvHints.isNull()) {
12839     for (FixItHint &H : ConvHints.Hints)
12840       FDiag << H;
12841   } else {
12842     FDiag << Hint;
12843   }
12844   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12845 
12846   if (MayHaveFunctionDiff)
12847     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12848 
12849   Diag(Loc, FDiag);
12850   if (DiagKind == diag::warn_incompatible_qualified_id &&
12851       PDecl && IFace && !IFace->hasDefinition())
12852       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12853         << IFace->getName() << PDecl->getName();
12854 
12855   if (SecondType == Context.OverloadTy)
12856     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12857                               FirstType, /*TakingAddress=*/true);
12858 
12859   if (CheckInferredResultType)
12860     EmitRelatedResultTypeNote(SrcExpr);
12861 
12862   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12863     EmitRelatedResultTypeNoteForReturn(DstType);
12864 
12865   if (Complained)
12866     *Complained = true;
12867   return isInvalid;
12868 }
12869 
12870 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12871                                                  llvm::APSInt *Result) {
12872   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12873   public:
12874     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12875       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12876     }
12877   } Diagnoser;
12878 
12879   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12880 }
12881 
12882 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12883                                                  llvm::APSInt *Result,
12884                                                  unsigned DiagID,
12885                                                  bool AllowFold) {
12886   class IDDiagnoser : public VerifyICEDiagnoser {
12887     unsigned DiagID;
12888 
12889   public:
12890     IDDiagnoser(unsigned DiagID)
12891       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12892 
12893     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12894       S.Diag(Loc, DiagID) << SR;
12895     }
12896   } Diagnoser(DiagID);
12897 
12898   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12899 }
12900 
12901 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12902                                             SourceRange SR) {
12903   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12904 }
12905 
12906 ExprResult
12907 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12908                                       VerifyICEDiagnoser &Diagnoser,
12909                                       bool AllowFold) {
12910   SourceLocation DiagLoc = E->getLocStart();
12911 
12912   if (getLangOpts().CPlusPlus11) {
12913     // C++11 [expr.const]p5:
12914     //   If an expression of literal class type is used in a context where an
12915     //   integral constant expression is required, then that class type shall
12916     //   have a single non-explicit conversion function to an integral or
12917     //   unscoped enumeration type
12918     ExprResult Converted;
12919     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12920     public:
12921       CXX11ConvertDiagnoser(bool Silent)
12922           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12923                                 Silent, true) {}
12924 
12925       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12926                                            QualType T) override {
12927         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12928       }
12929 
12930       SemaDiagnosticBuilder diagnoseIncomplete(
12931           Sema &S, SourceLocation Loc, QualType T) override {
12932         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12933       }
12934 
12935       SemaDiagnosticBuilder diagnoseExplicitConv(
12936           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12937         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12938       }
12939 
12940       SemaDiagnosticBuilder noteExplicitConv(
12941           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12942         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12943                  << ConvTy->isEnumeralType() << ConvTy;
12944       }
12945 
12946       SemaDiagnosticBuilder diagnoseAmbiguous(
12947           Sema &S, SourceLocation Loc, QualType T) override {
12948         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12949       }
12950 
12951       SemaDiagnosticBuilder noteAmbiguous(
12952           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12953         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12954                  << ConvTy->isEnumeralType() << ConvTy;
12955       }
12956 
12957       SemaDiagnosticBuilder diagnoseConversion(
12958           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12959         llvm_unreachable("conversion functions are permitted");
12960       }
12961     } ConvertDiagnoser(Diagnoser.Suppress);
12962 
12963     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12964                                                     ConvertDiagnoser);
12965     if (Converted.isInvalid())
12966       return Converted;
12967     E = Converted.get();
12968     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12969       return ExprError();
12970   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12971     // An ICE must be of integral or unscoped enumeration type.
12972     if (!Diagnoser.Suppress)
12973       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12974     return ExprError();
12975   }
12976 
12977   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12978   // in the non-ICE case.
12979   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12980     if (Result)
12981       *Result = E->EvaluateKnownConstInt(Context);
12982     return E;
12983   }
12984 
12985   Expr::EvalResult EvalResult;
12986   SmallVector<PartialDiagnosticAt, 8> Notes;
12987   EvalResult.Diag = &Notes;
12988 
12989   // Try to evaluate the expression, and produce diagnostics explaining why it's
12990   // not a constant expression as a side-effect.
12991   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12992                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12993 
12994   // In C++11, we can rely on diagnostics being produced for any expression
12995   // which is not a constant expression. If no diagnostics were produced, then
12996   // this is a constant expression.
12997   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12998     if (Result)
12999       *Result = EvalResult.Val.getInt();
13000     return E;
13001   }
13002 
13003   // If our only note is the usual "invalid subexpression" note, just point
13004   // the caret at its location rather than producing an essentially
13005   // redundant note.
13006   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13007         diag::note_invalid_subexpr_in_const_expr) {
13008     DiagLoc = Notes[0].first;
13009     Notes.clear();
13010   }
13011 
13012   if (!Folded || !AllowFold) {
13013     if (!Diagnoser.Suppress) {
13014       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13015       for (const PartialDiagnosticAt &Note : Notes)
13016         Diag(Note.first, Note.second);
13017     }
13018 
13019     return ExprError();
13020   }
13021 
13022   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13023   for (const PartialDiagnosticAt &Note : Notes)
13024     Diag(Note.first, Note.second);
13025 
13026   if (Result)
13027     *Result = EvalResult.Val.getInt();
13028   return E;
13029 }
13030 
13031 namespace {
13032   // Handle the case where we conclude a expression which we speculatively
13033   // considered to be unevaluated is actually evaluated.
13034   class TransformToPE : public TreeTransform<TransformToPE> {
13035     typedef TreeTransform<TransformToPE> BaseTransform;
13036 
13037   public:
13038     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13039 
13040     // Make sure we redo semantic analysis
13041     bool AlwaysRebuild() { return true; }
13042 
13043     // Make sure we handle LabelStmts correctly.
13044     // FIXME: This does the right thing, but maybe we need a more general
13045     // fix to TreeTransform?
13046     StmtResult TransformLabelStmt(LabelStmt *S) {
13047       S->getDecl()->setStmt(nullptr);
13048       return BaseTransform::TransformLabelStmt(S);
13049     }
13050 
13051     // We need to special-case DeclRefExprs referring to FieldDecls which
13052     // are not part of a member pointer formation; normal TreeTransforming
13053     // doesn't catch this case because of the way we represent them in the AST.
13054     // FIXME: This is a bit ugly; is it really the best way to handle this
13055     // case?
13056     //
13057     // Error on DeclRefExprs referring to FieldDecls.
13058     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13059       if (isa<FieldDecl>(E->getDecl()) &&
13060           !SemaRef.isUnevaluatedContext())
13061         return SemaRef.Diag(E->getLocation(),
13062                             diag::err_invalid_non_static_member_use)
13063             << E->getDecl() << E->getSourceRange();
13064 
13065       return BaseTransform::TransformDeclRefExpr(E);
13066     }
13067 
13068     // Exception: filter out member pointer formation
13069     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13070       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13071         return E;
13072 
13073       return BaseTransform::TransformUnaryOperator(E);
13074     }
13075 
13076     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13077       // Lambdas never need to be transformed.
13078       return E;
13079     }
13080   };
13081 }
13082 
13083 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13084   assert(isUnevaluatedContext() &&
13085          "Should only transform unevaluated expressions");
13086   ExprEvalContexts.back().Context =
13087       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13088   if (isUnevaluatedContext())
13089     return E;
13090   return TransformToPE(*this).TransformExpr(E);
13091 }
13092 
13093 void
13094 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13095                                       Decl *LambdaContextDecl,
13096                                       bool IsDecltype) {
13097   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13098                                 LambdaContextDecl, IsDecltype);
13099   Cleanup.reset();
13100   if (!MaybeODRUseExprs.empty())
13101     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13102 }
13103 
13104 void
13105 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13106                                       ReuseLambdaContextDecl_t,
13107                                       bool IsDecltype) {
13108   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13109   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13110 }
13111 
13112 void Sema::PopExpressionEvaluationContext() {
13113   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13114   unsigned NumTypos = Rec.NumTypos;
13115 
13116   if (!Rec.Lambdas.empty()) {
13117     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13118       unsigned D;
13119       if (Rec.isUnevaluated()) {
13120         // C++11 [expr.prim.lambda]p2:
13121         //   A lambda-expression shall not appear in an unevaluated operand
13122         //   (Clause 5).
13123         D = diag::err_lambda_unevaluated_operand;
13124       } else {
13125         // C++1y [expr.const]p2:
13126         //   A conditional-expression e is a core constant expression unless the
13127         //   evaluation of e, following the rules of the abstract machine, would
13128         //   evaluate [...] a lambda-expression.
13129         D = diag::err_lambda_in_constant_expression;
13130       }
13131 
13132       // C++1z allows lambda expressions as core constant expressions.
13133       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13134       // 1607) from appearing within template-arguments and array-bounds that
13135       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13136       // unevaluated contexts) might lift some of these restrictions in a
13137       // future version.
13138       if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13139         for (const auto *L : Rec.Lambdas)
13140           Diag(L->getLocStart(), D);
13141     } else {
13142       // Mark the capture expressions odr-used. This was deferred
13143       // during lambda expression creation.
13144       for (auto *Lambda : Rec.Lambdas) {
13145         for (auto *C : Lambda->capture_inits())
13146           MarkDeclarationsReferencedInExpr(C);
13147       }
13148     }
13149   }
13150 
13151   // When are coming out of an unevaluated context, clear out any
13152   // temporaries that we may have created as part of the evaluation of
13153   // the expression in that context: they aren't relevant because they
13154   // will never be constructed.
13155   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13156     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13157                              ExprCleanupObjects.end());
13158     Cleanup = Rec.ParentCleanup;
13159     CleanupVarDeclMarking();
13160     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13161   // Otherwise, merge the contexts together.
13162   } else {
13163     Cleanup.mergeFrom(Rec.ParentCleanup);
13164     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13165                             Rec.SavedMaybeODRUseExprs.end());
13166   }
13167 
13168   // Pop the current expression evaluation context off the stack.
13169   ExprEvalContexts.pop_back();
13170 
13171   if (!ExprEvalContexts.empty())
13172     ExprEvalContexts.back().NumTypos += NumTypos;
13173   else
13174     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13175                             "last ExpressionEvaluationContextRecord");
13176 }
13177 
13178 void Sema::DiscardCleanupsInEvaluationContext() {
13179   ExprCleanupObjects.erase(
13180          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13181          ExprCleanupObjects.end());
13182   Cleanup.reset();
13183   MaybeODRUseExprs.clear();
13184 }
13185 
13186 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13187   if (!E->getType()->isVariablyModifiedType())
13188     return E;
13189   return TransformToPotentiallyEvaluated(E);
13190 }
13191 
13192 /// Are we within a context in which some evaluation could be performed (be it
13193 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13194 /// captured by C++'s idea of an "unevaluated context".
13195 static bool isEvaluatableContext(Sema &SemaRef) {
13196   switch (SemaRef.ExprEvalContexts.back().Context) {
13197     case Sema::Unevaluated:
13198     case Sema::UnevaluatedAbstract:
13199     case Sema::DiscardedStatement:
13200       // Expressions in this context are never evaluated.
13201       return false;
13202 
13203     case Sema::UnevaluatedList:
13204     case Sema::ConstantEvaluated:
13205     case Sema::PotentiallyEvaluated:
13206       // Expressions in this context could be evaluated.
13207       return true;
13208 
13209     case Sema::PotentiallyEvaluatedIfUsed:
13210       // Referenced declarations will only be used if the construct in the
13211       // containing expression is used, at which point we'll be given another
13212       // turn to mark them.
13213       return false;
13214   }
13215   llvm_unreachable("Invalid context");
13216 }
13217 
13218 /// Are we within a context in which references to resolved functions or to
13219 /// variables result in odr-use?
13220 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13221   // An expression in a template is not really an expression until it's been
13222   // instantiated, so it doesn't trigger odr-use.
13223   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13224     return false;
13225 
13226   switch (SemaRef.ExprEvalContexts.back().Context) {
13227     case Sema::Unevaluated:
13228     case Sema::UnevaluatedList:
13229     case Sema::UnevaluatedAbstract:
13230     case Sema::DiscardedStatement:
13231       return false;
13232 
13233     case Sema::ConstantEvaluated:
13234     case Sema::PotentiallyEvaluated:
13235       return true;
13236 
13237     case Sema::PotentiallyEvaluatedIfUsed:
13238       return false;
13239   }
13240   llvm_unreachable("Invalid context");
13241 }
13242 
13243 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13244   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13245   return Func->isConstexpr() &&
13246          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13247 }
13248 
13249 /// \brief Mark a function referenced, and check whether it is odr-used
13250 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13251 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13252                                   bool MightBeOdrUse) {
13253   assert(Func && "No function?");
13254 
13255   Func->setReferenced();
13256 
13257   // C++11 [basic.def.odr]p3:
13258   //   A function whose name appears as a potentially-evaluated expression is
13259   //   odr-used if it is the unique lookup result or the selected member of a
13260   //   set of overloaded functions [...].
13261   //
13262   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13263   // can just check that here.
13264   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13265 
13266   // Determine whether we require a function definition to exist, per
13267   // C++11 [temp.inst]p3:
13268   //   Unless a function template specialization has been explicitly
13269   //   instantiated or explicitly specialized, the function template
13270   //   specialization is implicitly instantiated when the specialization is
13271   //   referenced in a context that requires a function definition to exist.
13272   //
13273   // That is either when this is an odr-use, or when a usage of a constexpr
13274   // function occurs within an evaluatable context.
13275   bool NeedDefinition =
13276       OdrUse || (isEvaluatableContext(*this) &&
13277                  isImplicitlyDefinableConstexprFunction(Func));
13278 
13279   // C++14 [temp.expl.spec]p6:
13280   //   If a template [...] is explicitly specialized then that specialization
13281   //   shall be declared before the first use of that specialization that would
13282   //   cause an implicit instantiation to take place, in every translation unit
13283   //   in which such a use occurs
13284   if (NeedDefinition &&
13285       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13286        Func->getMemberSpecializationInfo()))
13287     checkSpecializationVisibility(Loc, Func);
13288 
13289   // C++14 [except.spec]p17:
13290   //   An exception-specification is considered to be needed when:
13291   //   - the function is odr-used or, if it appears in an unevaluated operand,
13292   //     would be odr-used if the expression were potentially-evaluated;
13293   //
13294   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13295   // function is a pure virtual function we're calling, and in that case the
13296   // function was selected by overload resolution and we need to resolve its
13297   // exception specification for a different reason.
13298   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13299   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13300     ResolveExceptionSpec(Loc, FPT);
13301 
13302   // If we don't need to mark the function as used, and we don't need to
13303   // try to provide a definition, there's nothing more to do.
13304   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13305       (!NeedDefinition || Func->getBody()))
13306     return;
13307 
13308   // Note that this declaration has been used.
13309   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13310     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13311     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13312       if (Constructor->isDefaultConstructor()) {
13313         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13314           return;
13315         DefineImplicitDefaultConstructor(Loc, Constructor);
13316       } else if (Constructor->isCopyConstructor()) {
13317         DefineImplicitCopyConstructor(Loc, Constructor);
13318       } else if (Constructor->isMoveConstructor()) {
13319         DefineImplicitMoveConstructor(Loc, Constructor);
13320       }
13321     } else if (Constructor->getInheritedConstructor()) {
13322       DefineInheritingConstructor(Loc, Constructor);
13323     }
13324   } else if (CXXDestructorDecl *Destructor =
13325                  dyn_cast<CXXDestructorDecl>(Func)) {
13326     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13327     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13328       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13329         return;
13330       DefineImplicitDestructor(Loc, Destructor);
13331     }
13332     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13333       MarkVTableUsed(Loc, Destructor->getParent());
13334   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13335     if (MethodDecl->isOverloadedOperator() &&
13336         MethodDecl->getOverloadedOperator() == OO_Equal) {
13337       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13338       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13339         if (MethodDecl->isCopyAssignmentOperator())
13340           DefineImplicitCopyAssignment(Loc, MethodDecl);
13341         else if (MethodDecl->isMoveAssignmentOperator())
13342           DefineImplicitMoveAssignment(Loc, MethodDecl);
13343       }
13344     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13345                MethodDecl->getParent()->isLambda()) {
13346       CXXConversionDecl *Conversion =
13347           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13348       if (Conversion->isLambdaToBlockPointerConversion())
13349         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13350       else
13351         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13352     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13353       MarkVTableUsed(Loc, MethodDecl->getParent());
13354   }
13355 
13356   // Recursive functions should be marked when used from another function.
13357   // FIXME: Is this really right?
13358   if (CurContext == Func) return;
13359 
13360   // Implicit instantiation of function templates and member functions of
13361   // class templates.
13362   if (Func->isImplicitlyInstantiable()) {
13363     bool AlreadyInstantiated = false;
13364     SourceLocation PointOfInstantiation = Loc;
13365     if (FunctionTemplateSpecializationInfo *SpecInfo
13366                               = Func->getTemplateSpecializationInfo()) {
13367       if (SpecInfo->getPointOfInstantiation().isInvalid())
13368         SpecInfo->setPointOfInstantiation(Loc);
13369       else if (SpecInfo->getTemplateSpecializationKind()
13370                  == TSK_ImplicitInstantiation) {
13371         AlreadyInstantiated = true;
13372         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13373       }
13374     } else if (MemberSpecializationInfo *MSInfo
13375                                 = Func->getMemberSpecializationInfo()) {
13376       if (MSInfo->getPointOfInstantiation().isInvalid())
13377         MSInfo->setPointOfInstantiation(Loc);
13378       else if (MSInfo->getTemplateSpecializationKind()
13379                  == TSK_ImplicitInstantiation) {
13380         AlreadyInstantiated = true;
13381         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13382       }
13383     }
13384 
13385     if (!AlreadyInstantiated || Func->isConstexpr()) {
13386       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13387           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13388           CodeSynthesisContexts.size())
13389         PendingLocalImplicitInstantiations.push_back(
13390             std::make_pair(Func, PointOfInstantiation));
13391       else if (Func->isConstexpr())
13392         // Do not defer instantiations of constexpr functions, to avoid the
13393         // expression evaluator needing to call back into Sema if it sees a
13394         // call to such a function.
13395         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13396       else {
13397         PendingInstantiations.push_back(std::make_pair(Func,
13398                                                        PointOfInstantiation));
13399         // Notify the consumer that a function was implicitly instantiated.
13400         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13401       }
13402     }
13403   } else {
13404     // Walk redefinitions, as some of them may be instantiable.
13405     for (auto i : Func->redecls()) {
13406       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13407         MarkFunctionReferenced(Loc, i, OdrUse);
13408     }
13409   }
13410 
13411   if (!OdrUse) return;
13412 
13413   // Keep track of used but undefined functions.
13414   if (!Func->isDefined()) {
13415     if (mightHaveNonExternalLinkage(Func))
13416       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13417     else if (Func->getMostRecentDecl()->isInlined() &&
13418              !LangOpts.GNUInline &&
13419              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13420       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13421   }
13422 
13423   Func->markUsed(Context);
13424 }
13425 
13426 static void
13427 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13428                                    ValueDecl *var, DeclContext *DC) {
13429   DeclContext *VarDC = var->getDeclContext();
13430 
13431   //  If the parameter still belongs to the translation unit, then
13432   //  we're actually just using one parameter in the declaration of
13433   //  the next.
13434   if (isa<ParmVarDecl>(var) &&
13435       isa<TranslationUnitDecl>(VarDC))
13436     return;
13437 
13438   // For C code, don't diagnose about capture if we're not actually in code
13439   // right now; it's impossible to write a non-constant expression outside of
13440   // function context, so we'll get other (more useful) diagnostics later.
13441   //
13442   // For C++, things get a bit more nasty... it would be nice to suppress this
13443   // diagnostic for certain cases like using a local variable in an array bound
13444   // for a member of a local class, but the correct predicate is not obvious.
13445   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13446     return;
13447 
13448   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13449   unsigned ContextKind = 3; // unknown
13450   if (isa<CXXMethodDecl>(VarDC) &&
13451       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13452     ContextKind = 2;
13453   } else if (isa<FunctionDecl>(VarDC)) {
13454     ContextKind = 0;
13455   } else if (isa<BlockDecl>(VarDC)) {
13456     ContextKind = 1;
13457   }
13458 
13459   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13460     << var << ValueKind << ContextKind << VarDC;
13461   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13462       << var;
13463 
13464   // FIXME: Add additional diagnostic info about class etc. which prevents
13465   // capture.
13466 }
13467 
13468 
13469 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13470                                       bool &SubCapturesAreNested,
13471                                       QualType &CaptureType,
13472                                       QualType &DeclRefType) {
13473    // Check whether we've already captured it.
13474   if (CSI->CaptureMap.count(Var)) {
13475     // If we found a capture, any subcaptures are nested.
13476     SubCapturesAreNested = true;
13477 
13478     // Retrieve the capture type for this variable.
13479     CaptureType = CSI->getCapture(Var).getCaptureType();
13480 
13481     // Compute the type of an expression that refers to this variable.
13482     DeclRefType = CaptureType.getNonReferenceType();
13483 
13484     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13485     // are mutable in the sense that user can change their value - they are
13486     // private instances of the captured declarations.
13487     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13488     if (Cap.isCopyCapture() &&
13489         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13490         !(isa<CapturedRegionScopeInfo>(CSI) &&
13491           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13492       DeclRefType.addConst();
13493     return true;
13494   }
13495   return false;
13496 }
13497 
13498 // Only block literals, captured statements, and lambda expressions can
13499 // capture; other scopes don't work.
13500 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13501                                  SourceLocation Loc,
13502                                  const bool Diagnose, Sema &S) {
13503   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13504     return getLambdaAwareParentOfDeclContext(DC);
13505   else if (Var->hasLocalStorage()) {
13506     if (Diagnose)
13507        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13508   }
13509   return nullptr;
13510 }
13511 
13512 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13513 // certain types of variables (unnamed, variably modified types etc.)
13514 // so check for eligibility.
13515 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13516                                  SourceLocation Loc,
13517                                  const bool Diagnose, Sema &S) {
13518 
13519   bool IsBlock = isa<BlockScopeInfo>(CSI);
13520   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13521 
13522   // Lambdas are not allowed to capture unnamed variables
13523   // (e.g. anonymous unions).
13524   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13525   // assuming that's the intent.
13526   if (IsLambda && !Var->getDeclName()) {
13527     if (Diagnose) {
13528       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13529       S.Diag(Var->getLocation(), diag::note_declared_at);
13530     }
13531     return false;
13532   }
13533 
13534   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13535   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13536     if (Diagnose) {
13537       S.Diag(Loc, diag::err_ref_vm_type);
13538       S.Diag(Var->getLocation(), diag::note_previous_decl)
13539         << Var->getDeclName();
13540     }
13541     return false;
13542   }
13543   // Prohibit structs with flexible array members too.
13544   // We cannot capture what is in the tail end of the struct.
13545   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13546     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13547       if (Diagnose) {
13548         if (IsBlock)
13549           S.Diag(Loc, diag::err_ref_flexarray_type);
13550         else
13551           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13552             << Var->getDeclName();
13553         S.Diag(Var->getLocation(), diag::note_previous_decl)
13554           << Var->getDeclName();
13555       }
13556       return false;
13557     }
13558   }
13559   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13560   // Lambdas and captured statements are not allowed to capture __block
13561   // variables; they don't support the expected semantics.
13562   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13563     if (Diagnose) {
13564       S.Diag(Loc, diag::err_capture_block_variable)
13565         << Var->getDeclName() << !IsLambda;
13566       S.Diag(Var->getLocation(), diag::note_previous_decl)
13567         << Var->getDeclName();
13568     }
13569     return false;
13570   }
13571   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13572   if (S.getLangOpts().OpenCL && IsBlock &&
13573       Var->getType()->isBlockPointerType()) {
13574     if (Diagnose)
13575       S.Diag(Loc, diag::err_opencl_block_ref_block);
13576     return false;
13577   }
13578 
13579   return true;
13580 }
13581 
13582 // Returns true if the capture by block was successful.
13583 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13584                                  SourceLocation Loc,
13585                                  const bool BuildAndDiagnose,
13586                                  QualType &CaptureType,
13587                                  QualType &DeclRefType,
13588                                  const bool Nested,
13589                                  Sema &S) {
13590   Expr *CopyExpr = nullptr;
13591   bool ByRef = false;
13592 
13593   // Blocks are not allowed to capture arrays.
13594   if (CaptureType->isArrayType()) {
13595     if (BuildAndDiagnose) {
13596       S.Diag(Loc, diag::err_ref_array_type);
13597       S.Diag(Var->getLocation(), diag::note_previous_decl)
13598       << Var->getDeclName();
13599     }
13600     return false;
13601   }
13602 
13603   // Forbid the block-capture of autoreleasing variables.
13604   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13605     if (BuildAndDiagnose) {
13606       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13607         << /*block*/ 0;
13608       S.Diag(Var->getLocation(), diag::note_previous_decl)
13609         << Var->getDeclName();
13610     }
13611     return false;
13612   }
13613 
13614   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13615   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13616     // This function finds out whether there is an AttributedType of kind
13617     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13618     // attr_objc_ownership implies __autoreleasing was explicitly specified
13619     // rather than being added implicitly by the compiler.
13620     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13621       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13622         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13623           return true;
13624 
13625         // Peel off AttributedTypes that are not of kind objc_ownership.
13626         Ty = AttrTy->getModifiedType();
13627       }
13628 
13629       return false;
13630     };
13631 
13632     QualType PointeeTy = PT->getPointeeType();
13633 
13634     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13635         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13636         !IsObjCOwnershipAttributedType(PointeeTy)) {
13637       if (BuildAndDiagnose) {
13638         SourceLocation VarLoc = Var->getLocation();
13639         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13640         {
13641           auto AddAutoreleaseNote =
13642               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13643           // Provide a fix-it for the '__autoreleasing' keyword at the
13644           // appropriate location in the variable's type.
13645           if (const auto *TSI = Var->getTypeSourceInfo()) {
13646             PointerTypeLoc PTL =
13647                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13648             if (PTL) {
13649               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13650               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13651                                                S.getLangOpts());
13652               if (Loc.isValid()) {
13653                 StringRef CharAtLoc = Lexer::getSourceText(
13654                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13655                     S.getSourceManager(), S.getLangOpts());
13656                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13657                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13658                              ? " __autoreleasing "
13659                              : " __autoreleasing");
13660               }
13661             }
13662           }
13663         }
13664         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13665       }
13666     }
13667   }
13668 
13669   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13670   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13671       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13672     // Block capture by reference does not change the capture or
13673     // declaration reference types.
13674     ByRef = true;
13675   } else {
13676     // Block capture by copy introduces 'const'.
13677     CaptureType = CaptureType.getNonReferenceType().withConst();
13678     DeclRefType = CaptureType;
13679 
13680     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13681       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13682         // The capture logic needs the destructor, so make sure we mark it.
13683         // Usually this is unnecessary because most local variables have
13684         // their destructors marked at declaration time, but parameters are
13685         // an exception because it's technically only the call site that
13686         // actually requires the destructor.
13687         if (isa<ParmVarDecl>(Var))
13688           S.FinalizeVarWithDestructor(Var, Record);
13689 
13690         // Enter a new evaluation context to insulate the copy
13691         // full-expression.
13692         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13693 
13694         // According to the blocks spec, the capture of a variable from
13695         // the stack requires a const copy constructor.  This is not true
13696         // of the copy/move done to move a __block variable to the heap.
13697         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13698                                                   DeclRefType.withConst(),
13699                                                   VK_LValue, Loc);
13700 
13701         ExprResult Result
13702           = S.PerformCopyInitialization(
13703               InitializedEntity::InitializeBlock(Var->getLocation(),
13704                                                   CaptureType, false),
13705               Loc, DeclRef);
13706 
13707         // Build a full-expression copy expression if initialization
13708         // succeeded and used a non-trivial constructor.  Recover from
13709         // errors by pretending that the copy isn't necessary.
13710         if (!Result.isInvalid() &&
13711             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13712                 ->isTrivial()) {
13713           Result = S.MaybeCreateExprWithCleanups(Result);
13714           CopyExpr = Result.get();
13715         }
13716       }
13717     }
13718   }
13719 
13720   // Actually capture the variable.
13721   if (BuildAndDiagnose)
13722     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13723                     SourceLocation(), CaptureType, CopyExpr);
13724 
13725   return true;
13726 
13727 }
13728 
13729 
13730 /// \brief Capture the given variable in the captured region.
13731 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13732                                     VarDecl *Var,
13733                                     SourceLocation Loc,
13734                                     const bool BuildAndDiagnose,
13735                                     QualType &CaptureType,
13736                                     QualType &DeclRefType,
13737                                     const bool RefersToCapturedVariable,
13738                                     Sema &S) {
13739   // By default, capture variables by reference.
13740   bool ByRef = true;
13741   // Using an LValue reference type is consistent with Lambdas (see below).
13742   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13743     if (S.IsOpenMPCapturedDecl(Var))
13744       DeclRefType = DeclRefType.getUnqualifiedType();
13745     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13746   }
13747 
13748   if (ByRef)
13749     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13750   else
13751     CaptureType = DeclRefType;
13752 
13753   Expr *CopyExpr = nullptr;
13754   if (BuildAndDiagnose) {
13755     // The current implementation assumes that all variables are captured
13756     // by references. Since there is no capture by copy, no expression
13757     // evaluation will be needed.
13758     RecordDecl *RD = RSI->TheRecordDecl;
13759 
13760     FieldDecl *Field
13761       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13762                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13763                           nullptr, false, ICIS_NoInit);
13764     Field->setImplicit(true);
13765     Field->setAccess(AS_private);
13766     RD->addDecl(Field);
13767 
13768     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13769                                             DeclRefType, VK_LValue, Loc);
13770     Var->setReferenced(true);
13771     Var->markUsed(S.Context);
13772   }
13773 
13774   // Actually capture the variable.
13775   if (BuildAndDiagnose)
13776     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13777                     SourceLocation(), CaptureType, CopyExpr);
13778 
13779 
13780   return true;
13781 }
13782 
13783 /// \brief Create a field within the lambda class for the variable
13784 /// being captured.
13785 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13786                                     QualType FieldType, QualType DeclRefType,
13787                                     SourceLocation Loc,
13788                                     bool RefersToCapturedVariable) {
13789   CXXRecordDecl *Lambda = LSI->Lambda;
13790 
13791   // Build the non-static data member.
13792   FieldDecl *Field
13793     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13794                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13795                         nullptr, false, ICIS_NoInit);
13796   Field->setImplicit(true);
13797   Field->setAccess(AS_private);
13798   Lambda->addDecl(Field);
13799 }
13800 
13801 /// \brief Capture the given variable in the lambda.
13802 static bool captureInLambda(LambdaScopeInfo *LSI,
13803                             VarDecl *Var,
13804                             SourceLocation Loc,
13805                             const bool BuildAndDiagnose,
13806                             QualType &CaptureType,
13807                             QualType &DeclRefType,
13808                             const bool RefersToCapturedVariable,
13809                             const Sema::TryCaptureKind Kind,
13810                             SourceLocation EllipsisLoc,
13811                             const bool IsTopScope,
13812                             Sema &S) {
13813 
13814   // Determine whether we are capturing by reference or by value.
13815   bool ByRef = false;
13816   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13817     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13818   } else {
13819     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13820   }
13821 
13822   // Compute the type of the field that will capture this variable.
13823   if (ByRef) {
13824     // C++11 [expr.prim.lambda]p15:
13825     //   An entity is captured by reference if it is implicitly or
13826     //   explicitly captured but not captured by copy. It is
13827     //   unspecified whether additional unnamed non-static data
13828     //   members are declared in the closure type for entities
13829     //   captured by reference.
13830     //
13831     // FIXME: It is not clear whether we want to build an lvalue reference
13832     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13833     // to do the former, while EDG does the latter. Core issue 1249 will
13834     // clarify, but for now we follow GCC because it's a more permissive and
13835     // easily defensible position.
13836     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13837   } else {
13838     // C++11 [expr.prim.lambda]p14:
13839     //   For each entity captured by copy, an unnamed non-static
13840     //   data member is declared in the closure type. The
13841     //   declaration order of these members is unspecified. The type
13842     //   of such a data member is the type of the corresponding
13843     //   captured entity if the entity is not a reference to an
13844     //   object, or the referenced type otherwise. [Note: If the
13845     //   captured entity is a reference to a function, the
13846     //   corresponding data member is also a reference to a
13847     //   function. - end note ]
13848     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13849       if (!RefType->getPointeeType()->isFunctionType())
13850         CaptureType = RefType->getPointeeType();
13851     }
13852 
13853     // Forbid the lambda copy-capture of autoreleasing variables.
13854     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13855       if (BuildAndDiagnose) {
13856         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13857         S.Diag(Var->getLocation(), diag::note_previous_decl)
13858           << Var->getDeclName();
13859       }
13860       return false;
13861     }
13862 
13863     // Make sure that by-copy captures are of a complete and non-abstract type.
13864     if (BuildAndDiagnose) {
13865       if (!CaptureType->isDependentType() &&
13866           S.RequireCompleteType(Loc, CaptureType,
13867                                 diag::err_capture_of_incomplete_type,
13868                                 Var->getDeclName()))
13869         return false;
13870 
13871       if (S.RequireNonAbstractType(Loc, CaptureType,
13872                                    diag::err_capture_of_abstract_type))
13873         return false;
13874     }
13875   }
13876 
13877   // Capture this variable in the lambda.
13878   if (BuildAndDiagnose)
13879     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13880                             RefersToCapturedVariable);
13881 
13882   // Compute the type of a reference to this captured variable.
13883   if (ByRef)
13884     DeclRefType = CaptureType.getNonReferenceType();
13885   else {
13886     // C++ [expr.prim.lambda]p5:
13887     //   The closure type for a lambda-expression has a public inline
13888     //   function call operator [...]. This function call operator is
13889     //   declared const (9.3.1) if and only if the lambda-expression's
13890     //   parameter-declaration-clause is not followed by mutable.
13891     DeclRefType = CaptureType.getNonReferenceType();
13892     if (!LSI->Mutable && !CaptureType->isReferenceType())
13893       DeclRefType.addConst();
13894   }
13895 
13896   // Add the capture.
13897   if (BuildAndDiagnose)
13898     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13899                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13900 
13901   return true;
13902 }
13903 
13904 bool Sema::tryCaptureVariable(
13905     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13906     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13907     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13908   // An init-capture is notionally from the context surrounding its
13909   // declaration, but its parent DC is the lambda class.
13910   DeclContext *VarDC = Var->getDeclContext();
13911   if (Var->isInitCapture())
13912     VarDC = VarDC->getParent();
13913 
13914   DeclContext *DC = CurContext;
13915   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13916       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13917   // We need to sync up the Declaration Context with the
13918   // FunctionScopeIndexToStopAt
13919   if (FunctionScopeIndexToStopAt) {
13920     unsigned FSIndex = FunctionScopes.size() - 1;
13921     while (FSIndex != MaxFunctionScopesIndex) {
13922       DC = getLambdaAwareParentOfDeclContext(DC);
13923       --FSIndex;
13924     }
13925   }
13926 
13927 
13928   // If the variable is declared in the current context, there is no need to
13929   // capture it.
13930   if (VarDC == DC) return true;
13931 
13932   // Capture global variables if it is required to use private copy of this
13933   // variable.
13934   bool IsGlobal = !Var->hasLocalStorage();
13935   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13936     return true;
13937 
13938   // Walk up the stack to determine whether we can capture the variable,
13939   // performing the "simple" checks that don't depend on type. We stop when
13940   // we've either hit the declared scope of the variable or find an existing
13941   // capture of that variable.  We start from the innermost capturing-entity
13942   // (the DC) and ensure that all intervening capturing-entities
13943   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13944   // declcontext can either capture the variable or have already captured
13945   // the variable.
13946   CaptureType = Var->getType();
13947   DeclRefType = CaptureType.getNonReferenceType();
13948   bool Nested = false;
13949   bool Explicit = (Kind != TryCapture_Implicit);
13950   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13951   do {
13952     // Only block literals, captured statements, and lambda expressions can
13953     // capture; other scopes don't work.
13954     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13955                                                               ExprLoc,
13956                                                               BuildAndDiagnose,
13957                                                               *this);
13958     // We need to check for the parent *first* because, if we *have*
13959     // private-captured a global variable, we need to recursively capture it in
13960     // intermediate blocks, lambdas, etc.
13961     if (!ParentDC) {
13962       if (IsGlobal) {
13963         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13964         break;
13965       }
13966       return true;
13967     }
13968 
13969     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13970     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13971 
13972 
13973     // Check whether we've already captured it.
13974     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13975                                              DeclRefType)) {
13976       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
13977       break;
13978     }
13979     // If we are instantiating a generic lambda call operator body,
13980     // we do not want to capture new variables.  What was captured
13981     // during either a lambdas transformation or initial parsing
13982     // should be used.
13983     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13984       if (BuildAndDiagnose) {
13985         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13986         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13987           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13988           Diag(Var->getLocation(), diag::note_previous_decl)
13989              << Var->getDeclName();
13990           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13991         } else
13992           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13993       }
13994       return true;
13995     }
13996     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13997     // certain types of variables (unnamed, variably modified types etc.)
13998     // so check for eligibility.
13999     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14000        return true;
14001 
14002     // Try to capture variable-length arrays types.
14003     if (Var->getType()->isVariablyModifiedType()) {
14004       // We're going to walk down into the type and look for VLA
14005       // expressions.
14006       QualType QTy = Var->getType();
14007       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14008         QTy = PVD->getOriginalType();
14009       captureVariablyModifiedType(Context, QTy, CSI);
14010     }
14011 
14012     if (getLangOpts().OpenMP) {
14013       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14014         // OpenMP private variables should not be captured in outer scope, so
14015         // just break here. Similarly, global variables that are captured in a
14016         // target region should not be captured outside the scope of the region.
14017         if (RSI->CapRegionKind == CR_OpenMP) {
14018           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14019           // When we detect target captures we are looking from inside the
14020           // target region, therefore we need to propagate the capture from the
14021           // enclosing region. Therefore, the capture is not initially nested.
14022           if (IsTargetCap)
14023             FunctionScopesIndex--;
14024 
14025           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14026             Nested = !IsTargetCap;
14027             DeclRefType = DeclRefType.getUnqualifiedType();
14028             CaptureType = Context.getLValueReferenceType(DeclRefType);
14029             break;
14030           }
14031         }
14032       }
14033     }
14034     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14035       // No capture-default, and this is not an explicit capture
14036       // so cannot capture this variable.
14037       if (BuildAndDiagnose) {
14038         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14039         Diag(Var->getLocation(), diag::note_previous_decl)
14040           << Var->getDeclName();
14041         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14042           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14043                diag::note_lambda_decl);
14044         // FIXME: If we error out because an outer lambda can not implicitly
14045         // capture a variable that an inner lambda explicitly captures, we
14046         // should have the inner lambda do the explicit capture - because
14047         // it makes for cleaner diagnostics later.  This would purely be done
14048         // so that the diagnostic does not misleadingly claim that a variable
14049         // can not be captured by a lambda implicitly even though it is captured
14050         // explicitly.  Suggestion:
14051         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14052         //    at the function head
14053         //  - cache the StartingDeclContext - this must be a lambda
14054         //  - captureInLambda in the innermost lambda the variable.
14055       }
14056       return true;
14057     }
14058 
14059     FunctionScopesIndex--;
14060     DC = ParentDC;
14061     Explicit = false;
14062   } while (!VarDC->Equals(DC));
14063 
14064   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14065   // computing the type of the capture at each step, checking type-specific
14066   // requirements, and adding captures if requested.
14067   // If the variable had already been captured previously, we start capturing
14068   // at the lambda nested within that one.
14069   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14070        ++I) {
14071     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14072 
14073     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14074       if (!captureInBlock(BSI, Var, ExprLoc,
14075                           BuildAndDiagnose, CaptureType,
14076                           DeclRefType, Nested, *this))
14077         return true;
14078       Nested = true;
14079     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14080       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14081                                    BuildAndDiagnose, CaptureType,
14082                                    DeclRefType, Nested, *this))
14083         return true;
14084       Nested = true;
14085     } else {
14086       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14087       if (!captureInLambda(LSI, Var, ExprLoc,
14088                            BuildAndDiagnose, CaptureType,
14089                            DeclRefType, Nested, Kind, EllipsisLoc,
14090                             /*IsTopScope*/I == N - 1, *this))
14091         return true;
14092       Nested = true;
14093     }
14094   }
14095   return false;
14096 }
14097 
14098 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14099                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14100   QualType CaptureType;
14101   QualType DeclRefType;
14102   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14103                             /*BuildAndDiagnose=*/true, CaptureType,
14104                             DeclRefType, nullptr);
14105 }
14106 
14107 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14108   QualType CaptureType;
14109   QualType DeclRefType;
14110   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14111                              /*BuildAndDiagnose=*/false, CaptureType,
14112                              DeclRefType, nullptr);
14113 }
14114 
14115 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14116   QualType CaptureType;
14117   QualType DeclRefType;
14118 
14119   // Determine whether we can capture this variable.
14120   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14121                          /*BuildAndDiagnose=*/false, CaptureType,
14122                          DeclRefType, nullptr))
14123     return QualType();
14124 
14125   return DeclRefType;
14126 }
14127 
14128 
14129 
14130 // If either the type of the variable or the initializer is dependent,
14131 // return false. Otherwise, determine whether the variable is a constant
14132 // expression. Use this if you need to know if a variable that might or
14133 // might not be dependent is truly a constant expression.
14134 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14135     ASTContext &Context) {
14136 
14137   if (Var->getType()->isDependentType())
14138     return false;
14139   const VarDecl *DefVD = nullptr;
14140   Var->getAnyInitializer(DefVD);
14141   if (!DefVD)
14142     return false;
14143   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14144   Expr *Init = cast<Expr>(Eval->Value);
14145   if (Init->isValueDependent())
14146     return false;
14147   return IsVariableAConstantExpression(Var, Context);
14148 }
14149 
14150 
14151 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14152   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14153   // an object that satisfies the requirements for appearing in a
14154   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14155   // is immediately applied."  This function handles the lvalue-to-rvalue
14156   // conversion part.
14157   MaybeODRUseExprs.erase(E->IgnoreParens());
14158 
14159   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14160   // to a variable that is a constant expression, and if so, identify it as
14161   // a reference to a variable that does not involve an odr-use of that
14162   // variable.
14163   if (LambdaScopeInfo *LSI = getCurLambda()) {
14164     Expr *SansParensExpr = E->IgnoreParens();
14165     VarDecl *Var = nullptr;
14166     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14167       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14168     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14169       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14170 
14171     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14172       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14173   }
14174 }
14175 
14176 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14177   Res = CorrectDelayedTyposInExpr(Res);
14178 
14179   if (!Res.isUsable())
14180     return Res;
14181 
14182   // If a constant-expression is a reference to a variable where we delay
14183   // deciding whether it is an odr-use, just assume we will apply the
14184   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14185   // (a non-type template argument), we have special handling anyway.
14186   UpdateMarkingForLValueToRValue(Res.get());
14187   return Res;
14188 }
14189 
14190 void Sema::CleanupVarDeclMarking() {
14191   for (Expr *E : MaybeODRUseExprs) {
14192     VarDecl *Var;
14193     SourceLocation Loc;
14194     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14195       Var = cast<VarDecl>(DRE->getDecl());
14196       Loc = DRE->getLocation();
14197     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14198       Var = cast<VarDecl>(ME->getMemberDecl());
14199       Loc = ME->getMemberLoc();
14200     } else {
14201       llvm_unreachable("Unexpected expression");
14202     }
14203 
14204     MarkVarDeclODRUsed(Var, Loc, *this,
14205                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14206   }
14207 
14208   MaybeODRUseExprs.clear();
14209 }
14210 
14211 
14212 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14213                                     VarDecl *Var, Expr *E) {
14214   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14215          "Invalid Expr argument to DoMarkVarDeclReferenced");
14216   Var->setReferenced();
14217 
14218   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14219 
14220   bool OdrUseContext = isOdrUseContext(SemaRef);
14221   bool NeedDefinition =
14222       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14223                         Var->isUsableInConstantExpressions(SemaRef.Context));
14224 
14225   VarTemplateSpecializationDecl *VarSpec =
14226       dyn_cast<VarTemplateSpecializationDecl>(Var);
14227   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14228          "Can't instantiate a partial template specialization.");
14229 
14230   // If this might be a member specialization of a static data member, check
14231   // the specialization is visible. We already did the checks for variable
14232   // template specializations when we created them.
14233   if (NeedDefinition && TSK != TSK_Undeclared &&
14234       !isa<VarTemplateSpecializationDecl>(Var))
14235     SemaRef.checkSpecializationVisibility(Loc, Var);
14236 
14237   // Perform implicit instantiation of static data members, static data member
14238   // templates of class templates, and variable template specializations. Delay
14239   // instantiations of variable templates, except for those that could be used
14240   // in a constant expression.
14241   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14242     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14243 
14244     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14245       if (Var->getPointOfInstantiation().isInvalid()) {
14246         // This is a modification of an existing AST node. Notify listeners.
14247         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14248           L->StaticDataMemberInstantiated(Var);
14249       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14250         // Don't bother trying to instantiate it again, unless we might need
14251         // its initializer before we get to the end of the TU.
14252         TryInstantiating = false;
14253     }
14254 
14255     if (Var->getPointOfInstantiation().isInvalid())
14256       Var->setTemplateSpecializationKind(TSK, Loc);
14257 
14258     if (TryInstantiating) {
14259       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14260       bool InstantiationDependent = false;
14261       bool IsNonDependent =
14262           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14263                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14264                   : true;
14265 
14266       // Do not instantiate specializations that are still type-dependent.
14267       if (IsNonDependent) {
14268         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14269           // Do not defer instantiations of variables which could be used in a
14270           // constant expression.
14271           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14272         } else {
14273           SemaRef.PendingInstantiations
14274               .push_back(std::make_pair(Var, PointOfInstantiation));
14275         }
14276       }
14277     }
14278   }
14279 
14280   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14281   // the requirements for appearing in a constant expression (5.19) and, if
14282   // it is an object, the lvalue-to-rvalue conversion (4.1)
14283   // is immediately applied."  We check the first part here, and
14284   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14285   // Note that we use the C++11 definition everywhere because nothing in
14286   // C++03 depends on whether we get the C++03 version correct. The second
14287   // part does not apply to references, since they are not objects.
14288   if (OdrUseContext && E &&
14289       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14290     // A reference initialized by a constant expression can never be
14291     // odr-used, so simply ignore it.
14292     if (!Var->getType()->isReferenceType())
14293       SemaRef.MaybeODRUseExprs.insert(E);
14294   } else if (OdrUseContext) {
14295     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14296                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14297   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14298     // If this is a dependent context, we don't need to mark variables as
14299     // odr-used, but we may still need to track them for lambda capture.
14300     // FIXME: Do we also need to do this inside dependent typeid expressions
14301     // (which are modeled as unevaluated at this point)?
14302     const bool RefersToEnclosingScope =
14303         (SemaRef.CurContext != Var->getDeclContext() &&
14304          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14305     if (RefersToEnclosingScope) {
14306       LambdaScopeInfo *const LSI =
14307           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14308       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14309         // If a variable could potentially be odr-used, defer marking it so
14310         // until we finish analyzing the full expression for any
14311         // lvalue-to-rvalue
14312         // or discarded value conversions that would obviate odr-use.
14313         // Add it to the list of potential captures that will be analyzed
14314         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14315         // unless the variable is a reference that was initialized by a constant
14316         // expression (this will never need to be captured or odr-used).
14317         assert(E && "Capture variable should be used in an expression.");
14318         if (!Var->getType()->isReferenceType() ||
14319             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14320           LSI->addPotentialCapture(E->IgnoreParens());
14321       }
14322     }
14323   }
14324 }
14325 
14326 /// \brief Mark a variable referenced, and check whether it is odr-used
14327 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14328 /// used directly for normal expressions referring to VarDecl.
14329 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14330   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14331 }
14332 
14333 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14334                                Decl *D, Expr *E, bool MightBeOdrUse) {
14335   if (SemaRef.isInOpenMPDeclareTargetContext())
14336     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14337 
14338   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14339     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14340     return;
14341   }
14342 
14343   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14344 
14345   // If this is a call to a method via a cast, also mark the method in the
14346   // derived class used in case codegen can devirtualize the call.
14347   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14348   if (!ME)
14349     return;
14350   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14351   if (!MD)
14352     return;
14353   // Only attempt to devirtualize if this is truly a virtual call.
14354   bool IsVirtualCall = MD->isVirtual() &&
14355                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14356   if (!IsVirtualCall)
14357     return;
14358   const Expr *Base = ME->getBase();
14359   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14360   if (!MostDerivedClassDecl)
14361     return;
14362   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14363   if (!DM || DM->isPure())
14364     return;
14365   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14366 }
14367 
14368 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14369 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14370   // TODO: update this with DR# once a defect report is filed.
14371   // C++11 defect. The address of a pure member should not be an ODR use, even
14372   // if it's a qualified reference.
14373   bool OdrUse = true;
14374   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14375     if (Method->isVirtual())
14376       OdrUse = false;
14377   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14378 }
14379 
14380 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14381 void Sema::MarkMemberReferenced(MemberExpr *E) {
14382   // C++11 [basic.def.odr]p2:
14383   //   A non-overloaded function whose name appears as a potentially-evaluated
14384   //   expression or a member of a set of candidate functions, if selected by
14385   //   overload resolution when referred to from a potentially-evaluated
14386   //   expression, is odr-used, unless it is a pure virtual function and its
14387   //   name is not explicitly qualified.
14388   bool MightBeOdrUse = true;
14389   if (E->performsVirtualDispatch(getLangOpts())) {
14390     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14391       if (Method->isPure())
14392         MightBeOdrUse = false;
14393   }
14394   SourceLocation Loc = E->getMemberLoc().isValid() ?
14395                             E->getMemberLoc() : E->getLocStart();
14396   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14397 }
14398 
14399 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14400 /// marks the declaration referenced, and performs odr-use checking for
14401 /// functions and variables. This method should not be used when building a
14402 /// normal expression which refers to a variable.
14403 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14404                                  bool MightBeOdrUse) {
14405   if (MightBeOdrUse) {
14406     if (auto *VD = dyn_cast<VarDecl>(D)) {
14407       MarkVariableReferenced(Loc, VD);
14408       return;
14409     }
14410   }
14411   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14412     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14413     return;
14414   }
14415   D->setReferenced();
14416 }
14417 
14418 namespace {
14419   // Mark all of the declarations used by a type as referenced.
14420   // FIXME: Not fully implemented yet! We need to have a better understanding
14421   // of when we're entering a context we should not recurse into.
14422   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14423   // TreeTransforms rebuilding the type in a new context. Rather than
14424   // duplicating the TreeTransform logic, we should consider reusing it here.
14425   // Currently that causes problems when rebuilding LambdaExprs.
14426   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14427     Sema &S;
14428     SourceLocation Loc;
14429 
14430   public:
14431     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14432 
14433     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14434 
14435     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14436   };
14437 }
14438 
14439 bool MarkReferencedDecls::TraverseTemplateArgument(
14440     const TemplateArgument &Arg) {
14441   {
14442     // A non-type template argument is a constant-evaluated context.
14443     EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14444     if (Arg.getKind() == TemplateArgument::Declaration) {
14445       if (Decl *D = Arg.getAsDecl())
14446         S.MarkAnyDeclReferenced(Loc, D, true);
14447     } else if (Arg.getKind() == TemplateArgument::Expression) {
14448       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14449     }
14450   }
14451 
14452   return Inherited::TraverseTemplateArgument(Arg);
14453 }
14454 
14455 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14456   MarkReferencedDecls Marker(*this, Loc);
14457   Marker.TraverseType(T);
14458 }
14459 
14460 namespace {
14461   /// \brief Helper class that marks all of the declarations referenced by
14462   /// potentially-evaluated subexpressions as "referenced".
14463   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14464     Sema &S;
14465     bool SkipLocalVariables;
14466 
14467   public:
14468     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14469 
14470     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14471       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14472 
14473     void VisitDeclRefExpr(DeclRefExpr *E) {
14474       // If we were asked not to visit local variables, don't.
14475       if (SkipLocalVariables) {
14476         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14477           if (VD->hasLocalStorage())
14478             return;
14479       }
14480 
14481       S.MarkDeclRefReferenced(E);
14482     }
14483 
14484     void VisitMemberExpr(MemberExpr *E) {
14485       S.MarkMemberReferenced(E);
14486       Inherited::VisitMemberExpr(E);
14487     }
14488 
14489     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14490       S.MarkFunctionReferenced(E->getLocStart(),
14491             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14492       Visit(E->getSubExpr());
14493     }
14494 
14495     void VisitCXXNewExpr(CXXNewExpr *E) {
14496       if (E->getOperatorNew())
14497         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14498       if (E->getOperatorDelete())
14499         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14500       Inherited::VisitCXXNewExpr(E);
14501     }
14502 
14503     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14504       if (E->getOperatorDelete())
14505         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14506       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14507       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14508         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14509         S.MarkFunctionReferenced(E->getLocStart(),
14510                                     S.LookupDestructor(Record));
14511       }
14512 
14513       Inherited::VisitCXXDeleteExpr(E);
14514     }
14515 
14516     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14517       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14518       Inherited::VisitCXXConstructExpr(E);
14519     }
14520 
14521     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14522       Visit(E->getExpr());
14523     }
14524 
14525     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14526       Inherited::VisitImplicitCastExpr(E);
14527 
14528       if (E->getCastKind() == CK_LValueToRValue)
14529         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14530     }
14531   };
14532 }
14533 
14534 /// \brief Mark any declarations that appear within this expression or any
14535 /// potentially-evaluated subexpressions as "referenced".
14536 ///
14537 /// \param SkipLocalVariables If true, don't mark local variables as
14538 /// 'referenced'.
14539 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14540                                             bool SkipLocalVariables) {
14541   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14542 }
14543 
14544 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14545 /// of the program being compiled.
14546 ///
14547 /// This routine emits the given diagnostic when the code currently being
14548 /// type-checked is "potentially evaluated", meaning that there is a
14549 /// possibility that the code will actually be executable. Code in sizeof()
14550 /// expressions, code used only during overload resolution, etc., are not
14551 /// potentially evaluated. This routine will suppress such diagnostics or,
14552 /// in the absolutely nutty case of potentially potentially evaluated
14553 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14554 /// later.
14555 ///
14556 /// This routine should be used for all diagnostics that describe the run-time
14557 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14558 /// Failure to do so will likely result in spurious diagnostics or failures
14559 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14560 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14561                                const PartialDiagnostic &PD) {
14562   switch (ExprEvalContexts.back().Context) {
14563   case Unevaluated:
14564   case UnevaluatedList:
14565   case UnevaluatedAbstract:
14566   case DiscardedStatement:
14567     // The argument will never be evaluated, so don't complain.
14568     break;
14569 
14570   case ConstantEvaluated:
14571     // Relevant diagnostics should be produced by constant evaluation.
14572     break;
14573 
14574   case PotentiallyEvaluated:
14575   case PotentiallyEvaluatedIfUsed:
14576     if (Statement && getCurFunctionOrMethodDecl()) {
14577       FunctionScopes.back()->PossiblyUnreachableDiags.
14578         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14579     }
14580     else
14581       Diag(Loc, PD);
14582 
14583     return true;
14584   }
14585 
14586   return false;
14587 }
14588 
14589 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14590                                CallExpr *CE, FunctionDecl *FD) {
14591   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14592     return false;
14593 
14594   // If we're inside a decltype's expression, don't check for a valid return
14595   // type or construct temporaries until we know whether this is the last call.
14596   if (ExprEvalContexts.back().IsDecltype) {
14597     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14598     return false;
14599   }
14600 
14601   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14602     FunctionDecl *FD;
14603     CallExpr *CE;
14604 
14605   public:
14606     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14607       : FD(FD), CE(CE) { }
14608 
14609     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14610       if (!FD) {
14611         S.Diag(Loc, diag::err_call_incomplete_return)
14612           << T << CE->getSourceRange();
14613         return;
14614       }
14615 
14616       S.Diag(Loc, diag::err_call_function_incomplete_return)
14617         << CE->getSourceRange() << FD->getDeclName() << T;
14618       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14619           << FD->getDeclName();
14620     }
14621   } Diagnoser(FD, CE);
14622 
14623   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14624     return true;
14625 
14626   return false;
14627 }
14628 
14629 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14630 // will prevent this condition from triggering, which is what we want.
14631 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14632   SourceLocation Loc;
14633 
14634   unsigned diagnostic = diag::warn_condition_is_assignment;
14635   bool IsOrAssign = false;
14636 
14637   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14638     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14639       return;
14640 
14641     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14642 
14643     // Greylist some idioms by putting them into a warning subcategory.
14644     if (ObjCMessageExpr *ME
14645           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14646       Selector Sel = ME->getSelector();
14647 
14648       // self = [<foo> init...]
14649       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14650         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14651 
14652       // <foo> = [<bar> nextObject]
14653       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14654         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14655     }
14656 
14657     Loc = Op->getOperatorLoc();
14658   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14659     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14660       return;
14661 
14662     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14663     Loc = Op->getOperatorLoc();
14664   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14665     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14666   else {
14667     // Not an assignment.
14668     return;
14669   }
14670 
14671   Diag(Loc, diagnostic) << E->getSourceRange();
14672 
14673   SourceLocation Open = E->getLocStart();
14674   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14675   Diag(Loc, diag::note_condition_assign_silence)
14676         << FixItHint::CreateInsertion(Open, "(")
14677         << FixItHint::CreateInsertion(Close, ")");
14678 
14679   if (IsOrAssign)
14680     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14681       << FixItHint::CreateReplacement(Loc, "!=");
14682   else
14683     Diag(Loc, diag::note_condition_assign_to_comparison)
14684       << FixItHint::CreateReplacement(Loc, "==");
14685 }
14686 
14687 /// \brief Redundant parentheses over an equality comparison can indicate
14688 /// that the user intended an assignment used as condition.
14689 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14690   // Don't warn if the parens came from a macro.
14691   SourceLocation parenLoc = ParenE->getLocStart();
14692   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14693     return;
14694   // Don't warn for dependent expressions.
14695   if (ParenE->isTypeDependent())
14696     return;
14697 
14698   Expr *E = ParenE->IgnoreParens();
14699 
14700   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14701     if (opE->getOpcode() == BO_EQ &&
14702         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14703                                                            == Expr::MLV_Valid) {
14704       SourceLocation Loc = opE->getOperatorLoc();
14705 
14706       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14707       SourceRange ParenERange = ParenE->getSourceRange();
14708       Diag(Loc, diag::note_equality_comparison_silence)
14709         << FixItHint::CreateRemoval(ParenERange.getBegin())
14710         << FixItHint::CreateRemoval(ParenERange.getEnd());
14711       Diag(Loc, diag::note_equality_comparison_to_assign)
14712         << FixItHint::CreateReplacement(Loc, "=");
14713     }
14714 }
14715 
14716 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14717                                        bool IsConstexpr) {
14718   DiagnoseAssignmentAsCondition(E);
14719   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14720     DiagnoseEqualityWithExtraParens(parenE);
14721 
14722   ExprResult result = CheckPlaceholderExpr(E);
14723   if (result.isInvalid()) return ExprError();
14724   E = result.get();
14725 
14726   if (!E->isTypeDependent()) {
14727     if (getLangOpts().CPlusPlus)
14728       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14729 
14730     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14731     if (ERes.isInvalid())
14732       return ExprError();
14733     E = ERes.get();
14734 
14735     QualType T = E->getType();
14736     if (!T->isScalarType()) { // C99 6.8.4.1p1
14737       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14738         << T << E->getSourceRange();
14739       return ExprError();
14740     }
14741     CheckBoolLikeConversion(E, Loc);
14742   }
14743 
14744   return E;
14745 }
14746 
14747 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14748                                            Expr *SubExpr, ConditionKind CK) {
14749   // Empty conditions are valid in for-statements.
14750   if (!SubExpr)
14751     return ConditionResult();
14752 
14753   ExprResult Cond;
14754   switch (CK) {
14755   case ConditionKind::Boolean:
14756     Cond = CheckBooleanCondition(Loc, SubExpr);
14757     break;
14758 
14759   case ConditionKind::ConstexprIf:
14760     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14761     break;
14762 
14763   case ConditionKind::Switch:
14764     Cond = CheckSwitchCondition(Loc, SubExpr);
14765     break;
14766   }
14767   if (Cond.isInvalid())
14768     return ConditionError();
14769 
14770   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14771   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14772   if (!FullExpr.get())
14773     return ConditionError();
14774 
14775   return ConditionResult(*this, nullptr, FullExpr,
14776                          CK == ConditionKind::ConstexprIf);
14777 }
14778 
14779 namespace {
14780   /// A visitor for rebuilding a call to an __unknown_any expression
14781   /// to have an appropriate type.
14782   struct RebuildUnknownAnyFunction
14783     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14784 
14785     Sema &S;
14786 
14787     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14788 
14789     ExprResult VisitStmt(Stmt *S) {
14790       llvm_unreachable("unexpected statement!");
14791     }
14792 
14793     ExprResult VisitExpr(Expr *E) {
14794       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14795         << E->getSourceRange();
14796       return ExprError();
14797     }
14798 
14799     /// Rebuild an expression which simply semantically wraps another
14800     /// expression which it shares the type and value kind of.
14801     template <class T> ExprResult rebuildSugarExpr(T *E) {
14802       ExprResult SubResult = Visit(E->getSubExpr());
14803       if (SubResult.isInvalid()) return ExprError();
14804 
14805       Expr *SubExpr = SubResult.get();
14806       E->setSubExpr(SubExpr);
14807       E->setType(SubExpr->getType());
14808       E->setValueKind(SubExpr->getValueKind());
14809       assert(E->getObjectKind() == OK_Ordinary);
14810       return E;
14811     }
14812 
14813     ExprResult VisitParenExpr(ParenExpr *E) {
14814       return rebuildSugarExpr(E);
14815     }
14816 
14817     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14818       return rebuildSugarExpr(E);
14819     }
14820 
14821     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14822       ExprResult SubResult = Visit(E->getSubExpr());
14823       if (SubResult.isInvalid()) return ExprError();
14824 
14825       Expr *SubExpr = SubResult.get();
14826       E->setSubExpr(SubExpr);
14827       E->setType(S.Context.getPointerType(SubExpr->getType()));
14828       assert(E->getValueKind() == VK_RValue);
14829       assert(E->getObjectKind() == OK_Ordinary);
14830       return E;
14831     }
14832 
14833     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14834       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14835 
14836       E->setType(VD->getType());
14837 
14838       assert(E->getValueKind() == VK_RValue);
14839       if (S.getLangOpts().CPlusPlus &&
14840           !(isa<CXXMethodDecl>(VD) &&
14841             cast<CXXMethodDecl>(VD)->isInstance()))
14842         E->setValueKind(VK_LValue);
14843 
14844       return E;
14845     }
14846 
14847     ExprResult VisitMemberExpr(MemberExpr *E) {
14848       return resolveDecl(E, E->getMemberDecl());
14849     }
14850 
14851     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14852       return resolveDecl(E, E->getDecl());
14853     }
14854   };
14855 }
14856 
14857 /// Given a function expression of unknown-any type, try to rebuild it
14858 /// to have a function type.
14859 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14860   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14861   if (Result.isInvalid()) return ExprError();
14862   return S.DefaultFunctionArrayConversion(Result.get());
14863 }
14864 
14865 namespace {
14866   /// A visitor for rebuilding an expression of type __unknown_anytype
14867   /// into one which resolves the type directly on the referring
14868   /// expression.  Strict preservation of the original source
14869   /// structure is not a goal.
14870   struct RebuildUnknownAnyExpr
14871     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14872 
14873     Sema &S;
14874 
14875     /// The current destination type.
14876     QualType DestType;
14877 
14878     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14879       : S(S), DestType(CastType) {}
14880 
14881     ExprResult VisitStmt(Stmt *S) {
14882       llvm_unreachable("unexpected statement!");
14883     }
14884 
14885     ExprResult VisitExpr(Expr *E) {
14886       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14887         << E->getSourceRange();
14888       return ExprError();
14889     }
14890 
14891     ExprResult VisitCallExpr(CallExpr *E);
14892     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14893 
14894     /// Rebuild an expression which simply semantically wraps another
14895     /// expression which it shares the type and value kind of.
14896     template <class T> ExprResult rebuildSugarExpr(T *E) {
14897       ExprResult SubResult = Visit(E->getSubExpr());
14898       if (SubResult.isInvalid()) return ExprError();
14899       Expr *SubExpr = SubResult.get();
14900       E->setSubExpr(SubExpr);
14901       E->setType(SubExpr->getType());
14902       E->setValueKind(SubExpr->getValueKind());
14903       assert(E->getObjectKind() == OK_Ordinary);
14904       return E;
14905     }
14906 
14907     ExprResult VisitParenExpr(ParenExpr *E) {
14908       return rebuildSugarExpr(E);
14909     }
14910 
14911     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14912       return rebuildSugarExpr(E);
14913     }
14914 
14915     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14916       const PointerType *Ptr = DestType->getAs<PointerType>();
14917       if (!Ptr) {
14918         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14919           << E->getSourceRange();
14920         return ExprError();
14921       }
14922 
14923       if (isa<CallExpr>(E->getSubExpr())) {
14924         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14925           << E->getSourceRange();
14926         return ExprError();
14927       }
14928 
14929       assert(E->getValueKind() == VK_RValue);
14930       assert(E->getObjectKind() == OK_Ordinary);
14931       E->setType(DestType);
14932 
14933       // Build the sub-expression as if it were an object of the pointee type.
14934       DestType = Ptr->getPointeeType();
14935       ExprResult SubResult = Visit(E->getSubExpr());
14936       if (SubResult.isInvalid()) return ExprError();
14937       E->setSubExpr(SubResult.get());
14938       return E;
14939     }
14940 
14941     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14942 
14943     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14944 
14945     ExprResult VisitMemberExpr(MemberExpr *E) {
14946       return resolveDecl(E, E->getMemberDecl());
14947     }
14948 
14949     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14950       return resolveDecl(E, E->getDecl());
14951     }
14952   };
14953 }
14954 
14955 /// Rebuilds a call expression which yielded __unknown_anytype.
14956 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14957   Expr *CalleeExpr = E->getCallee();
14958 
14959   enum FnKind {
14960     FK_MemberFunction,
14961     FK_FunctionPointer,
14962     FK_BlockPointer
14963   };
14964 
14965   FnKind Kind;
14966   QualType CalleeType = CalleeExpr->getType();
14967   if (CalleeType == S.Context.BoundMemberTy) {
14968     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14969     Kind = FK_MemberFunction;
14970     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14971   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14972     CalleeType = Ptr->getPointeeType();
14973     Kind = FK_FunctionPointer;
14974   } else {
14975     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14976     Kind = FK_BlockPointer;
14977   }
14978   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14979 
14980   // Verify that this is a legal result type of a function.
14981   if (DestType->isArrayType() || DestType->isFunctionType()) {
14982     unsigned diagID = diag::err_func_returning_array_function;
14983     if (Kind == FK_BlockPointer)
14984       diagID = diag::err_block_returning_array_function;
14985 
14986     S.Diag(E->getExprLoc(), diagID)
14987       << DestType->isFunctionType() << DestType;
14988     return ExprError();
14989   }
14990 
14991   // Otherwise, go ahead and set DestType as the call's result.
14992   E->setType(DestType.getNonLValueExprType(S.Context));
14993   E->setValueKind(Expr::getValueKindForType(DestType));
14994   assert(E->getObjectKind() == OK_Ordinary);
14995 
14996   // Rebuild the function type, replacing the result type with DestType.
14997   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14998   if (Proto) {
14999     // __unknown_anytype(...) is a special case used by the debugger when
15000     // it has no idea what a function's signature is.
15001     //
15002     // We want to build this call essentially under the K&R
15003     // unprototyped rules, but making a FunctionNoProtoType in C++
15004     // would foul up all sorts of assumptions.  However, we cannot
15005     // simply pass all arguments as variadic arguments, nor can we
15006     // portably just call the function under a non-variadic type; see
15007     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15008     // However, it turns out that in practice it is generally safe to
15009     // call a function declared as "A foo(B,C,D);" under the prototype
15010     // "A foo(B,C,D,...);".  The only known exception is with the
15011     // Windows ABI, where any variadic function is implicitly cdecl
15012     // regardless of its normal CC.  Therefore we change the parameter
15013     // types to match the types of the arguments.
15014     //
15015     // This is a hack, but it is far superior to moving the
15016     // corresponding target-specific code from IR-gen to Sema/AST.
15017 
15018     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15019     SmallVector<QualType, 8> ArgTypes;
15020     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15021       ArgTypes.reserve(E->getNumArgs());
15022       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15023         Expr *Arg = E->getArg(i);
15024         QualType ArgType = Arg->getType();
15025         if (E->isLValue()) {
15026           ArgType = S.Context.getLValueReferenceType(ArgType);
15027         } else if (E->isXValue()) {
15028           ArgType = S.Context.getRValueReferenceType(ArgType);
15029         }
15030         ArgTypes.push_back(ArgType);
15031       }
15032       ParamTypes = ArgTypes;
15033     }
15034     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15035                                          Proto->getExtProtoInfo());
15036   } else {
15037     DestType = S.Context.getFunctionNoProtoType(DestType,
15038                                                 FnType->getExtInfo());
15039   }
15040 
15041   // Rebuild the appropriate pointer-to-function type.
15042   switch (Kind) {
15043   case FK_MemberFunction:
15044     // Nothing to do.
15045     break;
15046 
15047   case FK_FunctionPointer:
15048     DestType = S.Context.getPointerType(DestType);
15049     break;
15050 
15051   case FK_BlockPointer:
15052     DestType = S.Context.getBlockPointerType(DestType);
15053     break;
15054   }
15055 
15056   // Finally, we can recurse.
15057   ExprResult CalleeResult = Visit(CalleeExpr);
15058   if (!CalleeResult.isUsable()) return ExprError();
15059   E->setCallee(CalleeResult.get());
15060 
15061   // Bind a temporary if necessary.
15062   return S.MaybeBindToTemporary(E);
15063 }
15064 
15065 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15066   // Verify that this is a legal result type of a call.
15067   if (DestType->isArrayType() || DestType->isFunctionType()) {
15068     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15069       << DestType->isFunctionType() << DestType;
15070     return ExprError();
15071   }
15072 
15073   // Rewrite the method result type if available.
15074   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15075     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15076     Method->setReturnType(DestType);
15077   }
15078 
15079   // Change the type of the message.
15080   E->setType(DestType.getNonReferenceType());
15081   E->setValueKind(Expr::getValueKindForType(DestType));
15082 
15083   return S.MaybeBindToTemporary(E);
15084 }
15085 
15086 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15087   // The only case we should ever see here is a function-to-pointer decay.
15088   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15089     assert(E->getValueKind() == VK_RValue);
15090     assert(E->getObjectKind() == OK_Ordinary);
15091 
15092     E->setType(DestType);
15093 
15094     // Rebuild the sub-expression as the pointee (function) type.
15095     DestType = DestType->castAs<PointerType>()->getPointeeType();
15096 
15097     ExprResult Result = Visit(E->getSubExpr());
15098     if (!Result.isUsable()) return ExprError();
15099 
15100     E->setSubExpr(Result.get());
15101     return E;
15102   } else if (E->getCastKind() == CK_LValueToRValue) {
15103     assert(E->getValueKind() == VK_RValue);
15104     assert(E->getObjectKind() == OK_Ordinary);
15105 
15106     assert(isa<BlockPointerType>(E->getType()));
15107 
15108     E->setType(DestType);
15109 
15110     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15111     DestType = S.Context.getLValueReferenceType(DestType);
15112 
15113     ExprResult Result = Visit(E->getSubExpr());
15114     if (!Result.isUsable()) return ExprError();
15115 
15116     E->setSubExpr(Result.get());
15117     return E;
15118   } else {
15119     llvm_unreachable("Unhandled cast type!");
15120   }
15121 }
15122 
15123 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15124   ExprValueKind ValueKind = VK_LValue;
15125   QualType Type = DestType;
15126 
15127   // We know how to make this work for certain kinds of decls:
15128 
15129   //  - functions
15130   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15131     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15132       DestType = Ptr->getPointeeType();
15133       ExprResult Result = resolveDecl(E, VD);
15134       if (Result.isInvalid()) return ExprError();
15135       return S.ImpCastExprToType(Result.get(), Type,
15136                                  CK_FunctionToPointerDecay, VK_RValue);
15137     }
15138 
15139     if (!Type->isFunctionType()) {
15140       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15141         << VD << E->getSourceRange();
15142       return ExprError();
15143     }
15144     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15145       // We must match the FunctionDecl's type to the hack introduced in
15146       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15147       // type. See the lengthy commentary in that routine.
15148       QualType FDT = FD->getType();
15149       const FunctionType *FnType = FDT->castAs<FunctionType>();
15150       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15151       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15152       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15153         SourceLocation Loc = FD->getLocation();
15154         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15155                                       FD->getDeclContext(),
15156                                       Loc, Loc, FD->getNameInfo().getName(),
15157                                       DestType, FD->getTypeSourceInfo(),
15158                                       SC_None, false/*isInlineSpecified*/,
15159                                       FD->hasPrototype(),
15160                                       false/*isConstexprSpecified*/);
15161 
15162         if (FD->getQualifier())
15163           NewFD->setQualifierInfo(FD->getQualifierLoc());
15164 
15165         SmallVector<ParmVarDecl*, 16> Params;
15166         for (const auto &AI : FT->param_types()) {
15167           ParmVarDecl *Param =
15168             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15169           Param->setScopeInfo(0, Params.size());
15170           Params.push_back(Param);
15171         }
15172         NewFD->setParams(Params);
15173         DRE->setDecl(NewFD);
15174         VD = DRE->getDecl();
15175       }
15176     }
15177 
15178     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15179       if (MD->isInstance()) {
15180         ValueKind = VK_RValue;
15181         Type = S.Context.BoundMemberTy;
15182       }
15183 
15184     // Function references aren't l-values in C.
15185     if (!S.getLangOpts().CPlusPlus)
15186       ValueKind = VK_RValue;
15187 
15188   //  - variables
15189   } else if (isa<VarDecl>(VD)) {
15190     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15191       Type = RefTy->getPointeeType();
15192     } else if (Type->isFunctionType()) {
15193       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15194         << VD << E->getSourceRange();
15195       return ExprError();
15196     }
15197 
15198   //  - nothing else
15199   } else {
15200     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15201       << VD << E->getSourceRange();
15202     return ExprError();
15203   }
15204 
15205   // Modifying the declaration like this is friendly to IR-gen but
15206   // also really dangerous.
15207   VD->setType(DestType);
15208   E->setType(Type);
15209   E->setValueKind(ValueKind);
15210   return E;
15211 }
15212 
15213 /// Check a cast of an unknown-any type.  We intentionally only
15214 /// trigger this for C-style casts.
15215 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15216                                      Expr *CastExpr, CastKind &CastKind,
15217                                      ExprValueKind &VK, CXXCastPath &Path) {
15218   // The type we're casting to must be either void or complete.
15219   if (!CastType->isVoidType() &&
15220       RequireCompleteType(TypeRange.getBegin(), CastType,
15221                           diag::err_typecheck_cast_to_incomplete))
15222     return ExprError();
15223 
15224   // Rewrite the casted expression from scratch.
15225   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15226   if (!result.isUsable()) return ExprError();
15227 
15228   CastExpr = result.get();
15229   VK = CastExpr->getValueKind();
15230   CastKind = CK_NoOp;
15231 
15232   return CastExpr;
15233 }
15234 
15235 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15236   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15237 }
15238 
15239 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15240                                     Expr *arg, QualType &paramType) {
15241   // If the syntactic form of the argument is not an explicit cast of
15242   // any sort, just do default argument promotion.
15243   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15244   if (!castArg) {
15245     ExprResult result = DefaultArgumentPromotion(arg);
15246     if (result.isInvalid()) return ExprError();
15247     paramType = result.get()->getType();
15248     return result;
15249   }
15250 
15251   // Otherwise, use the type that was written in the explicit cast.
15252   assert(!arg->hasPlaceholderType());
15253   paramType = castArg->getTypeAsWritten();
15254 
15255   // Copy-initialize a parameter of that type.
15256   InitializedEntity entity =
15257     InitializedEntity::InitializeParameter(Context, paramType,
15258                                            /*consumed*/ false);
15259   return PerformCopyInitialization(entity, callLoc, arg);
15260 }
15261 
15262 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15263   Expr *orig = E;
15264   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15265   while (true) {
15266     E = E->IgnoreParenImpCasts();
15267     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15268       E = call->getCallee();
15269       diagID = diag::err_uncasted_call_of_unknown_any;
15270     } else {
15271       break;
15272     }
15273   }
15274 
15275   SourceLocation loc;
15276   NamedDecl *d;
15277   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15278     loc = ref->getLocation();
15279     d = ref->getDecl();
15280   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15281     loc = mem->getMemberLoc();
15282     d = mem->getMemberDecl();
15283   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15284     diagID = diag::err_uncasted_call_of_unknown_any;
15285     loc = msg->getSelectorStartLoc();
15286     d = msg->getMethodDecl();
15287     if (!d) {
15288       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15289         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15290         << orig->getSourceRange();
15291       return ExprError();
15292     }
15293   } else {
15294     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15295       << E->getSourceRange();
15296     return ExprError();
15297   }
15298 
15299   S.Diag(loc, diagID) << d << orig->getSourceRange();
15300 
15301   // Never recoverable.
15302   return ExprError();
15303 }
15304 
15305 /// Check for operands with placeholder types and complain if found.
15306 /// Returns true if there was an error and no recovery was possible.
15307 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15308   if (!getLangOpts().CPlusPlus) {
15309     // C cannot handle TypoExpr nodes on either side of a binop because it
15310     // doesn't handle dependent types properly, so make sure any TypoExprs have
15311     // been dealt with before checking the operands.
15312     ExprResult Result = CorrectDelayedTyposInExpr(E);
15313     if (!Result.isUsable()) return ExprError();
15314     E = Result.get();
15315   }
15316 
15317   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15318   if (!placeholderType) return E;
15319 
15320   switch (placeholderType->getKind()) {
15321 
15322   // Overloaded expressions.
15323   case BuiltinType::Overload: {
15324     // Try to resolve a single function template specialization.
15325     // This is obligatory.
15326     ExprResult Result = E;
15327     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15328       return Result;
15329 
15330     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15331     // leaves Result unchanged on failure.
15332     Result = E;
15333     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15334       return Result;
15335 
15336     // If that failed, try to recover with a call.
15337     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15338                          /*complain*/ true);
15339     return Result;
15340   }
15341 
15342   // Bound member functions.
15343   case BuiltinType::BoundMember: {
15344     ExprResult result = E;
15345     const Expr *BME = E->IgnoreParens();
15346     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15347     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15348     if (isa<CXXPseudoDestructorExpr>(BME)) {
15349       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15350     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15351       if (ME->getMemberNameInfo().getName().getNameKind() ==
15352           DeclarationName::CXXDestructorName)
15353         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15354     }
15355     tryToRecoverWithCall(result, PD,
15356                          /*complain*/ true);
15357     return result;
15358   }
15359 
15360   // ARC unbridged casts.
15361   case BuiltinType::ARCUnbridgedCast: {
15362     Expr *realCast = stripARCUnbridgedCast(E);
15363     diagnoseARCUnbridgedCast(realCast);
15364     return realCast;
15365   }
15366 
15367   // Expressions of unknown type.
15368   case BuiltinType::UnknownAny:
15369     return diagnoseUnknownAnyExpr(*this, E);
15370 
15371   // Pseudo-objects.
15372   case BuiltinType::PseudoObject:
15373     return checkPseudoObjectRValue(E);
15374 
15375   case BuiltinType::BuiltinFn: {
15376     // Accept __noop without parens by implicitly converting it to a call expr.
15377     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15378     if (DRE) {
15379       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15380       if (FD->getBuiltinID() == Builtin::BI__noop) {
15381         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15382                               CK_BuiltinFnToFnPtr).get();
15383         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15384                                       VK_RValue, SourceLocation());
15385       }
15386     }
15387 
15388     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15389     return ExprError();
15390   }
15391 
15392   // Expressions of unknown type.
15393   case BuiltinType::OMPArraySection:
15394     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15395     return ExprError();
15396 
15397   // Everything else should be impossible.
15398 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15399   case BuiltinType::Id:
15400 #include "clang/Basic/OpenCLImageTypes.def"
15401 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15402 #define PLACEHOLDER_TYPE(Id, SingletonId)
15403 #include "clang/AST/BuiltinTypes.def"
15404     break;
15405   }
15406 
15407   llvm_unreachable("invalid placeholder type!");
15408 }
15409 
15410 bool Sema::CheckCaseExpression(Expr *E) {
15411   if (E->isTypeDependent())
15412     return true;
15413   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15414     return E->getType()->isIntegralOrEnumerationType();
15415   return false;
15416 }
15417 
15418 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15419 ExprResult
15420 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15421   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15422          "Unknown Objective-C Boolean value!");
15423   QualType BoolT = Context.ObjCBuiltinBoolTy;
15424   if (!Context.getBOOLDecl()) {
15425     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15426                         Sema::LookupOrdinaryName);
15427     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15428       NamedDecl *ND = Result.getFoundDecl();
15429       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15430         Context.setBOOLDecl(TD);
15431     }
15432   }
15433   if (Context.getBOOLDecl())
15434     BoolT = Context.getBOOLType();
15435   return new (Context)
15436       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15437 }
15438 
15439 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15440     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15441     SourceLocation RParen) {
15442 
15443   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15444 
15445   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15446                            [&](const AvailabilitySpec &Spec) {
15447                              return Spec.getPlatform() == Platform;
15448                            });
15449 
15450   VersionTuple Version;
15451   if (Spec != AvailSpecs.end())
15452     Version = Spec->getVersion();
15453 
15454   return new (Context)
15455       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15456 }
15457