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       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337 
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343 
344   // See if this is a deleted function.
345   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     if (FD->isDeleted()) {
347       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348       if (Ctor && Ctor->isInheritingConstructor())
349         Diag(Loc, diag::err_deleted_inherited_ctor_use)
350             << Ctor->getParent()
351             << Ctor->getInheritedConstructor().getConstructor()->getParent();
352       else
353         Diag(Loc, diag::err_deleted_function_use);
354       NoteDeletedFunction(FD);
355       return true;
356     }
357 
358     // If the function has a deduced return type, and we can't deduce it,
359     // then we can't use it either.
360     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361         DeduceReturnType(FD, Loc))
362       return true;
363 
364     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365       return true;
366 
367     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
368       return true;
369   }
370 
371   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372   // Only the variables omp_in and omp_out are allowed in the combiner.
373   // Only the variables omp_priv and omp_orig are allowed in the
374   // initializer-clause.
375   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
377       isa<VarDecl>(D)) {
378     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379         << getCurFunction()->HasOMPDeclareReductionCombiner;
380     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
381     return true;
382   }
383 
384   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
385                              ObjCPropertyAccess);
386 
387   DiagnoseUnusedOfDecl(*this, D, Loc);
388 
389   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
390 
391   return false;
392 }
393 
394 /// \brief Retrieve the message suffix that should be added to a
395 /// diagnostic complaining about the given function being deleted or
396 /// unavailable.
397 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
398   std::string Message;
399   if (FD->getAvailability(&Message))
400     return ": " + Message;
401 
402   return std::string();
403 }
404 
405 /// DiagnoseSentinelCalls - This routine checks whether a call or
406 /// message-send is to a declaration with the sentinel attribute, and
407 /// if so, it checks that the requirements of the sentinel are
408 /// satisfied.
409 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
410                                  ArrayRef<Expr *> Args) {
411   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
412   if (!attr)
413     return;
414 
415   // The number of formal parameters of the declaration.
416   unsigned numFormalParams;
417 
418   // The kind of declaration.  This is also an index into a %select in
419   // the diagnostic.
420   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
421 
422   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
423     numFormalParams = MD->param_size();
424     calleeType = CT_Method;
425   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
426     numFormalParams = FD->param_size();
427     calleeType = CT_Function;
428   } else if (isa<VarDecl>(D)) {
429     QualType type = cast<ValueDecl>(D)->getType();
430     const FunctionType *fn = nullptr;
431     if (const PointerType *ptr = type->getAs<PointerType>()) {
432       fn = ptr->getPointeeType()->getAs<FunctionType>();
433       if (!fn) return;
434       calleeType = CT_Function;
435     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
436       fn = ptr->getPointeeType()->castAs<FunctionType>();
437       calleeType = CT_Block;
438     } else {
439       return;
440     }
441 
442     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
443       numFormalParams = proto->getNumParams();
444     } else {
445       numFormalParams = 0;
446     }
447   } else {
448     return;
449   }
450 
451   // "nullPos" is the number of formal parameters at the end which
452   // effectively count as part of the variadic arguments.  This is
453   // useful if you would prefer to not have *any* formal parameters,
454   // but the language forces you to have at least one.
455   unsigned nullPos = attr->getNullPos();
456   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
457   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
458 
459   // The number of arguments which should follow the sentinel.
460   unsigned numArgsAfterSentinel = attr->getSentinel();
461 
462   // If there aren't enough arguments for all the formal parameters,
463   // the sentinel, and the args after the sentinel, complain.
464   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
465     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
466     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
467     return;
468   }
469 
470   // Otherwise, find the sentinel expression.
471   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
472   if (!sentinelExpr) return;
473   if (sentinelExpr->isValueDependent()) return;
474   if (Context.isSentinelNullExpr(sentinelExpr)) return;
475 
476   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
477   // or 'NULL' if those are actually defined in the context.  Only use
478   // 'nil' for ObjC methods, where it's much more likely that the
479   // variadic arguments form a list of object pointers.
480   SourceLocation MissingNilLoc
481     = getLocForEndOfToken(sentinelExpr->getLocEnd());
482   std::string NullValue;
483   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
484     NullValue = "nil";
485   else if (getLangOpts().CPlusPlus11)
486     NullValue = "nullptr";
487   else if (PP.isMacroDefined("NULL"))
488     NullValue = "NULL";
489   else
490     NullValue = "(void*) 0";
491 
492   if (MissingNilLoc.isInvalid())
493     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
494   else
495     Diag(MissingNilLoc, diag::warn_missing_sentinel)
496       << int(calleeType)
497       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
499 }
500 
501 SourceRange Sema::getExprRange(Expr *E) const {
502   return E ? E->getSourceRange() : SourceRange();
503 }
504 
505 //===----------------------------------------------------------------------===//
506 //  Standard Promotions and Conversions
507 //===----------------------------------------------------------------------===//
508 
509 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
511   // Handle any placeholder expressions which made it here.
512   if (E->getType()->isPlaceholderType()) {
513     ExprResult result = CheckPlaceholderExpr(E);
514     if (result.isInvalid()) return ExprError();
515     E = result.get();
516   }
517 
518   QualType Ty = E->getType();
519   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
520 
521   if (Ty->isFunctionType()) {
522     // If we are here, we are not calling a function but taking
523     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
524     if (getLangOpts().OpenCL) {
525       if (Diagnose)
526         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
527       return ExprError();
528     }
529 
530     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
531       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
532         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
533           return ExprError();
534 
535     E = ImpCastExprToType(E, Context.getPointerType(Ty),
536                           CK_FunctionToPointerDecay).get();
537   } else if (Ty->isArrayType()) {
538     // In C90 mode, arrays only promote to pointers if the array expression is
539     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
540     // type 'array of type' is converted to an expression that has type 'pointer
541     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
542     // that has type 'array of type' ...".  The relevant change is "an lvalue"
543     // (C90) to "an expression" (C99).
544     //
545     // C++ 4.2p1:
546     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
547     // T" can be converted to an rvalue of type "pointer to T".
548     //
549     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
550       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
551                             CK_ArrayToPointerDecay).get();
552   }
553   return E;
554 }
555 
556 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
557   // Check to see if we are dereferencing a null pointer.  If so,
558   // and if not volatile-qualified, this is undefined behavior that the
559   // optimizer will delete, so warn about it.  People sometimes try to use this
560   // to get a deterministic trap and are surprised by clang's behavior.  This
561   // only handles the pattern "*null", which is a very syntactic check.
562   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
563     if (UO->getOpcode() == UO_Deref &&
564         UO->getSubExpr()->IgnoreParenCasts()->
565           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
566         !UO->getType().isVolatileQualified()) {
567     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568                           S.PDiag(diag::warn_indirection_through_null)
569                             << UO->getSubExpr()->getSourceRange());
570     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571                         S.PDiag(diag::note_indirection_through_null));
572   }
573 }
574 
575 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
576                                     SourceLocation AssignLoc,
577                                     const Expr* RHS) {
578   const ObjCIvarDecl *IV = OIRE->getDecl();
579   if (!IV)
580     return;
581 
582   DeclarationName MemberName = IV->getDeclName();
583   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
584   if (!Member || !Member->isStr("isa"))
585     return;
586 
587   const Expr *Base = OIRE->getBase();
588   QualType BaseType = Base->getType();
589   if (OIRE->isArrow())
590     BaseType = BaseType->getPointeeType();
591   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
592     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
593       ObjCInterfaceDecl *ClassDeclared = nullptr;
594       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
595       if (!ClassDeclared->getSuperClass()
596           && (*ClassDeclared->ivar_begin()) == IV) {
597         if (RHS) {
598           NamedDecl *ObjectSetClass =
599             S.LookupSingleName(S.TUScope,
600                                &S.Context.Idents.get("object_setClass"),
601                                SourceLocation(), S.LookupOrdinaryName);
602           if (ObjectSetClass) {
603             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
604             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
605             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
606             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
607                                                      AssignLoc), ",") <<
608             FixItHint::CreateInsertion(RHSLocEnd, ")");
609           }
610           else
611             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
612         } else {
613           NamedDecl *ObjectGetClass =
614             S.LookupSingleName(S.TUScope,
615                                &S.Context.Idents.get("object_getClass"),
616                                SourceLocation(), S.LookupOrdinaryName);
617           if (ObjectGetClass)
618             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
619             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
620             FixItHint::CreateReplacement(
621                                          SourceRange(OIRE->getOpLoc(),
622                                                      OIRE->getLocEnd()), ")");
623           else
624             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
625         }
626         S.Diag(IV->getLocation(), diag::note_ivar_decl);
627       }
628     }
629 }
630 
631 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
632   // Handle any placeholder expressions which made it here.
633   if (E->getType()->isPlaceholderType()) {
634     ExprResult result = CheckPlaceholderExpr(E);
635     if (result.isInvalid()) return ExprError();
636     E = result.get();
637   }
638 
639   // C++ [conv.lval]p1:
640   //   A glvalue of a non-function, non-array type T can be
641   //   converted to a prvalue.
642   if (!E->isGLValue()) return E;
643 
644   QualType T = E->getType();
645   assert(!T.isNull() && "r-value conversion on typeless expression?");
646 
647   // We don't want to throw lvalue-to-rvalue casts on top of
648   // expressions of certain types in C++.
649   if (getLangOpts().CPlusPlus &&
650       (E->getType() == Context.OverloadTy ||
651        T->isDependentType() ||
652        T->isRecordType()))
653     return E;
654 
655   // The C standard is actually really unclear on this point, and
656   // DR106 tells us what the result should be but not why.  It's
657   // generally best to say that void types just doesn't undergo
658   // lvalue-to-rvalue at all.  Note that expressions of unqualified
659   // 'void' type are never l-values, but qualified void can be.
660   if (T->isVoidType())
661     return E;
662 
663   // OpenCL usually rejects direct accesses to values of 'half' type.
664   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
665       T->isHalfType()) {
666     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667       << 0 << T;
668     return ExprError();
669   }
670 
671   CheckForNullPointerDereference(*this, E);
672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674                                      &Context.Idents.get("object_getClass"),
675                                      SourceLocation(), LookupOrdinaryName);
676     if (ObjectGetClass)
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
678         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
679         FixItHint::CreateReplacement(
680                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681     else
682       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683   }
684   else if (const ObjCIvarRefExpr *OIRE =
685             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687 
688   // C++ [conv.lval]p1:
689   //   [...] If T is a non-class type, the type of the prvalue is the
690   //   cv-unqualified version of T. Otherwise, the type of the
691   //   rvalue is T.
692   //
693   // C99 6.3.2.1p2:
694   //   If the lvalue has qualified type, the value has the unqualified
695   //   version of the type of the lvalue; otherwise, the value has the
696   //   type of the lvalue.
697   if (T.hasQualifiers())
698     T = T.getUnqualifiedType();
699 
700   // Under the MS ABI, lock down the inheritance model now.
701   if (T->isMemberPointerType() &&
702       Context.getTargetInfo().getCXXABI().isMicrosoft())
703     (void)isCompleteType(E->getExprLoc(), T);
704 
705   UpdateMarkingForLValueToRValue(E);
706 
707   // Loading a __weak object implicitly retains the value, so we need a cleanup to
708   // balance that.
709   if (getLangOpts().ObjCAutoRefCount &&
710       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711     Cleanup.setExprNeedsCleanups(true);
712 
713   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
714                                             nullptr, VK_RValue);
715 
716   // C11 6.3.2.1p2:
717   //   ... if the lvalue has atomic type, the value has the non-atomic version
718   //   of the type of the lvalue ...
719   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
720     T = Atomic->getValueType().getUnqualifiedType();
721     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
722                                    nullptr, VK_RValue);
723   }
724 
725   return Res;
726 }
727 
728 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
729   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
730   if (Res.isInvalid())
731     return ExprError();
732   Res = DefaultLvalueConversion(Res.get());
733   if (Res.isInvalid())
734     return ExprError();
735   return Res;
736 }
737 
738 /// CallExprUnaryConversions - a special case of an unary conversion
739 /// performed on a function designator of a call expression.
740 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
741   QualType Ty = E->getType();
742   ExprResult Res = E;
743   // Only do implicit cast for a function type, but not for a pointer
744   // to function type.
745   if (Ty->isFunctionType()) {
746     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
747                             CK_FunctionToPointerDecay).get();
748     if (Res.isInvalid())
749       return ExprError();
750   }
751   Res = DefaultLvalueConversion(Res.get());
752   if (Res.isInvalid())
753     return ExprError();
754   return Res.get();
755 }
756 
757 /// UsualUnaryConversions - Performs various conversions that are common to most
758 /// operators (C99 6.3). The conversions of array and function types are
759 /// sometimes suppressed. For example, the array->pointer conversion doesn't
760 /// apply if the array is an argument to the sizeof or address (&) operators.
761 /// In these instances, this routine should *not* be called.
762 ExprResult Sema::UsualUnaryConversions(Expr *E) {
763   // First, convert to an r-value.
764   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
765   if (Res.isInvalid())
766     return ExprError();
767   E = Res.get();
768 
769   QualType Ty = E->getType();
770   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
771 
772   // Half FP have to be promoted to float unless it is natively supported
773   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
774     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
775 
776   // Try to perform integral promotions if the object has a theoretically
777   // promotable type.
778   if (Ty->isIntegralOrUnscopedEnumerationType()) {
779     // C99 6.3.1.1p2:
780     //
781     //   The following may be used in an expression wherever an int or
782     //   unsigned int may be used:
783     //     - an object or expression with an integer type whose integer
784     //       conversion rank is less than or equal to the rank of int
785     //       and unsigned int.
786     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
787     //
788     //   If an int can represent all values of the original type, the
789     //   value is converted to an int; otherwise, it is converted to an
790     //   unsigned int. These are called the integer promotions. All
791     //   other types are unchanged by the integer promotions.
792 
793     QualType PTy = Context.isPromotableBitField(E);
794     if (!PTy.isNull()) {
795       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
796       return E;
797     }
798     if (Ty->isPromotableIntegerType()) {
799       QualType PT = Context.getPromotedIntegerType(Ty);
800       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
801       return E;
802     }
803   }
804   return E;
805 }
806 
807 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
808 /// do not have a prototype. Arguments that have type float or __fp16
809 /// are promoted to double. All other argument types are converted by
810 /// UsualUnaryConversions().
811 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
812   QualType Ty = E->getType();
813   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
814 
815   ExprResult Res = UsualUnaryConversions(E);
816   if (Res.isInvalid())
817     return ExprError();
818   E = Res.get();
819 
820   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
821   // double.
822   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
823   if (BTy && (BTy->getKind() == BuiltinType::Half ||
824               BTy->getKind() == BuiltinType::Float)) {
825     if (getLangOpts().OpenCL &&
826         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
827         if (BTy->getKind() == BuiltinType::Half) {
828             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
829         }
830     } else {
831       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
832     }
833   }
834 
835   // C++ performs lvalue-to-rvalue conversion as a default argument
836   // promotion, even on class types, but note:
837   //   C++11 [conv.lval]p2:
838   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
839   //     operand or a subexpression thereof the value contained in the
840   //     referenced object is not accessed. Otherwise, if the glvalue
841   //     has a class type, the conversion copy-initializes a temporary
842   //     of type T from the glvalue and the result of the conversion
843   //     is a prvalue for the temporary.
844   // FIXME: add some way to gate this entire thing for correctness in
845   // potentially potentially evaluated contexts.
846   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
847     ExprResult Temp = PerformCopyInitialization(
848                        InitializedEntity::InitializeTemporary(E->getType()),
849                                                 E->getExprLoc(), E);
850     if (Temp.isInvalid())
851       return ExprError();
852     E = Temp.get();
853   }
854 
855   return E;
856 }
857 
858 /// Determine the degree of POD-ness for an expression.
859 /// Incomplete types are considered POD, since this check can be performed
860 /// when we're in an unevaluated context.
861 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
862   if (Ty->isIncompleteType()) {
863     // C++11 [expr.call]p7:
864     //   After these conversions, if the argument does not have arithmetic,
865     //   enumeration, pointer, pointer to member, or class type, the program
866     //   is ill-formed.
867     //
868     // Since we've already performed array-to-pointer and function-to-pointer
869     // decay, the only such type in C++ is cv void. This also handles
870     // initializer lists as variadic arguments.
871     if (Ty->isVoidType())
872       return VAK_Invalid;
873 
874     if (Ty->isObjCObjectType())
875       return VAK_Invalid;
876     return VAK_Valid;
877   }
878 
879   if (Ty.isCXX98PODType(Context))
880     return VAK_Valid;
881 
882   // C++11 [expr.call]p7:
883   //   Passing a potentially-evaluated argument of class type (Clause 9)
884   //   having a non-trivial copy constructor, a non-trivial move constructor,
885   //   or a non-trivial destructor, with no corresponding parameter,
886   //   is conditionally-supported with implementation-defined semantics.
887   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
888     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
889       if (!Record->hasNonTrivialCopyConstructor() &&
890           !Record->hasNonTrivialMoveConstructor() &&
891           !Record->hasNonTrivialDestructor())
892         return VAK_ValidInCXX11;
893 
894   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
895     return VAK_Valid;
896 
897   if (Ty->isObjCObjectType())
898     return VAK_Invalid;
899 
900   if (getLangOpts().MSVCCompat)
901     return VAK_MSVCUndefined;
902 
903   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
904   // permitted to reject them. We should consider doing so.
905   return VAK_Undefined;
906 }
907 
908 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
909   // Don't allow one to pass an Objective-C interface to a vararg.
910   const QualType &Ty = E->getType();
911   VarArgKind VAK = isValidVarArgType(Ty);
912 
913   // Complain about passing non-POD types through varargs.
914   switch (VAK) {
915   case VAK_ValidInCXX11:
916     DiagRuntimeBehavior(
917         E->getLocStart(), nullptr,
918         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
919           << Ty << CT);
920     // Fall through.
921   case VAK_Valid:
922     if (Ty->isRecordType()) {
923       // This is unlikely to be what the user intended. If the class has a
924       // 'c_str' member function, the user probably meant to call that.
925       DiagRuntimeBehavior(E->getLocStart(), nullptr,
926                           PDiag(diag::warn_pass_class_arg_to_vararg)
927                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
928     }
929     break;
930 
931   case VAK_Undefined:
932   case VAK_MSVCUndefined:
933     DiagRuntimeBehavior(
934         E->getLocStart(), nullptr,
935         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
936           << getLangOpts().CPlusPlus11 << Ty << CT);
937     break;
938 
939   case VAK_Invalid:
940     if (Ty->isObjCObjectType())
941       DiagRuntimeBehavior(
942           E->getLocStart(), nullptr,
943           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
944             << Ty << CT);
945     else
946       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
947         << isa<InitListExpr>(E) << Ty << CT;
948     break;
949   }
950 }
951 
952 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
953 /// will create a trap if the resulting type is not a POD type.
954 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
955                                                   FunctionDecl *FDecl) {
956   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
957     // Strip the unbridged-cast placeholder expression off, if applicable.
958     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
959         (CT == VariadicMethod ||
960          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
961       E = stripARCUnbridgedCast(E);
962 
963     // Otherwise, do normal placeholder checking.
964     } else {
965       ExprResult ExprRes = CheckPlaceholderExpr(E);
966       if (ExprRes.isInvalid())
967         return ExprError();
968       E = ExprRes.get();
969     }
970   }
971 
972   ExprResult ExprRes = DefaultArgumentPromotion(E);
973   if (ExprRes.isInvalid())
974     return ExprError();
975   E = ExprRes.get();
976 
977   // Diagnostics regarding non-POD argument types are
978   // emitted along with format string checking in Sema::CheckFunctionCall().
979   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
980     // Turn this into a trap.
981     CXXScopeSpec SS;
982     SourceLocation TemplateKWLoc;
983     UnqualifiedId Name;
984     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
985                        E->getLocStart());
986     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
987                                           Name, true, false);
988     if (TrapFn.isInvalid())
989       return ExprError();
990 
991     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
992                                     E->getLocStart(), None,
993                                     E->getLocEnd());
994     if (Call.isInvalid())
995       return ExprError();
996 
997     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
998                                   Call.get(), E);
999     if (Comma.isInvalid())
1000       return ExprError();
1001     return Comma.get();
1002   }
1003 
1004   if (!getLangOpts().CPlusPlus &&
1005       RequireCompleteType(E->getExprLoc(), E->getType(),
1006                           diag::err_call_incomplete_argument))
1007     return ExprError();
1008 
1009   return E;
1010 }
1011 
1012 /// \brief Converts an integer to complex float type.  Helper function of
1013 /// UsualArithmeticConversions()
1014 ///
1015 /// \return false if the integer expression is an integer type and is
1016 /// successfully converted to the complex type.
1017 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1018                                                   ExprResult &ComplexExpr,
1019                                                   QualType IntTy,
1020                                                   QualType ComplexTy,
1021                                                   bool SkipCast) {
1022   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1023   if (SkipCast) return false;
1024   if (IntTy->isIntegerType()) {
1025     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1026     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_FloatingRealToComplex);
1029   } else {
1030     assert(IntTy->isComplexIntegerType());
1031     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1032                                   CK_IntegralComplexToFloatingComplex);
1033   }
1034   return false;
1035 }
1036 
1037 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1038 /// UsualArithmeticConversions()
1039 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1040                                              ExprResult &RHS, QualType LHSType,
1041                                              QualType RHSType,
1042                                              bool IsCompAssign) {
1043   // if we have an integer operand, the result is the complex type.
1044   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1045                                              /*skipCast*/false))
1046     return LHSType;
1047   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1048                                              /*skipCast*/IsCompAssign))
1049     return RHSType;
1050 
1051   // This handles complex/complex, complex/float, or float/complex.
1052   // When both operands are complex, the shorter operand is converted to the
1053   // type of the longer, and that is the type of the result. This corresponds
1054   // to what is done when combining two real floating-point operands.
1055   // The fun begins when size promotion occur across type domains.
1056   // From H&S 6.3.4: When one operand is complex and the other is a real
1057   // floating-point type, the less precise type is converted, within it's
1058   // real or complex domain, to the precision of the other type. For example,
1059   // when combining a "long double" with a "double _Complex", the
1060   // "double _Complex" is promoted to "long double _Complex".
1061 
1062   // Compute the rank of the two types, regardless of whether they are complex.
1063   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1064 
1065   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1066   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1067   QualType LHSElementType =
1068       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1069   QualType RHSElementType =
1070       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1071 
1072   QualType ResultType = S.Context.getComplexType(LHSElementType);
1073   if (Order < 0) {
1074     // Promote the precision of the LHS if not an assignment.
1075     ResultType = S.Context.getComplexType(RHSElementType);
1076     if (!IsCompAssign) {
1077       if (LHSComplexType)
1078         LHS =
1079             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1080       else
1081         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1082     }
1083   } else if (Order > 0) {
1084     // Promote the precision of the RHS.
1085     if (RHSComplexType)
1086       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1087     else
1088       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1089   }
1090   return ResultType;
1091 }
1092 
1093 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1094 /// of UsualArithmeticConversions()
1095 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1096                                            ExprResult &IntExpr,
1097                                            QualType FloatTy, QualType IntTy,
1098                                            bool ConvertFloat, bool ConvertInt) {
1099   if (IntTy->isIntegerType()) {
1100     if (ConvertInt)
1101       // Convert intExpr to the lhs floating point type.
1102       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1103                                     CK_IntegralToFloating);
1104     return FloatTy;
1105   }
1106 
1107   // Convert both sides to the appropriate complex float.
1108   assert(IntTy->isComplexIntegerType());
1109   QualType result = S.Context.getComplexType(FloatTy);
1110 
1111   // _Complex int -> _Complex float
1112   if (ConvertInt)
1113     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1114                                   CK_IntegralComplexToFloatingComplex);
1115 
1116   // float -> _Complex float
1117   if (ConvertFloat)
1118     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1119                                     CK_FloatingRealToComplex);
1120 
1121   return result;
1122 }
1123 
1124 /// \brief Handle arithmethic conversion with floating point types.  Helper
1125 /// function of UsualArithmeticConversions()
1126 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1127                                       ExprResult &RHS, QualType LHSType,
1128                                       QualType RHSType, bool IsCompAssign) {
1129   bool LHSFloat = LHSType->isRealFloatingType();
1130   bool RHSFloat = RHSType->isRealFloatingType();
1131 
1132   // If we have two real floating types, convert the smaller operand
1133   // to the bigger result.
1134   if (LHSFloat && RHSFloat) {
1135     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1136     if (order > 0) {
1137       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138       return LHSType;
1139     }
1140 
1141     assert(order < 0 && "illegal float comparison");
1142     if (!IsCompAssign)
1143       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1144     return RHSType;
1145   }
1146 
1147   if (LHSFloat) {
1148     // Half FP has to be promoted to float unless it is natively supported
1149     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1150       LHSType = S.Context.FloatTy;
1151 
1152     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153                                       /*convertFloat=*/!IsCompAssign,
1154                                       /*convertInt=*/ true);
1155   }
1156   assert(RHSFloat);
1157   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1158                                     /*convertInt=*/ true,
1159                                     /*convertFloat=*/!IsCompAssign);
1160 }
1161 
1162 /// \brief Diagnose attempts to convert between __float128 and long double if
1163 /// there is no support for such conversion. Helper function of
1164 /// UsualArithmeticConversions().
1165 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1166                                       QualType RHSType) {
1167   /*  No issue converting if at least one of the types is not a floating point
1168       type or the two types have the same rank.
1169   */
1170   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1171       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1172     return false;
1173 
1174   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1175          "The remaining types must be floating point types.");
1176 
1177   auto *LHSComplex = LHSType->getAs<ComplexType>();
1178   auto *RHSComplex = RHSType->getAs<ComplexType>();
1179 
1180   QualType LHSElemType = LHSComplex ?
1181     LHSComplex->getElementType() : LHSType;
1182   QualType RHSElemType = RHSComplex ?
1183     RHSComplex->getElementType() : RHSType;
1184 
1185   // No issue if the two types have the same representation
1186   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1187       &S.Context.getFloatTypeSemantics(RHSElemType))
1188     return false;
1189 
1190   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1191                                 RHSElemType == S.Context.LongDoubleTy);
1192   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1193                             RHSElemType == S.Context.Float128Ty);
1194 
1195   /* We've handled the situation where __float128 and long double have the same
1196      representation. The only other allowable conversion is if long double is
1197      really just double.
1198   */
1199   return Float128AndLongDouble &&
1200     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1201      &llvm::APFloat::IEEEdouble());
1202 }
1203 
1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1205 
1206 namespace {
1207 /// These helper callbacks are placed in an anonymous namespace to
1208 /// permit their use as function template parameters.
1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1211 }
1212 
1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1214   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1215                              CK_IntegralComplexCast);
1216 }
1217 }
1218 
1219 /// \brief Handle integer arithmetic conversions.  Helper function of
1220 /// UsualArithmeticConversions()
1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1223                                         ExprResult &RHS, QualType LHSType,
1224                                         QualType RHSType, bool IsCompAssign) {
1225   // The rules for this case are in C99 6.3.1.8
1226   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1227   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1228   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1229   if (LHSSigned == RHSSigned) {
1230     // Same signedness; use the higher-ranked type
1231     if (order >= 0) {
1232       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233       return LHSType;
1234     } else if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236     return RHSType;
1237   } else if (order != (LHSSigned ? 1 : -1)) {
1238     // The unsigned type has greater than or equal rank to the
1239     // signed type, so use the unsigned type
1240     if (RHSSigned) {
1241       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1242       return LHSType;
1243     } else if (!IsCompAssign)
1244       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1245     return RHSType;
1246   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1247     // The two types are different widths; if we are here, that
1248     // means the signed type is larger than the unsigned type, so
1249     // use the signed type.
1250     if (LHSSigned) {
1251       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1252       return LHSType;
1253     } else if (!IsCompAssign)
1254       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1255     return RHSType;
1256   } else {
1257     // The signed type is higher-ranked than the unsigned type,
1258     // but isn't actually any bigger (like unsigned int and long
1259     // on most 32-bit systems).  Use the unsigned type corresponding
1260     // to the signed type.
1261     QualType result =
1262       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1263     RHS = (*doRHSCast)(S, RHS.get(), result);
1264     if (!IsCompAssign)
1265       LHS = (*doLHSCast)(S, LHS.get(), result);
1266     return result;
1267   }
1268 }
1269 
1270 /// \brief Handle conversions with GCC complex int extension.  Helper function
1271 /// of UsualArithmeticConversions()
1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1273                                            ExprResult &RHS, QualType LHSType,
1274                                            QualType RHSType,
1275                                            bool IsCompAssign) {
1276   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1277   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1278 
1279   if (LHSComplexInt && RHSComplexInt) {
1280     QualType LHSEltType = LHSComplexInt->getElementType();
1281     QualType RHSEltType = RHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1285 
1286     return S.Context.getComplexType(ScalarType);
1287   }
1288 
1289   if (LHSComplexInt) {
1290     QualType LHSEltType = LHSComplexInt->getElementType();
1291     QualType ScalarType =
1292       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1293         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1294     QualType ComplexType = S.Context.getComplexType(ScalarType);
1295     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297 
1298     return ComplexType;
1299   }
1300 
1301   assert(RHSComplexInt);
1302 
1303   QualType RHSEltType = RHSComplexInt->getElementType();
1304   QualType ScalarType =
1305     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1306       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1307   QualType ComplexType = S.Context.getComplexType(ScalarType);
1308 
1309   if (!IsCompAssign)
1310     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1311                               CK_IntegralRealToComplex);
1312   return ComplexType;
1313 }
1314 
1315 /// UsualArithmeticConversions - Performs various conversions that are common to
1316 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1317 /// routine returns the first non-arithmetic type found. The client is
1318 /// responsible for emitting appropriate error diagnostics.
1319 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1320                                           bool IsCompAssign) {
1321   if (!IsCompAssign) {
1322     LHS = UsualUnaryConversions(LHS.get());
1323     if (LHS.isInvalid())
1324       return QualType();
1325   }
1326 
1327   RHS = UsualUnaryConversions(RHS.get());
1328   if (RHS.isInvalid())
1329     return QualType();
1330 
1331   // For conversion purposes, we ignore any qualifiers.
1332   // For example, "const float" and "float" are equivalent.
1333   QualType LHSType =
1334     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1335   QualType RHSType =
1336     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1337 
1338   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1339   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1340     LHSType = AtomicLHS->getValueType();
1341 
1342   // If both types are identical, no conversion is needed.
1343   if (LHSType == RHSType)
1344     return LHSType;
1345 
1346   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1347   // The caller can deal with this (e.g. pointer + int).
1348   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1349     return QualType();
1350 
1351   // Apply unary and bitfield promotions to the LHS's type.
1352   QualType LHSUnpromotedType = LHSType;
1353   if (LHSType->isPromotableIntegerType())
1354     LHSType = Context.getPromotedIntegerType(LHSType);
1355   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1356   if (!LHSBitfieldPromoteTy.isNull())
1357     LHSType = LHSBitfieldPromoteTy;
1358   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1359     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // At this point, we have two different arithmetic types.
1366 
1367   // Diagnose attempts to convert between __float128 and long double where
1368   // such conversions currently can't be handled.
1369   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1370     return QualType();
1371 
1372   // Handle complex types first (C99 6.3.1.8p1).
1373   if (LHSType->isComplexType() || RHSType->isComplexType())
1374     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1375                                         IsCompAssign);
1376 
1377   // Now handle "real" floating types (i.e. float, double, long double).
1378   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1379     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1380                                  IsCompAssign);
1381 
1382   // Handle GCC complex int extension.
1383   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1384     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1385                                       IsCompAssign);
1386 
1387   // Finally, we have two differing integer types.
1388   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1389            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1390 }
1391 
1392 
1393 //===----------------------------------------------------------------------===//
1394 //  Semantic Analysis for various Expression Types
1395 //===----------------------------------------------------------------------===//
1396 
1397 
1398 ExprResult
1399 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1400                                 SourceLocation DefaultLoc,
1401                                 SourceLocation RParenLoc,
1402                                 Expr *ControllingExpr,
1403                                 ArrayRef<ParsedType> ArgTypes,
1404                                 ArrayRef<Expr *> ArgExprs) {
1405   unsigned NumAssocs = ArgTypes.size();
1406   assert(NumAssocs == ArgExprs.size());
1407 
1408   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1409   for (unsigned i = 0; i < NumAssocs; ++i) {
1410     if (ArgTypes[i])
1411       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1412     else
1413       Types[i] = nullptr;
1414   }
1415 
1416   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1417                                              ControllingExpr,
1418                                              llvm::makeArrayRef(Types, NumAssocs),
1419                                              ArgExprs);
1420   delete [] Types;
1421   return ER;
1422 }
1423 
1424 ExprResult
1425 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1426                                  SourceLocation DefaultLoc,
1427                                  SourceLocation RParenLoc,
1428                                  Expr *ControllingExpr,
1429                                  ArrayRef<TypeSourceInfo *> Types,
1430                                  ArrayRef<Expr *> Exprs) {
1431   unsigned NumAssocs = Types.size();
1432   assert(NumAssocs == Exprs.size());
1433 
1434   // Decay and strip qualifiers for the controlling expression type, and handle
1435   // placeholder type replacement. See committee discussion from WG14 DR423.
1436   {
1437     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1438     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1439     if (R.isInvalid())
1440       return ExprError();
1441     ControllingExpr = R.get();
1442   }
1443 
1444   // The controlling expression is an unevaluated operand, so side effects are
1445   // likely unintended.
1446   if (ActiveTemplateInstantiations.empty() &&
1447       ControllingExpr->HasSideEffects(Context, false))
1448     Diag(ControllingExpr->getExprLoc(),
1449          diag::warn_side_effects_unevaluated_context);
1450 
1451   bool TypeErrorFound = false,
1452        IsResultDependent = ControllingExpr->isTypeDependent(),
1453        ContainsUnexpandedParameterPack
1454          = ControllingExpr->containsUnexpandedParameterPack();
1455 
1456   for (unsigned i = 0; i < NumAssocs; ++i) {
1457     if (Exprs[i]->containsUnexpandedParameterPack())
1458       ContainsUnexpandedParameterPack = true;
1459 
1460     if (Types[i]) {
1461       if (Types[i]->getType()->containsUnexpandedParameterPack())
1462         ContainsUnexpandedParameterPack = true;
1463 
1464       if (Types[i]->getType()->isDependentType()) {
1465         IsResultDependent = true;
1466       } else {
1467         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1468         // complete object type other than a variably modified type."
1469         unsigned D = 0;
1470         if (Types[i]->getType()->isIncompleteType())
1471           D = diag::err_assoc_type_incomplete;
1472         else if (!Types[i]->getType()->isObjectType())
1473           D = diag::err_assoc_type_nonobject;
1474         else if (Types[i]->getType()->isVariablyModifiedType())
1475           D = diag::err_assoc_type_variably_modified;
1476 
1477         if (D != 0) {
1478           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1479             << Types[i]->getTypeLoc().getSourceRange()
1480             << Types[i]->getType();
1481           TypeErrorFound = true;
1482         }
1483 
1484         // C11 6.5.1.1p2 "No two generic associations in the same generic
1485         // selection shall specify compatible types."
1486         for (unsigned j = i+1; j < NumAssocs; ++j)
1487           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1488               Context.typesAreCompatible(Types[i]->getType(),
1489                                          Types[j]->getType())) {
1490             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1491                  diag::err_assoc_compatible_types)
1492               << Types[j]->getTypeLoc().getSourceRange()
1493               << Types[j]->getType()
1494               << Types[i]->getType();
1495             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1496                  diag::note_compat_assoc)
1497               << Types[i]->getTypeLoc().getSourceRange()
1498               << Types[i]->getType();
1499             TypeErrorFound = true;
1500           }
1501       }
1502     }
1503   }
1504   if (TypeErrorFound)
1505     return ExprError();
1506 
1507   // If we determined that the generic selection is result-dependent, don't
1508   // try to compute the result expression.
1509   if (IsResultDependent)
1510     return new (Context) GenericSelectionExpr(
1511         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1512         ContainsUnexpandedParameterPack);
1513 
1514   SmallVector<unsigned, 1> CompatIndices;
1515   unsigned DefaultIndex = -1U;
1516   for (unsigned i = 0; i < NumAssocs; ++i) {
1517     if (!Types[i])
1518       DefaultIndex = i;
1519     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1520                                         Types[i]->getType()))
1521       CompatIndices.push_back(i);
1522   }
1523 
1524   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1525   // type compatible with at most one of the types named in its generic
1526   // association list."
1527   if (CompatIndices.size() > 1) {
1528     // We strip parens here because the controlling expression is typically
1529     // parenthesized in macro definitions.
1530     ControllingExpr = ControllingExpr->IgnoreParens();
1531     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1532       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1533       << (unsigned) CompatIndices.size();
1534     for (unsigned I : CompatIndices) {
1535       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1536            diag::note_compat_assoc)
1537         << Types[I]->getTypeLoc().getSourceRange()
1538         << Types[I]->getType();
1539     }
1540     return ExprError();
1541   }
1542 
1543   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1544   // its controlling expression shall have type compatible with exactly one of
1545   // the types named in its generic association list."
1546   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1547     // We strip parens here because the controlling expression is typically
1548     // parenthesized in macro definitions.
1549     ControllingExpr = ControllingExpr->IgnoreParens();
1550     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1551       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1552     return ExprError();
1553   }
1554 
1555   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1556   // type name that is compatible with the type of the controlling expression,
1557   // then the result expression of the generic selection is the expression
1558   // in that generic association. Otherwise, the result expression of the
1559   // generic selection is the expression in the default generic association."
1560   unsigned ResultIndex =
1561     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1562 
1563   return new (Context) GenericSelectionExpr(
1564       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1565       ContainsUnexpandedParameterPack, ResultIndex);
1566 }
1567 
1568 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1569 /// location of the token and the offset of the ud-suffix within it.
1570 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1571                                      unsigned Offset) {
1572   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1573                                         S.getLangOpts());
1574 }
1575 
1576 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1577 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1578 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1579                                                  IdentifierInfo *UDSuffix,
1580                                                  SourceLocation UDSuffixLoc,
1581                                                  ArrayRef<Expr*> Args,
1582                                                  SourceLocation LitEndLoc) {
1583   assert(Args.size() <= 2 && "too many arguments for literal operator");
1584 
1585   QualType ArgTy[2];
1586   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1587     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1588     if (ArgTy[ArgIdx]->isArrayType())
1589       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1590   }
1591 
1592   DeclarationName OpName =
1593     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1594   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1595   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1596 
1597   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1598   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1599                               /*AllowRaw*/false, /*AllowTemplate*/false,
1600                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1601     return ExprError();
1602 
1603   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1604 }
1605 
1606 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1607 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1608 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1609 /// multiple tokens.  However, the common case is that StringToks points to one
1610 /// string.
1611 ///
1612 ExprResult
1613 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1614   assert(!StringToks.empty() && "Must have at least one string!");
1615 
1616   StringLiteralParser Literal(StringToks, PP);
1617   if (Literal.hadError)
1618     return ExprError();
1619 
1620   SmallVector<SourceLocation, 4> StringTokLocs;
1621   for (const Token &Tok : StringToks)
1622     StringTokLocs.push_back(Tok.getLocation());
1623 
1624   QualType CharTy = Context.CharTy;
1625   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1626   if (Literal.isWide()) {
1627     CharTy = Context.getWideCharType();
1628     Kind = StringLiteral::Wide;
1629   } else if (Literal.isUTF8()) {
1630     Kind = StringLiteral::UTF8;
1631   } else if (Literal.isUTF16()) {
1632     CharTy = Context.Char16Ty;
1633     Kind = StringLiteral::UTF16;
1634   } else if (Literal.isUTF32()) {
1635     CharTy = Context.Char32Ty;
1636     Kind = StringLiteral::UTF32;
1637   } else if (Literal.isPascal()) {
1638     CharTy = Context.UnsignedCharTy;
1639   }
1640 
1641   QualType CharTyConst = CharTy;
1642   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1643   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1644     CharTyConst.addConst();
1645 
1646   // Get an array type for the string, according to C99 6.4.5.  This includes
1647   // the nul terminator character as well as the string length for pascal
1648   // strings.
1649   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1650                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1651                                  ArrayType::Normal, 0);
1652 
1653   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1654   if (getLangOpts().OpenCL) {
1655     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1656   }
1657 
1658   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1659   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1660                                              Kind, Literal.Pascal, StrTy,
1661                                              &StringTokLocs[0],
1662                                              StringTokLocs.size());
1663   if (Literal.getUDSuffix().empty())
1664     return Lit;
1665 
1666   // We're building a user-defined literal.
1667   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1668   SourceLocation UDSuffixLoc =
1669     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1670                    Literal.getUDSuffixOffset());
1671 
1672   // Make sure we're allowed user-defined literals here.
1673   if (!UDLScope)
1674     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1675 
1676   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1677   //   operator "" X (str, len)
1678   QualType SizeType = Context.getSizeType();
1679 
1680   DeclarationName OpName =
1681     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1682   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1683   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1684 
1685   QualType ArgTy[] = {
1686     Context.getArrayDecayedType(StrTy), SizeType
1687   };
1688 
1689   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1690   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1691                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1692                                 /*AllowStringTemplate*/true)) {
1693 
1694   case LOLR_Cooked: {
1695     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1696     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1697                                                     StringTokLocs[0]);
1698     Expr *Args[] = { Lit, LenArg };
1699 
1700     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1701   }
1702 
1703   case LOLR_StringTemplate: {
1704     TemplateArgumentListInfo ExplicitArgs;
1705 
1706     unsigned CharBits = Context.getIntWidth(CharTy);
1707     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1708     llvm::APSInt Value(CharBits, CharIsUnsigned);
1709 
1710     TemplateArgument TypeArg(CharTy);
1711     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1712     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1713 
1714     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1715       Value = Lit->getCodeUnit(I);
1716       TemplateArgument Arg(Context, Value, CharTy);
1717       TemplateArgumentLocInfo ArgInfo;
1718       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1719     }
1720     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1721                                     &ExplicitArgs);
1722   }
1723   case LOLR_Raw:
1724   case LOLR_Template:
1725     llvm_unreachable("unexpected literal operator lookup result");
1726   case LOLR_Error:
1727     return ExprError();
1728   }
1729   llvm_unreachable("unexpected literal operator lookup result");
1730 }
1731 
1732 ExprResult
1733 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1734                        SourceLocation Loc,
1735                        const CXXScopeSpec *SS) {
1736   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1737   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1738 }
1739 
1740 /// BuildDeclRefExpr - Build an expression that references a
1741 /// declaration that does not require a closure capture.
1742 ExprResult
1743 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1744                        const DeclarationNameInfo &NameInfo,
1745                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1746                        const TemplateArgumentListInfo *TemplateArgs) {
1747   bool RefersToCapturedVariable =
1748       isa<VarDecl>(D) &&
1749       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1750 
1751   DeclRefExpr *E;
1752   if (isa<VarTemplateSpecializationDecl>(D)) {
1753     VarTemplateSpecializationDecl *VarSpec =
1754         cast<VarTemplateSpecializationDecl>(D);
1755 
1756     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1757                                         : NestedNameSpecifierLoc(),
1758                             VarSpec->getTemplateKeywordLoc(), D,
1759                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1760                             FoundD, TemplateArgs);
1761   } else {
1762     assert(!TemplateArgs && "No template arguments for non-variable"
1763                             " template specialization references");
1764     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1765                                         : NestedNameSpecifierLoc(),
1766                             SourceLocation(), D, RefersToCapturedVariable,
1767                             NameInfo, Ty, VK, FoundD);
1768   }
1769 
1770   MarkDeclRefReferenced(E);
1771 
1772   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1773       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1774       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1775       recordUseOfEvaluatedWeak(E);
1776 
1777   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1778     UnusedPrivateFields.remove(FD);
1779     // Just in case we're building an illegal pointer-to-member.
1780     if (FD->isBitField())
1781       E->setObjectKind(OK_BitField);
1782   }
1783 
1784   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1785   // designates a bit-field.
1786   if (auto *BD = dyn_cast<BindingDecl>(D))
1787     if (auto *BE = BD->getBinding())
1788       E->setObjectKind(BE->getObjectKind());
1789 
1790   return E;
1791 }
1792 
1793 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1794 /// possibly a list of template arguments.
1795 ///
1796 /// If this produces template arguments, it is permitted to call
1797 /// DecomposeTemplateName.
1798 ///
1799 /// This actually loses a lot of source location information for
1800 /// non-standard name kinds; we should consider preserving that in
1801 /// some way.
1802 void
1803 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1804                              TemplateArgumentListInfo &Buffer,
1805                              DeclarationNameInfo &NameInfo,
1806                              const TemplateArgumentListInfo *&TemplateArgs) {
1807   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1808     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1809     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1810 
1811     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1812                                        Id.TemplateId->NumArgs);
1813     translateTemplateArguments(TemplateArgsPtr, Buffer);
1814 
1815     TemplateName TName = Id.TemplateId->Template.get();
1816     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1817     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1818     TemplateArgs = &Buffer;
1819   } else {
1820     NameInfo = GetNameFromUnqualifiedId(Id);
1821     TemplateArgs = nullptr;
1822   }
1823 }
1824 
1825 static void emitEmptyLookupTypoDiagnostic(
1826     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1827     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1828     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1829   DeclContext *Ctx =
1830       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1831   if (!TC) {
1832     // Emit a special diagnostic for failed member lookups.
1833     // FIXME: computing the declaration context might fail here (?)
1834     if (Ctx)
1835       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1836                                                  << SS.getRange();
1837     else
1838       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1839     return;
1840   }
1841 
1842   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1843   bool DroppedSpecifier =
1844       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1845   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1846                         ? diag::note_implicit_param_decl
1847                         : diag::note_previous_decl;
1848   if (!Ctx)
1849     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1850                          SemaRef.PDiag(NoteID));
1851   else
1852     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1853                                  << Typo << Ctx << DroppedSpecifier
1854                                  << SS.getRange(),
1855                          SemaRef.PDiag(NoteID));
1856 }
1857 
1858 /// Diagnose an empty lookup.
1859 ///
1860 /// \return false if new lookup candidates were found
1861 bool
1862 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1863                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1864                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1865                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1866   DeclarationName Name = R.getLookupName();
1867 
1868   unsigned diagnostic = diag::err_undeclared_var_use;
1869   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1870   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1871       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1872       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1873     diagnostic = diag::err_undeclared_use;
1874     diagnostic_suggest = diag::err_undeclared_use_suggest;
1875   }
1876 
1877   // If the original lookup was an unqualified lookup, fake an
1878   // unqualified lookup.  This is useful when (for example) the
1879   // original lookup would not have found something because it was a
1880   // dependent name.
1881   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1882   while (DC) {
1883     if (isa<CXXRecordDecl>(DC)) {
1884       LookupQualifiedName(R, DC);
1885 
1886       if (!R.empty()) {
1887         // Don't give errors about ambiguities in this lookup.
1888         R.suppressDiagnostics();
1889 
1890         // During a default argument instantiation the CurContext points
1891         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1892         // function parameter list, hence add an explicit check.
1893         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1894                               ActiveTemplateInstantiations.back().Kind ==
1895             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1896         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1897         bool isInstance = CurMethod &&
1898                           CurMethod->isInstance() &&
1899                           DC == CurMethod->getParent() && !isDefaultArgument;
1900 
1901         // Give a code modification hint to insert 'this->'.
1902         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1903         // Actually quite difficult!
1904         if (getLangOpts().MSVCCompat)
1905           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1906         if (isInstance) {
1907           Diag(R.getNameLoc(), diagnostic) << Name
1908             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1909           CheckCXXThisCapture(R.getNameLoc());
1910         } else {
1911           Diag(R.getNameLoc(), diagnostic) << Name;
1912         }
1913 
1914         // Do we really want to note all of these?
1915         for (NamedDecl *D : R)
1916           Diag(D->getLocation(), diag::note_dependent_var_use);
1917 
1918         // Return true if we are inside a default argument instantiation
1919         // and the found name refers to an instance member function, otherwise
1920         // the function calling DiagnoseEmptyLookup will try to create an
1921         // implicit member call and this is wrong for default argument.
1922         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1923           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1924           return true;
1925         }
1926 
1927         // Tell the callee to try to recover.
1928         return false;
1929       }
1930 
1931       R.clear();
1932     }
1933 
1934     // In Microsoft mode, if we are performing lookup from within a friend
1935     // function definition declared at class scope then we must set
1936     // DC to the lexical parent to be able to search into the parent
1937     // class.
1938     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1939         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1940         DC->getLexicalParent()->isRecord())
1941       DC = DC->getLexicalParent();
1942     else
1943       DC = DC->getParent();
1944   }
1945 
1946   // We didn't find anything, so try to correct for a typo.
1947   TypoCorrection Corrected;
1948   if (S && Out) {
1949     SourceLocation TypoLoc = R.getNameLoc();
1950     assert(!ExplicitTemplateArgs &&
1951            "Diagnosing an empty lookup with explicit template args!");
1952     *Out = CorrectTypoDelayed(
1953         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1954         [=](const TypoCorrection &TC) {
1955           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1956                                         diagnostic, diagnostic_suggest);
1957         },
1958         nullptr, CTK_ErrorRecovery);
1959     if (*Out)
1960       return true;
1961   } else if (S && (Corrected =
1962                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1963                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1964     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1965     bool DroppedSpecifier =
1966         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1967     R.setLookupName(Corrected.getCorrection());
1968 
1969     bool AcceptableWithRecovery = false;
1970     bool AcceptableWithoutRecovery = false;
1971     NamedDecl *ND = Corrected.getFoundDecl();
1972     if (ND) {
1973       if (Corrected.isOverloaded()) {
1974         OverloadCandidateSet OCS(R.getNameLoc(),
1975                                  OverloadCandidateSet::CSK_Normal);
1976         OverloadCandidateSet::iterator Best;
1977         for (NamedDecl *CD : Corrected) {
1978           if (FunctionTemplateDecl *FTD =
1979                    dyn_cast<FunctionTemplateDecl>(CD))
1980             AddTemplateOverloadCandidate(
1981                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1982                 Args, OCS);
1983           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1984             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1985               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1986                                    Args, OCS);
1987         }
1988         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1989         case OR_Success:
1990           ND = Best->FoundDecl;
1991           Corrected.setCorrectionDecl(ND);
1992           break;
1993         default:
1994           // FIXME: Arbitrarily pick the first declaration for the note.
1995           Corrected.setCorrectionDecl(ND);
1996           break;
1997         }
1998       }
1999       R.addDecl(ND);
2000       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2001         CXXRecordDecl *Record = nullptr;
2002         if (Corrected.getCorrectionSpecifier()) {
2003           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2004           Record = Ty->getAsCXXRecordDecl();
2005         }
2006         if (!Record)
2007           Record = cast<CXXRecordDecl>(
2008               ND->getDeclContext()->getRedeclContext());
2009         R.setNamingClass(Record);
2010       }
2011 
2012       auto *UnderlyingND = ND->getUnderlyingDecl();
2013       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2014                                isa<FunctionTemplateDecl>(UnderlyingND);
2015       // FIXME: If we ended up with a typo for a type name or
2016       // Objective-C class name, we're in trouble because the parser
2017       // is in the wrong place to recover. Suggest the typo
2018       // correction, but don't make it a fix-it since we're not going
2019       // to recover well anyway.
2020       AcceptableWithoutRecovery =
2021           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2022     } else {
2023       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2024       // because we aren't able to recover.
2025       AcceptableWithoutRecovery = true;
2026     }
2027 
2028     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2029       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2030                             ? diag::note_implicit_param_decl
2031                             : diag::note_previous_decl;
2032       if (SS.isEmpty())
2033         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2034                      PDiag(NoteID), AcceptableWithRecovery);
2035       else
2036         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2037                                   << Name << computeDeclContext(SS, false)
2038                                   << DroppedSpecifier << SS.getRange(),
2039                      PDiag(NoteID), AcceptableWithRecovery);
2040 
2041       // Tell the callee whether to try to recover.
2042       return !AcceptableWithRecovery;
2043     }
2044   }
2045   R.clear();
2046 
2047   // Emit a special diagnostic for failed member lookups.
2048   // FIXME: computing the declaration context might fail here (?)
2049   if (!SS.isEmpty()) {
2050     Diag(R.getNameLoc(), diag::err_no_member)
2051       << Name << computeDeclContext(SS, false)
2052       << SS.getRange();
2053     return true;
2054   }
2055 
2056   // Give up, we can't recover.
2057   Diag(R.getNameLoc(), diagnostic) << Name;
2058   return true;
2059 }
2060 
2061 /// In Microsoft mode, if we are inside a template class whose parent class has
2062 /// dependent base classes, and we can't resolve an unqualified identifier, then
2063 /// assume the identifier is a member of a dependent base class.  We can only
2064 /// recover successfully in static methods, instance methods, and other contexts
2065 /// where 'this' is available.  This doesn't precisely match MSVC's
2066 /// instantiation model, but it's close enough.
2067 static Expr *
2068 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2069                                DeclarationNameInfo &NameInfo,
2070                                SourceLocation TemplateKWLoc,
2071                                const TemplateArgumentListInfo *TemplateArgs) {
2072   // Only try to recover from lookup into dependent bases in static methods or
2073   // contexts where 'this' is available.
2074   QualType ThisType = S.getCurrentThisType();
2075   const CXXRecordDecl *RD = nullptr;
2076   if (!ThisType.isNull())
2077     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2078   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2079     RD = MD->getParent();
2080   if (!RD || !RD->hasAnyDependentBases())
2081     return nullptr;
2082 
2083   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2084   // is available, suggest inserting 'this->' as a fixit.
2085   SourceLocation Loc = NameInfo.getLoc();
2086   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2087   DB << NameInfo.getName() << RD;
2088 
2089   if (!ThisType.isNull()) {
2090     DB << FixItHint::CreateInsertion(Loc, "this->");
2091     return CXXDependentScopeMemberExpr::Create(
2092         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2093         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2094         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2095   }
2096 
2097   // Synthesize a fake NNS that points to the derived class.  This will
2098   // perform name lookup during template instantiation.
2099   CXXScopeSpec SS;
2100   auto *NNS =
2101       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2102   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2103   return DependentScopeDeclRefExpr::Create(
2104       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2105       TemplateArgs);
2106 }
2107 
2108 ExprResult
2109 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2110                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2111                         bool HasTrailingLParen, bool IsAddressOfOperand,
2112                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2113                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2114   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2115          "cannot be direct & operand and have a trailing lparen");
2116   if (SS.isInvalid())
2117     return ExprError();
2118 
2119   TemplateArgumentListInfo TemplateArgsBuffer;
2120 
2121   // Decompose the UnqualifiedId into the following data.
2122   DeclarationNameInfo NameInfo;
2123   const TemplateArgumentListInfo *TemplateArgs;
2124   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2125 
2126   DeclarationName Name = NameInfo.getName();
2127   IdentifierInfo *II = Name.getAsIdentifierInfo();
2128   SourceLocation NameLoc = NameInfo.getLoc();
2129 
2130   // C++ [temp.dep.expr]p3:
2131   //   An id-expression is type-dependent if it contains:
2132   //     -- an identifier that was declared with a dependent type,
2133   //        (note: handled after lookup)
2134   //     -- a template-id that is dependent,
2135   //        (note: handled in BuildTemplateIdExpr)
2136   //     -- a conversion-function-id that specifies a dependent type,
2137   //     -- a nested-name-specifier that contains a class-name that
2138   //        names a dependent type.
2139   // Determine whether this is a member of an unknown specialization;
2140   // we need to handle these differently.
2141   bool DependentID = false;
2142   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2143       Name.getCXXNameType()->isDependentType()) {
2144     DependentID = true;
2145   } else if (SS.isSet()) {
2146     if (DeclContext *DC = computeDeclContext(SS, false)) {
2147       if (RequireCompleteDeclContext(SS, DC))
2148         return ExprError();
2149     } else {
2150       DependentID = true;
2151     }
2152   }
2153 
2154   if (DependentID)
2155     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2156                                       IsAddressOfOperand, TemplateArgs);
2157 
2158   // Perform the required lookup.
2159   LookupResult R(*this, NameInfo,
2160                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2161                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2162   if (TemplateArgs) {
2163     // Lookup the template name again to correctly establish the context in
2164     // which it was found. This is really unfortunate as we already did the
2165     // lookup to determine that it was a template name in the first place. If
2166     // this becomes a performance hit, we can work harder to preserve those
2167     // results until we get here but it's likely not worth it.
2168     bool MemberOfUnknownSpecialization;
2169     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2170                        MemberOfUnknownSpecialization);
2171 
2172     if (MemberOfUnknownSpecialization ||
2173         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2174       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2175                                         IsAddressOfOperand, TemplateArgs);
2176   } else {
2177     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2178     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2179 
2180     // If the result might be in a dependent base class, this is a dependent
2181     // id-expression.
2182     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2183       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2184                                         IsAddressOfOperand, TemplateArgs);
2185 
2186     // If this reference is in an Objective-C method, then we need to do
2187     // some special Objective-C lookup, too.
2188     if (IvarLookupFollowUp) {
2189       ExprResult E(LookupInObjCMethod(R, S, II, true));
2190       if (E.isInvalid())
2191         return ExprError();
2192 
2193       if (Expr *Ex = E.getAs<Expr>())
2194         return Ex;
2195     }
2196   }
2197 
2198   if (R.isAmbiguous())
2199     return ExprError();
2200 
2201   // This could be an implicitly declared function reference (legal in C90,
2202   // extension in C99, forbidden in C++).
2203   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2204     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2205     if (D) R.addDecl(D);
2206   }
2207 
2208   // Determine whether this name might be a candidate for
2209   // argument-dependent lookup.
2210   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2211 
2212   if (R.empty() && !ADL) {
2213     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2214       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2215                                                    TemplateKWLoc, TemplateArgs))
2216         return E;
2217     }
2218 
2219     // Don't diagnose an empty lookup for inline assembly.
2220     if (IsInlineAsmIdentifier)
2221       return ExprError();
2222 
2223     // If this name wasn't predeclared and if this is not a function
2224     // call, diagnose the problem.
2225     TypoExpr *TE = nullptr;
2226     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2227         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2228     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2229     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2230            "Typo correction callback misconfigured");
2231     if (CCC) {
2232       // Make sure the callback knows what the typo being diagnosed is.
2233       CCC->setTypoName(II);
2234       if (SS.isValid())
2235         CCC->setTypoNNS(SS.getScopeRep());
2236     }
2237     if (DiagnoseEmptyLookup(S, SS, R,
2238                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2239                             nullptr, None, &TE)) {
2240       if (TE && KeywordReplacement) {
2241         auto &State = getTypoExprState(TE);
2242         auto BestTC = State.Consumer->getNextCorrection();
2243         if (BestTC.isKeyword()) {
2244           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2245           if (State.DiagHandler)
2246             State.DiagHandler(BestTC);
2247           KeywordReplacement->startToken();
2248           KeywordReplacement->setKind(II->getTokenID());
2249           KeywordReplacement->setIdentifierInfo(II);
2250           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2251           // Clean up the state associated with the TypoExpr, since it has
2252           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2253           clearDelayedTypo(TE);
2254           // Signal that a correction to a keyword was performed by returning a
2255           // valid-but-null ExprResult.
2256           return (Expr*)nullptr;
2257         }
2258         State.Consumer->resetCorrectionStream();
2259       }
2260       return TE ? TE : ExprError();
2261     }
2262 
2263     assert(!R.empty() &&
2264            "DiagnoseEmptyLookup returned false but added no results");
2265 
2266     // If we found an Objective-C instance variable, let
2267     // LookupInObjCMethod build the appropriate expression to
2268     // reference the ivar.
2269     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2270       R.clear();
2271       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2272       // In a hopelessly buggy code, Objective-C instance variable
2273       // lookup fails and no expression will be built to reference it.
2274       if (!E.isInvalid() && !E.get())
2275         return ExprError();
2276       return E;
2277     }
2278   }
2279 
2280   // This is guaranteed from this point on.
2281   assert(!R.empty() || ADL);
2282 
2283   // Check whether this might be a C++ implicit instance member access.
2284   // C++ [class.mfct.non-static]p3:
2285   //   When an id-expression that is not part of a class member access
2286   //   syntax and not used to form a pointer to member is used in the
2287   //   body of a non-static member function of class X, if name lookup
2288   //   resolves the name in the id-expression to a non-static non-type
2289   //   member of some class C, the id-expression is transformed into a
2290   //   class member access expression using (*this) as the
2291   //   postfix-expression to the left of the . operator.
2292   //
2293   // But we don't actually need to do this for '&' operands if R
2294   // resolved to a function or overloaded function set, because the
2295   // expression is ill-formed if it actually works out to be a
2296   // non-static member function:
2297   //
2298   // C++ [expr.ref]p4:
2299   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2300   //   [t]he expression can be used only as the left-hand operand of a
2301   //   member function call.
2302   //
2303   // There are other safeguards against such uses, but it's important
2304   // to get this right here so that we don't end up making a
2305   // spuriously dependent expression if we're inside a dependent
2306   // instance method.
2307   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2308     bool MightBeImplicitMember;
2309     if (!IsAddressOfOperand)
2310       MightBeImplicitMember = true;
2311     else if (!SS.isEmpty())
2312       MightBeImplicitMember = false;
2313     else if (R.isOverloadedResult())
2314       MightBeImplicitMember = false;
2315     else if (R.isUnresolvableResult())
2316       MightBeImplicitMember = true;
2317     else
2318       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2319                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2320                               isa<MSPropertyDecl>(R.getFoundDecl());
2321 
2322     if (MightBeImplicitMember)
2323       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2324                                              R, TemplateArgs, S);
2325   }
2326 
2327   if (TemplateArgs || TemplateKWLoc.isValid()) {
2328 
2329     // In C++1y, if this is a variable template id, then check it
2330     // in BuildTemplateIdExpr().
2331     // The single lookup result must be a variable template declaration.
2332     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2333         Id.TemplateId->Kind == TNK_Var_template) {
2334       assert(R.getAsSingle<VarTemplateDecl>() &&
2335              "There should only be one declaration found.");
2336     }
2337 
2338     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2339   }
2340 
2341   return BuildDeclarationNameExpr(SS, R, ADL);
2342 }
2343 
2344 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2345 /// declaration name, generally during template instantiation.
2346 /// There's a large number of things which don't need to be done along
2347 /// this path.
2348 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2349     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2350     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2351   DeclContext *DC = computeDeclContext(SS, false);
2352   if (!DC)
2353     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2354                                      NameInfo, /*TemplateArgs=*/nullptr);
2355 
2356   if (RequireCompleteDeclContext(SS, DC))
2357     return ExprError();
2358 
2359   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2360   LookupQualifiedName(R, DC);
2361 
2362   if (R.isAmbiguous())
2363     return ExprError();
2364 
2365   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2366     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367                                      NameInfo, /*TemplateArgs=*/nullptr);
2368 
2369   if (R.empty()) {
2370     Diag(NameInfo.getLoc(), diag::err_no_member)
2371       << NameInfo.getName() << DC << SS.getRange();
2372     return ExprError();
2373   }
2374 
2375   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2376     // Diagnose a missing typename if this resolved unambiguously to a type in
2377     // a dependent context.  If we can recover with a type, downgrade this to
2378     // a warning in Microsoft compatibility mode.
2379     unsigned DiagID = diag::err_typename_missing;
2380     if (RecoveryTSI && getLangOpts().MSVCCompat)
2381       DiagID = diag::ext_typename_missing;
2382     SourceLocation Loc = SS.getBeginLoc();
2383     auto D = Diag(Loc, DiagID);
2384     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2385       << SourceRange(Loc, NameInfo.getEndLoc());
2386 
2387     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2388     // context.
2389     if (!RecoveryTSI)
2390       return ExprError();
2391 
2392     // Only issue the fixit if we're prepared to recover.
2393     D << FixItHint::CreateInsertion(Loc, "typename ");
2394 
2395     // Recover by pretending this was an elaborated type.
2396     QualType Ty = Context.getTypeDeclType(TD);
2397     TypeLocBuilder TLB;
2398     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2399 
2400     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2401     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2402     QTL.setElaboratedKeywordLoc(SourceLocation());
2403     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2404 
2405     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2406 
2407     return ExprEmpty();
2408   }
2409 
2410   // Defend against this resolving to an implicit member access. We usually
2411   // won't get here if this might be a legitimate a class member (we end up in
2412   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2413   // a pointer-to-member or in an unevaluated context in C++11.
2414   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2415     return BuildPossibleImplicitMemberExpr(SS,
2416                                            /*TemplateKWLoc=*/SourceLocation(),
2417                                            R, /*TemplateArgs=*/nullptr, S);
2418 
2419   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2420 }
2421 
2422 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2423 /// detected that we're currently inside an ObjC method.  Perform some
2424 /// additional lookup.
2425 ///
2426 /// Ideally, most of this would be done by lookup, but there's
2427 /// actually quite a lot of extra work involved.
2428 ///
2429 /// Returns a null sentinel to indicate trivial success.
2430 ExprResult
2431 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2432                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2433   SourceLocation Loc = Lookup.getNameLoc();
2434   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2435 
2436   // Check for error condition which is already reported.
2437   if (!CurMethod)
2438     return ExprError();
2439 
2440   // There are two cases to handle here.  1) scoped lookup could have failed,
2441   // in which case we should look for an ivar.  2) scoped lookup could have
2442   // found a decl, but that decl is outside the current instance method (i.e.
2443   // a global variable).  In these two cases, we do a lookup for an ivar with
2444   // this name, if the lookup sucedes, we replace it our current decl.
2445 
2446   // If we're in a class method, we don't normally want to look for
2447   // ivars.  But if we don't find anything else, and there's an
2448   // ivar, that's an error.
2449   bool IsClassMethod = CurMethod->isClassMethod();
2450 
2451   bool LookForIvars;
2452   if (Lookup.empty())
2453     LookForIvars = true;
2454   else if (IsClassMethod)
2455     LookForIvars = false;
2456   else
2457     LookForIvars = (Lookup.isSingleResult() &&
2458                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2459   ObjCInterfaceDecl *IFace = nullptr;
2460   if (LookForIvars) {
2461     IFace = CurMethod->getClassInterface();
2462     ObjCInterfaceDecl *ClassDeclared;
2463     ObjCIvarDecl *IV = nullptr;
2464     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2465       // Diagnose using an ivar in a class method.
2466       if (IsClassMethod)
2467         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2468                          << IV->getDeclName());
2469 
2470       // If we're referencing an invalid decl, just return this as a silent
2471       // error node.  The error diagnostic was already emitted on the decl.
2472       if (IV->isInvalidDecl())
2473         return ExprError();
2474 
2475       // Check if referencing a field with __attribute__((deprecated)).
2476       if (DiagnoseUseOfDecl(IV, Loc))
2477         return ExprError();
2478 
2479       // Diagnose the use of an ivar outside of the declaring class.
2480       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2481           !declaresSameEntity(ClassDeclared, IFace) &&
2482           !getLangOpts().DebuggerSupport)
2483         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2484 
2485       // FIXME: This should use a new expr for a direct reference, don't
2486       // turn this into Self->ivar, just return a BareIVarExpr or something.
2487       IdentifierInfo &II = Context.Idents.get("self");
2488       UnqualifiedId SelfName;
2489       SelfName.setIdentifier(&II, SourceLocation());
2490       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2491       CXXScopeSpec SelfScopeSpec;
2492       SourceLocation TemplateKWLoc;
2493       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2494                                               SelfName, false, false);
2495       if (SelfExpr.isInvalid())
2496         return ExprError();
2497 
2498       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2499       if (SelfExpr.isInvalid())
2500         return ExprError();
2501 
2502       MarkAnyDeclReferenced(Loc, IV, true);
2503 
2504       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2505       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2506           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2507         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2508 
2509       ObjCIvarRefExpr *Result = new (Context)
2510           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2511                           IV->getLocation(), SelfExpr.get(), true, true);
2512 
2513       if (getLangOpts().ObjCAutoRefCount) {
2514         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2515           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2516             recordUseOfEvaluatedWeak(Result);
2517         }
2518         if (CurContext->isClosure())
2519           Diag(Loc, diag::warn_implicitly_retains_self)
2520             << FixItHint::CreateInsertion(Loc, "self->");
2521       }
2522 
2523       return Result;
2524     }
2525   } else if (CurMethod->isInstanceMethod()) {
2526     // We should warn if a local variable hides an ivar.
2527     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2528       ObjCInterfaceDecl *ClassDeclared;
2529       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2530         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2531             declaresSameEntity(IFace, ClassDeclared))
2532           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2533       }
2534     }
2535   } else if (Lookup.isSingleResult() &&
2536              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2537     // If accessing a stand-alone ivar in a class method, this is an error.
2538     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2539       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540                        << IV->getDeclName());
2541   }
2542 
2543   if (Lookup.empty() && II && AllowBuiltinCreation) {
2544     // FIXME. Consolidate this with similar code in LookupName.
2545     if (unsigned BuiltinID = II->getBuiltinID()) {
2546       if (!(getLangOpts().CPlusPlus &&
2547             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2548         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2549                                            S, Lookup.isForRedeclaration(),
2550                                            Lookup.getNameLoc());
2551         if (D) Lookup.addDecl(D);
2552       }
2553     }
2554   }
2555   // Sentinel value saying that we didn't do anything special.
2556   return ExprResult((Expr *)nullptr);
2557 }
2558 
2559 /// \brief Cast a base object to a member's actual type.
2560 ///
2561 /// Logically this happens in three phases:
2562 ///
2563 /// * First we cast from the base type to the naming class.
2564 ///   The naming class is the class into which we were looking
2565 ///   when we found the member;  it's the qualifier type if a
2566 ///   qualifier was provided, and otherwise it's the base type.
2567 ///
2568 /// * Next we cast from the naming class to the declaring class.
2569 ///   If the member we found was brought into a class's scope by
2570 ///   a using declaration, this is that class;  otherwise it's
2571 ///   the class declaring the member.
2572 ///
2573 /// * Finally we cast from the declaring class to the "true"
2574 ///   declaring class of the member.  This conversion does not
2575 ///   obey access control.
2576 ExprResult
2577 Sema::PerformObjectMemberConversion(Expr *From,
2578                                     NestedNameSpecifier *Qualifier,
2579                                     NamedDecl *FoundDecl,
2580                                     NamedDecl *Member) {
2581   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2582   if (!RD)
2583     return From;
2584 
2585   QualType DestRecordType;
2586   QualType DestType;
2587   QualType FromRecordType;
2588   QualType FromType = From->getType();
2589   bool PointerConversions = false;
2590   if (isa<FieldDecl>(Member)) {
2591     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2592 
2593     if (FromType->getAs<PointerType>()) {
2594       DestType = Context.getPointerType(DestRecordType);
2595       FromRecordType = FromType->getPointeeType();
2596       PointerConversions = true;
2597     } else {
2598       DestType = DestRecordType;
2599       FromRecordType = FromType;
2600     }
2601   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2602     if (Method->isStatic())
2603       return From;
2604 
2605     DestType = Method->getThisType(Context);
2606     DestRecordType = DestType->getPointeeType();
2607 
2608     if (FromType->getAs<PointerType>()) {
2609       FromRecordType = FromType->getPointeeType();
2610       PointerConversions = true;
2611     } else {
2612       FromRecordType = FromType;
2613       DestType = DestRecordType;
2614     }
2615   } else {
2616     // No conversion necessary.
2617     return From;
2618   }
2619 
2620   if (DestType->isDependentType() || FromType->isDependentType())
2621     return From;
2622 
2623   // If the unqualified types are the same, no conversion is necessary.
2624   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2625     return From;
2626 
2627   SourceRange FromRange = From->getSourceRange();
2628   SourceLocation FromLoc = FromRange.getBegin();
2629 
2630   ExprValueKind VK = From->getValueKind();
2631 
2632   // C++ [class.member.lookup]p8:
2633   //   [...] Ambiguities can often be resolved by qualifying a name with its
2634   //   class name.
2635   //
2636   // If the member was a qualified name and the qualified referred to a
2637   // specific base subobject type, we'll cast to that intermediate type
2638   // first and then to the object in which the member is declared. That allows
2639   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2640   //
2641   //   class Base { public: int x; };
2642   //   class Derived1 : public Base { };
2643   //   class Derived2 : public Base { };
2644   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2645   //
2646   //   void VeryDerived::f() {
2647   //     x = 17; // error: ambiguous base subobjects
2648   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2649   //   }
2650   if (Qualifier && Qualifier->getAsType()) {
2651     QualType QType = QualType(Qualifier->getAsType(), 0);
2652     assert(QType->isRecordType() && "lookup done with non-record type");
2653 
2654     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2655 
2656     // In C++98, the qualifier type doesn't actually have to be a base
2657     // type of the object type, in which case we just ignore it.
2658     // Otherwise build the appropriate casts.
2659     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2660       CXXCastPath BasePath;
2661       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2662                                        FromLoc, FromRange, &BasePath))
2663         return ExprError();
2664 
2665       if (PointerConversions)
2666         QType = Context.getPointerType(QType);
2667       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2668                                VK, &BasePath).get();
2669 
2670       FromType = QType;
2671       FromRecordType = QRecordType;
2672 
2673       // If the qualifier type was the same as the destination type,
2674       // we're done.
2675       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2676         return From;
2677     }
2678   }
2679 
2680   bool IgnoreAccess = false;
2681 
2682   // If we actually found the member through a using declaration, cast
2683   // down to the using declaration's type.
2684   //
2685   // Pointer equality is fine here because only one declaration of a
2686   // class ever has member declarations.
2687   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2688     assert(isa<UsingShadowDecl>(FoundDecl));
2689     QualType URecordType = Context.getTypeDeclType(
2690                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2691 
2692     // We only need to do this if the naming-class to declaring-class
2693     // conversion is non-trivial.
2694     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2695       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2696       CXXCastPath BasePath;
2697       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2698                                        FromLoc, FromRange, &BasePath))
2699         return ExprError();
2700 
2701       QualType UType = URecordType;
2702       if (PointerConversions)
2703         UType = Context.getPointerType(UType);
2704       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2705                                VK, &BasePath).get();
2706       FromType = UType;
2707       FromRecordType = URecordType;
2708     }
2709 
2710     // We don't do access control for the conversion from the
2711     // declaring class to the true declaring class.
2712     IgnoreAccess = true;
2713   }
2714 
2715   CXXCastPath BasePath;
2716   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2717                                    FromLoc, FromRange, &BasePath,
2718                                    IgnoreAccess))
2719     return ExprError();
2720 
2721   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2722                            VK, &BasePath);
2723 }
2724 
2725 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2726                                       const LookupResult &R,
2727                                       bool HasTrailingLParen) {
2728   // Only when used directly as the postfix-expression of a call.
2729   if (!HasTrailingLParen)
2730     return false;
2731 
2732   // Never if a scope specifier was provided.
2733   if (SS.isSet())
2734     return false;
2735 
2736   // Only in C++ or ObjC++.
2737   if (!getLangOpts().CPlusPlus)
2738     return false;
2739 
2740   // Turn off ADL when we find certain kinds of declarations during
2741   // normal lookup:
2742   for (NamedDecl *D : R) {
2743     // C++0x [basic.lookup.argdep]p3:
2744     //     -- a declaration of a class member
2745     // Since using decls preserve this property, we check this on the
2746     // original decl.
2747     if (D->isCXXClassMember())
2748       return false;
2749 
2750     // C++0x [basic.lookup.argdep]p3:
2751     //     -- a block-scope function declaration that is not a
2752     //        using-declaration
2753     // NOTE: we also trigger this for function templates (in fact, we
2754     // don't check the decl type at all, since all other decl types
2755     // turn off ADL anyway).
2756     if (isa<UsingShadowDecl>(D))
2757       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2758     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2759       return false;
2760 
2761     // C++0x [basic.lookup.argdep]p3:
2762     //     -- a declaration that is neither a function or a function
2763     //        template
2764     // And also for builtin functions.
2765     if (isa<FunctionDecl>(D)) {
2766       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2767 
2768       // But also builtin functions.
2769       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2770         return false;
2771     } else if (!isa<FunctionTemplateDecl>(D))
2772       return false;
2773   }
2774 
2775   return true;
2776 }
2777 
2778 
2779 /// Diagnoses obvious problems with the use of the given declaration
2780 /// as an expression.  This is only actually called for lookups that
2781 /// were not overloaded, and it doesn't promise that the declaration
2782 /// will in fact be used.
2783 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2784   if (D->isInvalidDecl())
2785     return true;
2786 
2787   if (isa<TypedefNameDecl>(D)) {
2788     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2789     return true;
2790   }
2791 
2792   if (isa<ObjCInterfaceDecl>(D)) {
2793     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2794     return true;
2795   }
2796 
2797   if (isa<NamespaceDecl>(D)) {
2798     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2799     return true;
2800   }
2801 
2802   return false;
2803 }
2804 
2805 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2806                                           LookupResult &R, bool NeedsADL,
2807                                           bool AcceptInvalidDecl) {
2808   // If this is a single, fully-resolved result and we don't need ADL,
2809   // just build an ordinary singleton decl ref.
2810   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2811     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2812                                     R.getRepresentativeDecl(), nullptr,
2813                                     AcceptInvalidDecl);
2814 
2815   // We only need to check the declaration if there's exactly one
2816   // result, because in the overloaded case the results can only be
2817   // functions and function templates.
2818   if (R.isSingleResult() &&
2819       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2820     return ExprError();
2821 
2822   // Otherwise, just build an unresolved lookup expression.  Suppress
2823   // any lookup-related diagnostics; we'll hash these out later, when
2824   // we've picked a target.
2825   R.suppressDiagnostics();
2826 
2827   UnresolvedLookupExpr *ULE
2828     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2829                                    SS.getWithLocInContext(Context),
2830                                    R.getLookupNameInfo(),
2831                                    NeedsADL, R.isOverloadedResult(),
2832                                    R.begin(), R.end());
2833 
2834   return ULE;
2835 }
2836 
2837 static void
2838 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2839                                    ValueDecl *var, DeclContext *DC);
2840 
2841 /// \brief Complete semantic analysis for a reference to the given declaration.
2842 ExprResult Sema::BuildDeclarationNameExpr(
2843     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2844     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2845     bool AcceptInvalidDecl) {
2846   assert(D && "Cannot refer to a NULL declaration");
2847   assert(!isa<FunctionTemplateDecl>(D) &&
2848          "Cannot refer unambiguously to a function template");
2849 
2850   SourceLocation Loc = NameInfo.getLoc();
2851   if (CheckDeclInExpr(*this, Loc, D))
2852     return ExprError();
2853 
2854   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2855     // Specifically diagnose references to class templates that are missing
2856     // a template argument list.
2857     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2858                                            << Template << SS.getRange();
2859     Diag(Template->getLocation(), diag::note_template_decl_here);
2860     return ExprError();
2861   }
2862 
2863   // Make sure that we're referring to a value.
2864   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2865   if (!VD) {
2866     Diag(Loc, diag::err_ref_non_value)
2867       << D << SS.getRange();
2868     Diag(D->getLocation(), diag::note_declared_at);
2869     return ExprError();
2870   }
2871 
2872   // Check whether this declaration can be used. Note that we suppress
2873   // this check when we're going to perform argument-dependent lookup
2874   // on this function name, because this might not be the function
2875   // that overload resolution actually selects.
2876   if (DiagnoseUseOfDecl(VD, Loc))
2877     return ExprError();
2878 
2879   // Only create DeclRefExpr's for valid Decl's.
2880   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2881     return ExprError();
2882 
2883   // Handle members of anonymous structs and unions.  If we got here,
2884   // and the reference is to a class member indirect field, then this
2885   // must be the subject of a pointer-to-member expression.
2886   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2887     if (!indirectField->isCXXClassMember())
2888       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2889                                                       indirectField);
2890 
2891   {
2892     QualType type = VD->getType();
2893     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2894       // C++ [except.spec]p17:
2895       //   An exception-specification is considered to be needed when:
2896       //   - in an expression, the function is the unique lookup result or
2897       //     the selected member of a set of overloaded functions.
2898       ResolveExceptionSpec(Loc, FPT);
2899       type = VD->getType();
2900     }
2901     ExprValueKind valueKind = VK_RValue;
2902 
2903     switch (D->getKind()) {
2904     // Ignore all the non-ValueDecl kinds.
2905 #define ABSTRACT_DECL(kind)
2906 #define VALUE(type, base)
2907 #define DECL(type, base) \
2908     case Decl::type:
2909 #include "clang/AST/DeclNodes.inc"
2910       llvm_unreachable("invalid value decl kind");
2911 
2912     // These shouldn't make it here.
2913     case Decl::ObjCAtDefsField:
2914     case Decl::ObjCIvar:
2915       llvm_unreachable("forming non-member reference to ivar?");
2916 
2917     // Enum constants are always r-values and never references.
2918     // Unresolved using declarations are dependent.
2919     case Decl::EnumConstant:
2920     case Decl::UnresolvedUsingValue:
2921     case Decl::OMPDeclareReduction:
2922       valueKind = VK_RValue;
2923       break;
2924 
2925     // Fields and indirect fields that got here must be for
2926     // pointer-to-member expressions; we just call them l-values for
2927     // internal consistency, because this subexpression doesn't really
2928     // exist in the high-level semantics.
2929     case Decl::Field:
2930     case Decl::IndirectField:
2931       assert(getLangOpts().CPlusPlus &&
2932              "building reference to field in C?");
2933 
2934       // These can't have reference type in well-formed programs, but
2935       // for internal consistency we do this anyway.
2936       type = type.getNonReferenceType();
2937       valueKind = VK_LValue;
2938       break;
2939 
2940     // Non-type template parameters are either l-values or r-values
2941     // depending on the type.
2942     case Decl::NonTypeTemplateParm: {
2943       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2944         type = reftype->getPointeeType();
2945         valueKind = VK_LValue; // even if the parameter is an r-value reference
2946         break;
2947       }
2948 
2949       // For non-references, we need to strip qualifiers just in case
2950       // the template parameter was declared as 'const int' or whatever.
2951       valueKind = VK_RValue;
2952       type = type.getUnqualifiedType();
2953       break;
2954     }
2955 
2956     case Decl::Var:
2957     case Decl::VarTemplateSpecialization:
2958     case Decl::VarTemplatePartialSpecialization:
2959     case Decl::Decomposition:
2960     case Decl::OMPCapturedExpr:
2961       // In C, "extern void blah;" is valid and is an r-value.
2962       if (!getLangOpts().CPlusPlus &&
2963           !type.hasQualifiers() &&
2964           type->isVoidType()) {
2965         valueKind = VK_RValue;
2966         break;
2967       }
2968       // fallthrough
2969 
2970     case Decl::ImplicitParam:
2971     case Decl::ParmVar: {
2972       // These are always l-values.
2973       valueKind = VK_LValue;
2974       type = type.getNonReferenceType();
2975 
2976       // FIXME: Does the addition of const really only apply in
2977       // potentially-evaluated contexts? Since the variable isn't actually
2978       // captured in an unevaluated context, it seems that the answer is no.
2979       if (!isUnevaluatedContext()) {
2980         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2981         if (!CapturedType.isNull())
2982           type = CapturedType;
2983       }
2984 
2985       break;
2986     }
2987 
2988     case Decl::Binding: {
2989       // These are always lvalues.
2990       valueKind = VK_LValue;
2991       type = type.getNonReferenceType();
2992       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2993       // decides how that's supposed to work.
2994       auto *BD = cast<BindingDecl>(VD);
2995       if (BD->getDeclContext()->isFunctionOrMethod() &&
2996           BD->getDeclContext() != CurContext)
2997         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2998       break;
2999     }
3000 
3001     case Decl::Function: {
3002       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3003         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3004           type = Context.BuiltinFnTy;
3005           valueKind = VK_RValue;
3006           break;
3007         }
3008       }
3009 
3010       const FunctionType *fty = type->castAs<FunctionType>();
3011 
3012       // If we're referring to a function with an __unknown_anytype
3013       // result type, make the entire expression __unknown_anytype.
3014       if (fty->getReturnType() == Context.UnknownAnyTy) {
3015         type = Context.UnknownAnyTy;
3016         valueKind = VK_RValue;
3017         break;
3018       }
3019 
3020       // Functions are l-values in C++.
3021       if (getLangOpts().CPlusPlus) {
3022         valueKind = VK_LValue;
3023         break;
3024       }
3025 
3026       // C99 DR 316 says that, if a function type comes from a
3027       // function definition (without a prototype), that type is only
3028       // used for checking compatibility. Therefore, when referencing
3029       // the function, we pretend that we don't have the full function
3030       // type.
3031       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3032           isa<FunctionProtoType>(fty))
3033         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3034                                               fty->getExtInfo());
3035 
3036       // Functions are r-values in C.
3037       valueKind = VK_RValue;
3038       break;
3039     }
3040 
3041     case Decl::MSProperty:
3042       valueKind = VK_LValue;
3043       break;
3044 
3045     case Decl::CXXMethod:
3046       // If we're referring to a method with an __unknown_anytype
3047       // result type, make the entire expression __unknown_anytype.
3048       // This should only be possible with a type written directly.
3049       if (const FunctionProtoType *proto
3050             = dyn_cast<FunctionProtoType>(VD->getType()))
3051         if (proto->getReturnType() == Context.UnknownAnyTy) {
3052           type = Context.UnknownAnyTy;
3053           valueKind = VK_RValue;
3054           break;
3055         }
3056 
3057       // C++ methods are l-values if static, r-values if non-static.
3058       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3059         valueKind = VK_LValue;
3060         break;
3061       }
3062       // fallthrough
3063 
3064     case Decl::CXXConversion:
3065     case Decl::CXXDestructor:
3066     case Decl::CXXConstructor:
3067       valueKind = VK_RValue;
3068       break;
3069     }
3070 
3071     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3072                             TemplateArgs);
3073   }
3074 }
3075 
3076 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3077                                     SmallString<32> &Target) {
3078   Target.resize(CharByteWidth * (Source.size() + 1));
3079   char *ResultPtr = &Target[0];
3080   const llvm::UTF8 *ErrorPtr;
3081   bool success =
3082       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3083   (void)success;
3084   assert(success);
3085   Target.resize(ResultPtr - &Target[0]);
3086 }
3087 
3088 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3089                                      PredefinedExpr::IdentType IT) {
3090   // Pick the current block, lambda, captured statement or function.
3091   Decl *currentDecl = nullptr;
3092   if (const BlockScopeInfo *BSI = getCurBlock())
3093     currentDecl = BSI->TheDecl;
3094   else if (const LambdaScopeInfo *LSI = getCurLambda())
3095     currentDecl = LSI->CallOperator;
3096   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3097     currentDecl = CSI->TheCapturedDecl;
3098   else
3099     currentDecl = getCurFunctionOrMethodDecl();
3100 
3101   if (!currentDecl) {
3102     Diag(Loc, diag::ext_predef_outside_function);
3103     currentDecl = Context.getTranslationUnitDecl();
3104   }
3105 
3106   QualType ResTy;
3107   StringLiteral *SL = nullptr;
3108   if (cast<DeclContext>(currentDecl)->isDependentContext())
3109     ResTy = Context.DependentTy;
3110   else {
3111     // Pre-defined identifiers are of type char[x], where x is the length of
3112     // the string.
3113     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3114     unsigned Length = Str.length();
3115 
3116     llvm::APInt LengthI(32, Length + 1);
3117     if (IT == PredefinedExpr::LFunction) {
3118       ResTy = Context.WideCharTy.withConst();
3119       SmallString<32> RawChars;
3120       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3121                               Str, RawChars);
3122       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3123                                            /*IndexTypeQuals*/ 0);
3124       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3125                                  /*Pascal*/ false, ResTy, Loc);
3126     } else {
3127       ResTy = Context.CharTy.withConst();
3128       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3129                                            /*IndexTypeQuals*/ 0);
3130       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3131                                  /*Pascal*/ false, ResTy, Loc);
3132     }
3133   }
3134 
3135   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3136 }
3137 
3138 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3139   PredefinedExpr::IdentType IT;
3140 
3141   switch (Kind) {
3142   default: llvm_unreachable("Unknown simple primary expr!");
3143   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3144   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3145   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3146   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3147   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3148   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3149   }
3150 
3151   return BuildPredefinedExpr(Loc, IT);
3152 }
3153 
3154 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3155   SmallString<16> CharBuffer;
3156   bool Invalid = false;
3157   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3158   if (Invalid)
3159     return ExprError();
3160 
3161   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3162                             PP, Tok.getKind());
3163   if (Literal.hadError())
3164     return ExprError();
3165 
3166   QualType Ty;
3167   if (Literal.isWide())
3168     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3169   else if (Literal.isUTF16())
3170     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3171   else if (Literal.isUTF32())
3172     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3173   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3174     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3175   else
3176     Ty = Context.CharTy;  // 'x' -> char in C++
3177 
3178   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3179   if (Literal.isWide())
3180     Kind = CharacterLiteral::Wide;
3181   else if (Literal.isUTF16())
3182     Kind = CharacterLiteral::UTF16;
3183   else if (Literal.isUTF32())
3184     Kind = CharacterLiteral::UTF32;
3185   else if (Literal.isUTF8())
3186     Kind = CharacterLiteral::UTF8;
3187 
3188   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3189                                              Tok.getLocation());
3190 
3191   if (Literal.getUDSuffix().empty())
3192     return Lit;
3193 
3194   // We're building a user-defined literal.
3195   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3196   SourceLocation UDSuffixLoc =
3197     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3198 
3199   // Make sure we're allowed user-defined literals here.
3200   if (!UDLScope)
3201     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3202 
3203   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3204   //   operator "" X (ch)
3205   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3206                                         Lit, Tok.getLocation());
3207 }
3208 
3209 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3210   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3211   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3212                                 Context.IntTy, Loc);
3213 }
3214 
3215 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3216                                   QualType Ty, SourceLocation Loc) {
3217   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3218 
3219   using llvm::APFloat;
3220   APFloat Val(Format);
3221 
3222   APFloat::opStatus result = Literal.GetFloatValue(Val);
3223 
3224   // Overflow is always an error, but underflow is only an error if
3225   // we underflowed to zero (APFloat reports denormals as underflow).
3226   if ((result & APFloat::opOverflow) ||
3227       ((result & APFloat::opUnderflow) && Val.isZero())) {
3228     unsigned diagnostic;
3229     SmallString<20> buffer;
3230     if (result & APFloat::opOverflow) {
3231       diagnostic = diag::warn_float_overflow;
3232       APFloat::getLargest(Format).toString(buffer);
3233     } else {
3234       diagnostic = diag::warn_float_underflow;
3235       APFloat::getSmallest(Format).toString(buffer);
3236     }
3237 
3238     S.Diag(Loc, diagnostic)
3239       << Ty
3240       << StringRef(buffer.data(), buffer.size());
3241   }
3242 
3243   bool isExact = (result == APFloat::opOK);
3244   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3245 }
3246 
3247 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3248   assert(E && "Invalid expression");
3249 
3250   if (E->isValueDependent())
3251     return false;
3252 
3253   QualType QT = E->getType();
3254   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3255     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3256     return true;
3257   }
3258 
3259   llvm::APSInt ValueAPS;
3260   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3261 
3262   if (R.isInvalid())
3263     return true;
3264 
3265   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3266   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3267     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3268         << ValueAPS.toString(10) << ValueIsPositive;
3269     return true;
3270   }
3271 
3272   return false;
3273 }
3274 
3275 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3276   // Fast path for a single digit (which is quite common).  A single digit
3277   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3278   if (Tok.getLength() == 1) {
3279     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3280     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3281   }
3282 
3283   SmallString<128> SpellingBuffer;
3284   // NumericLiteralParser wants to overread by one character.  Add padding to
3285   // the buffer in case the token is copied to the buffer.  If getSpelling()
3286   // returns a StringRef to the memory buffer, it should have a null char at
3287   // the EOF, so it is also safe.
3288   SpellingBuffer.resize(Tok.getLength() + 1);
3289 
3290   // Get the spelling of the token, which eliminates trigraphs, etc.
3291   bool Invalid = false;
3292   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3293   if (Invalid)
3294     return ExprError();
3295 
3296   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3297   if (Literal.hadError)
3298     return ExprError();
3299 
3300   if (Literal.hasUDSuffix()) {
3301     // We're building a user-defined literal.
3302     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3303     SourceLocation UDSuffixLoc =
3304       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3305 
3306     // Make sure we're allowed user-defined literals here.
3307     if (!UDLScope)
3308       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3309 
3310     QualType CookedTy;
3311     if (Literal.isFloatingLiteral()) {
3312       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3313       // long double, the literal is treated as a call of the form
3314       //   operator "" X (f L)
3315       CookedTy = Context.LongDoubleTy;
3316     } else {
3317       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3318       // unsigned long long, the literal is treated as a call of the form
3319       //   operator "" X (n ULL)
3320       CookedTy = Context.UnsignedLongLongTy;
3321     }
3322 
3323     DeclarationName OpName =
3324       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3325     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3326     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3327 
3328     SourceLocation TokLoc = Tok.getLocation();
3329 
3330     // Perform literal operator lookup to determine if we're building a raw
3331     // literal or a cooked one.
3332     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3333     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3334                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3335                                   /*AllowStringTemplate*/false)) {
3336     case LOLR_Error:
3337       return ExprError();
3338 
3339     case LOLR_Cooked: {
3340       Expr *Lit;
3341       if (Literal.isFloatingLiteral()) {
3342         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3343       } else {
3344         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3345         if (Literal.GetIntegerValue(ResultVal))
3346           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3347               << /* Unsigned */ 1;
3348         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3349                                      Tok.getLocation());
3350       }
3351       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3352     }
3353 
3354     case LOLR_Raw: {
3355       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3356       // literal is treated as a call of the form
3357       //   operator "" X ("n")
3358       unsigned Length = Literal.getUDSuffixOffset();
3359       QualType StrTy = Context.getConstantArrayType(
3360           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3361           ArrayType::Normal, 0);
3362       Expr *Lit = StringLiteral::Create(
3363           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3364           /*Pascal*/false, StrTy, &TokLoc, 1);
3365       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3366     }
3367 
3368     case LOLR_Template: {
3369       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3370       // template), L is treated as a call fo the form
3371       //   operator "" X <'c1', 'c2', ... 'ck'>()
3372       // where n is the source character sequence c1 c2 ... ck.
3373       TemplateArgumentListInfo ExplicitArgs;
3374       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3375       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3376       llvm::APSInt Value(CharBits, CharIsUnsigned);
3377       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3378         Value = TokSpelling[I];
3379         TemplateArgument Arg(Context, Value, Context.CharTy);
3380         TemplateArgumentLocInfo ArgInfo;
3381         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3382       }
3383       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3384                                       &ExplicitArgs);
3385     }
3386     case LOLR_StringTemplate:
3387       llvm_unreachable("unexpected literal operator lookup result");
3388     }
3389   }
3390 
3391   Expr *Res;
3392 
3393   if (Literal.isFloatingLiteral()) {
3394     QualType Ty;
3395     if (Literal.isHalf){
3396       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3397         Ty = Context.HalfTy;
3398       else {
3399         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3400         return ExprError();
3401       }
3402     } else if (Literal.isFloat)
3403       Ty = Context.FloatTy;
3404     else if (Literal.isLong)
3405       Ty = Context.LongDoubleTy;
3406     else if (Literal.isFloat128)
3407       Ty = Context.Float128Ty;
3408     else
3409       Ty = Context.DoubleTy;
3410 
3411     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3412 
3413     if (Ty == Context.DoubleTy) {
3414       if (getLangOpts().SinglePrecisionConstants) {
3415         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3416         if (BTy->getKind() != BuiltinType::Float) {
3417           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3418         }
3419       } else if (getLangOpts().OpenCL &&
3420                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3421         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3422         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3423         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3424       }
3425     }
3426   } else if (!Literal.isIntegerLiteral()) {
3427     return ExprError();
3428   } else {
3429     QualType Ty;
3430 
3431     // 'long long' is a C99 or C++11 feature.
3432     if (!getLangOpts().C99 && Literal.isLongLong) {
3433       if (getLangOpts().CPlusPlus)
3434         Diag(Tok.getLocation(),
3435              getLangOpts().CPlusPlus11 ?
3436              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3437       else
3438         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3439     }
3440 
3441     // Get the value in the widest-possible width.
3442     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3443     llvm::APInt ResultVal(MaxWidth, 0);
3444 
3445     if (Literal.GetIntegerValue(ResultVal)) {
3446       // If this value didn't fit into uintmax_t, error and force to ull.
3447       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3448           << /* Unsigned */ 1;
3449       Ty = Context.UnsignedLongLongTy;
3450       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3451              "long long is not intmax_t?");
3452     } else {
3453       // If this value fits into a ULL, try to figure out what else it fits into
3454       // according to the rules of C99 6.4.4.1p5.
3455 
3456       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3457       // be an unsigned int.
3458       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3459 
3460       // Check from smallest to largest, picking the smallest type we can.
3461       unsigned Width = 0;
3462 
3463       // Microsoft specific integer suffixes are explicitly sized.
3464       if (Literal.MicrosoftInteger) {
3465         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3466           Width = 8;
3467           Ty = Context.CharTy;
3468         } else {
3469           Width = Literal.MicrosoftInteger;
3470           Ty = Context.getIntTypeForBitwidth(Width,
3471                                              /*Signed=*/!Literal.isUnsigned);
3472         }
3473       }
3474 
3475       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3476         // Are int/unsigned possibilities?
3477         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3478 
3479         // Does it fit in a unsigned int?
3480         if (ResultVal.isIntN(IntSize)) {
3481           // Does it fit in a signed int?
3482           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3483             Ty = Context.IntTy;
3484           else if (AllowUnsigned)
3485             Ty = Context.UnsignedIntTy;
3486           Width = IntSize;
3487         }
3488       }
3489 
3490       // Are long/unsigned long possibilities?
3491       if (Ty.isNull() && !Literal.isLongLong) {
3492         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3493 
3494         // Does it fit in a unsigned long?
3495         if (ResultVal.isIntN(LongSize)) {
3496           // Does it fit in a signed long?
3497           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3498             Ty = Context.LongTy;
3499           else if (AllowUnsigned)
3500             Ty = Context.UnsignedLongTy;
3501           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3502           // is compatible.
3503           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3504             const unsigned LongLongSize =
3505                 Context.getTargetInfo().getLongLongWidth();
3506             Diag(Tok.getLocation(),
3507                  getLangOpts().CPlusPlus
3508                      ? Literal.isLong
3509                            ? diag::warn_old_implicitly_unsigned_long_cxx
3510                            : /*C++98 UB*/ diag::
3511                                  ext_old_implicitly_unsigned_long_cxx
3512                      : diag::warn_old_implicitly_unsigned_long)
3513                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3514                                             : /*will be ill-formed*/ 1);
3515             Ty = Context.UnsignedLongTy;
3516           }
3517           Width = LongSize;
3518         }
3519       }
3520 
3521       // Check long long if needed.
3522       if (Ty.isNull()) {
3523         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3524 
3525         // Does it fit in a unsigned long long?
3526         if (ResultVal.isIntN(LongLongSize)) {
3527           // Does it fit in a signed long long?
3528           // To be compatible with MSVC, hex integer literals ending with the
3529           // LL or i64 suffix are always signed in Microsoft mode.
3530           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3531               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3532             Ty = Context.LongLongTy;
3533           else if (AllowUnsigned)
3534             Ty = Context.UnsignedLongLongTy;
3535           Width = LongLongSize;
3536         }
3537       }
3538 
3539       // If we still couldn't decide a type, we probably have something that
3540       // does not fit in a signed long long, but has no U suffix.
3541       if (Ty.isNull()) {
3542         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3543         Ty = Context.UnsignedLongLongTy;
3544         Width = Context.getTargetInfo().getLongLongWidth();
3545       }
3546 
3547       if (ResultVal.getBitWidth() != Width)
3548         ResultVal = ResultVal.trunc(Width);
3549     }
3550     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3551   }
3552 
3553   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3554   if (Literal.isImaginary)
3555     Res = new (Context) ImaginaryLiteral(Res,
3556                                         Context.getComplexType(Res->getType()));
3557 
3558   return Res;
3559 }
3560 
3561 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3562   assert(E && "ActOnParenExpr() missing expr");
3563   return new (Context) ParenExpr(L, R, E);
3564 }
3565 
3566 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3567                                          SourceLocation Loc,
3568                                          SourceRange ArgRange) {
3569   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3570   // scalar or vector data type argument..."
3571   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3572   // type (C99 6.2.5p18) or void.
3573   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3574     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3575       << T << ArgRange;
3576     return true;
3577   }
3578 
3579   assert((T->isVoidType() || !T->isIncompleteType()) &&
3580          "Scalar types should always be complete");
3581   return false;
3582 }
3583 
3584 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3585                                            SourceLocation Loc,
3586                                            SourceRange ArgRange,
3587                                            UnaryExprOrTypeTrait TraitKind) {
3588   // Invalid types must be hard errors for SFINAE in C++.
3589   if (S.LangOpts.CPlusPlus)
3590     return true;
3591 
3592   // C99 6.5.3.4p1:
3593   if (T->isFunctionType() &&
3594       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3595     // sizeof(function)/alignof(function) is allowed as an extension.
3596     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3597       << TraitKind << ArgRange;
3598     return false;
3599   }
3600 
3601   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3602   // this is an error (OpenCL v1.1 s6.3.k)
3603   if (T->isVoidType()) {
3604     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3605                                         : diag::ext_sizeof_alignof_void_type;
3606     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3607     return false;
3608   }
3609 
3610   return true;
3611 }
3612 
3613 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3614                                              SourceLocation Loc,
3615                                              SourceRange ArgRange,
3616                                              UnaryExprOrTypeTrait TraitKind) {
3617   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3618   // runtime doesn't allow it.
3619   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3620     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3621       << T << (TraitKind == UETT_SizeOf)
3622       << ArgRange;
3623     return true;
3624   }
3625 
3626   return false;
3627 }
3628 
3629 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3630 /// pointer type is equal to T) and emit a warning if it is.
3631 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3632                                      Expr *E) {
3633   // Don't warn if the operation changed the type.
3634   if (T != E->getType())
3635     return;
3636 
3637   // Now look for array decays.
3638   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3639   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3640     return;
3641 
3642   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3643                                              << ICE->getType()
3644                                              << ICE->getSubExpr()->getType();
3645 }
3646 
3647 /// \brief Check the constraints on expression operands to unary type expression
3648 /// and type traits.
3649 ///
3650 /// Completes any types necessary and validates the constraints on the operand
3651 /// expression. The logic mostly mirrors the type-based overload, but may modify
3652 /// the expression as it completes the type for that expression through template
3653 /// instantiation, etc.
3654 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3655                                             UnaryExprOrTypeTrait ExprKind) {
3656   QualType ExprTy = E->getType();
3657   assert(!ExprTy->isReferenceType());
3658 
3659   if (ExprKind == UETT_VecStep)
3660     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                         E->getSourceRange());
3662 
3663   // Whitelist some types as extensions
3664   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3665                                       E->getSourceRange(), ExprKind))
3666     return false;
3667 
3668   // 'alignof' applied to an expression only requires the base element type of
3669   // the expression to be complete. 'sizeof' requires the expression's type to
3670   // be complete (and will attempt to complete it if it's an array of unknown
3671   // bound).
3672   if (ExprKind == UETT_AlignOf) {
3673     if (RequireCompleteType(E->getExprLoc(),
3674                             Context.getBaseElementType(E->getType()),
3675                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3676                             E->getSourceRange()))
3677       return true;
3678   } else {
3679     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3680                                 ExprKind, E->getSourceRange()))
3681       return true;
3682   }
3683 
3684   // Completing the expression's type may have changed it.
3685   ExprTy = E->getType();
3686   assert(!ExprTy->isReferenceType());
3687 
3688   if (ExprTy->isFunctionType()) {
3689     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3690       << ExprKind << E->getSourceRange();
3691     return true;
3692   }
3693 
3694   // The operand for sizeof and alignof is in an unevaluated expression context,
3695   // so side effects could result in unintended consequences.
3696   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3697       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3698     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3699 
3700   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3701                                        E->getSourceRange(), ExprKind))
3702     return true;
3703 
3704   if (ExprKind == UETT_SizeOf) {
3705     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3706       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3707         QualType OType = PVD->getOriginalType();
3708         QualType Type = PVD->getType();
3709         if (Type->isPointerType() && OType->isArrayType()) {
3710           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3711             << Type << OType;
3712           Diag(PVD->getLocation(), diag::note_declared_at);
3713         }
3714       }
3715     }
3716 
3717     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3718     // decays into a pointer and returns an unintended result. This is most
3719     // likely a typo for "sizeof(array) op x".
3720     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3721       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3722                                BO->getLHS());
3723       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3724                                BO->getRHS());
3725     }
3726   }
3727 
3728   return false;
3729 }
3730 
3731 /// \brief Check the constraints on operands to unary expression and type
3732 /// traits.
3733 ///
3734 /// This will complete any types necessary, and validate the various constraints
3735 /// on those operands.
3736 ///
3737 /// The UsualUnaryConversions() function is *not* called by this routine.
3738 /// C99 6.3.2.1p[2-4] all state:
3739 ///   Except when it is the operand of the sizeof operator ...
3740 ///
3741 /// C++ [expr.sizeof]p4
3742 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3743 ///   standard conversions are not applied to the operand of sizeof.
3744 ///
3745 /// This policy is followed for all of the unary trait expressions.
3746 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3747                                             SourceLocation OpLoc,
3748                                             SourceRange ExprRange,
3749                                             UnaryExprOrTypeTrait ExprKind) {
3750   if (ExprType->isDependentType())
3751     return false;
3752 
3753   // C++ [expr.sizeof]p2:
3754   //     When applied to a reference or a reference type, the result
3755   //     is the size of the referenced type.
3756   // C++11 [expr.alignof]p3:
3757   //     When alignof is applied to a reference type, the result
3758   //     shall be the alignment of the referenced type.
3759   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3760     ExprType = Ref->getPointeeType();
3761 
3762   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3763   //   When alignof or _Alignof is applied to an array type, the result
3764   //   is the alignment of the element type.
3765   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3766     ExprType = Context.getBaseElementType(ExprType);
3767 
3768   if (ExprKind == UETT_VecStep)
3769     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3770 
3771   // Whitelist some types as extensions
3772   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3773                                       ExprKind))
3774     return false;
3775 
3776   if (RequireCompleteType(OpLoc, ExprType,
3777                           diag::err_sizeof_alignof_incomplete_type,
3778                           ExprKind, ExprRange))
3779     return true;
3780 
3781   if (ExprType->isFunctionType()) {
3782     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3783       << ExprKind << ExprRange;
3784     return true;
3785   }
3786 
3787   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3788                                        ExprKind))
3789     return true;
3790 
3791   return false;
3792 }
3793 
3794 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3795   E = E->IgnoreParens();
3796 
3797   // Cannot know anything else if the expression is dependent.
3798   if (E->isTypeDependent())
3799     return false;
3800 
3801   if (E->getObjectKind() == OK_BitField) {
3802     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3803        << 1 << E->getSourceRange();
3804     return true;
3805   }
3806 
3807   ValueDecl *D = nullptr;
3808   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3809     D = DRE->getDecl();
3810   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3811     D = ME->getMemberDecl();
3812   }
3813 
3814   // If it's a field, require the containing struct to have a
3815   // complete definition so that we can compute the layout.
3816   //
3817   // This can happen in C++11 onwards, either by naming the member
3818   // in a way that is not transformed into a member access expression
3819   // (in an unevaluated operand, for instance), or by naming the member
3820   // in a trailing-return-type.
3821   //
3822   // For the record, since __alignof__ on expressions is a GCC
3823   // extension, GCC seems to permit this but always gives the
3824   // nonsensical answer 0.
3825   //
3826   // We don't really need the layout here --- we could instead just
3827   // directly check for all the appropriate alignment-lowing
3828   // attributes --- but that would require duplicating a lot of
3829   // logic that just isn't worth duplicating for such a marginal
3830   // use-case.
3831   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3832     // Fast path this check, since we at least know the record has a
3833     // definition if we can find a member of it.
3834     if (!FD->getParent()->isCompleteDefinition()) {
3835       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3836         << E->getSourceRange();
3837       return true;
3838     }
3839 
3840     // Otherwise, if it's a field, and the field doesn't have
3841     // reference type, then it must have a complete type (or be a
3842     // flexible array member, which we explicitly want to
3843     // white-list anyway), which makes the following checks trivial.
3844     if (!FD->getType()->isReferenceType())
3845       return false;
3846   }
3847 
3848   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3849 }
3850 
3851 bool Sema::CheckVecStepExpr(Expr *E) {
3852   E = E->IgnoreParens();
3853 
3854   // Cannot know anything else if the expression is dependent.
3855   if (E->isTypeDependent())
3856     return false;
3857 
3858   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3859 }
3860 
3861 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3862                                         CapturingScopeInfo *CSI) {
3863   assert(T->isVariablyModifiedType());
3864   assert(CSI != nullptr);
3865 
3866   // We're going to walk down into the type and look for VLA expressions.
3867   do {
3868     const Type *Ty = T.getTypePtr();
3869     switch (Ty->getTypeClass()) {
3870 #define TYPE(Class, Base)
3871 #define ABSTRACT_TYPE(Class, Base)
3872 #define NON_CANONICAL_TYPE(Class, Base)
3873 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3874 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3875 #include "clang/AST/TypeNodes.def"
3876       T = QualType();
3877       break;
3878     // These types are never variably-modified.
3879     case Type::Builtin:
3880     case Type::Complex:
3881     case Type::Vector:
3882     case Type::ExtVector:
3883     case Type::Record:
3884     case Type::Enum:
3885     case Type::Elaborated:
3886     case Type::TemplateSpecialization:
3887     case Type::ObjCObject:
3888     case Type::ObjCInterface:
3889     case Type::ObjCObjectPointer:
3890     case Type::ObjCTypeParam:
3891     case Type::Pipe:
3892       llvm_unreachable("type class is never variably-modified!");
3893     case Type::Adjusted:
3894       T = cast<AdjustedType>(Ty)->getOriginalType();
3895       break;
3896     case Type::Decayed:
3897       T = cast<DecayedType>(Ty)->getPointeeType();
3898       break;
3899     case Type::Pointer:
3900       T = cast<PointerType>(Ty)->getPointeeType();
3901       break;
3902     case Type::BlockPointer:
3903       T = cast<BlockPointerType>(Ty)->getPointeeType();
3904       break;
3905     case Type::LValueReference:
3906     case Type::RValueReference:
3907       T = cast<ReferenceType>(Ty)->getPointeeType();
3908       break;
3909     case Type::MemberPointer:
3910       T = cast<MemberPointerType>(Ty)->getPointeeType();
3911       break;
3912     case Type::ConstantArray:
3913     case Type::IncompleteArray:
3914       // Losing element qualification here is fine.
3915       T = cast<ArrayType>(Ty)->getElementType();
3916       break;
3917     case Type::VariableArray: {
3918       // Losing element qualification here is fine.
3919       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3920 
3921       // Unknown size indication requires no size computation.
3922       // Otherwise, evaluate and record it.
3923       if (auto Size = VAT->getSizeExpr()) {
3924         if (!CSI->isVLATypeCaptured(VAT)) {
3925           RecordDecl *CapRecord = nullptr;
3926           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3927             CapRecord = LSI->Lambda;
3928           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3929             CapRecord = CRSI->TheRecordDecl;
3930           }
3931           if (CapRecord) {
3932             auto ExprLoc = Size->getExprLoc();
3933             auto SizeType = Context.getSizeType();
3934             // Build the non-static data member.
3935             auto Field =
3936                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3937                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3938                                   /*BW*/ nullptr, /*Mutable*/ false,
3939                                   /*InitStyle*/ ICIS_NoInit);
3940             Field->setImplicit(true);
3941             Field->setAccess(AS_private);
3942             Field->setCapturedVLAType(VAT);
3943             CapRecord->addDecl(Field);
3944 
3945             CSI->addVLATypeCapture(ExprLoc, SizeType);
3946           }
3947         }
3948       }
3949       T = VAT->getElementType();
3950       break;
3951     }
3952     case Type::FunctionProto:
3953     case Type::FunctionNoProto:
3954       T = cast<FunctionType>(Ty)->getReturnType();
3955       break;
3956     case Type::Paren:
3957     case Type::TypeOf:
3958     case Type::UnaryTransform:
3959     case Type::Attributed:
3960     case Type::SubstTemplateTypeParm:
3961     case Type::PackExpansion:
3962       // Keep walking after single level desugaring.
3963       T = T.getSingleStepDesugaredType(Context);
3964       break;
3965     case Type::Typedef:
3966       T = cast<TypedefType>(Ty)->desugar();
3967       break;
3968     case Type::Decltype:
3969       T = cast<DecltypeType>(Ty)->desugar();
3970       break;
3971     case Type::Auto:
3972     case Type::DeducedTemplateSpecialization:
3973       T = cast<DeducedType>(Ty)->getDeducedType();
3974       break;
3975     case Type::TypeOfExpr:
3976       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3977       break;
3978     case Type::Atomic:
3979       T = cast<AtomicType>(Ty)->getValueType();
3980       break;
3981     }
3982   } while (!T.isNull() && T->isVariablyModifiedType());
3983 }
3984 
3985 /// \brief Build a sizeof or alignof expression given a type operand.
3986 ExprResult
3987 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3988                                      SourceLocation OpLoc,
3989                                      UnaryExprOrTypeTrait ExprKind,
3990                                      SourceRange R) {
3991   if (!TInfo)
3992     return ExprError();
3993 
3994   QualType T = TInfo->getType();
3995 
3996   if (!T->isDependentType() &&
3997       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3998     return ExprError();
3999 
4000   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4001     if (auto *TT = T->getAs<TypedefType>()) {
4002       for (auto I = FunctionScopes.rbegin(),
4003                 E = std::prev(FunctionScopes.rend());
4004            I != E; ++I) {
4005         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4006         if (CSI == nullptr)
4007           break;
4008         DeclContext *DC = nullptr;
4009         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4010           DC = LSI->CallOperator;
4011         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4012           DC = CRSI->TheCapturedDecl;
4013         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4014           DC = BSI->TheDecl;
4015         if (DC) {
4016           if (DC->containsDecl(TT->getDecl()))
4017             break;
4018           captureVariablyModifiedType(Context, T, CSI);
4019         }
4020       }
4021     }
4022   }
4023 
4024   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4025   return new (Context) UnaryExprOrTypeTraitExpr(
4026       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4027 }
4028 
4029 /// \brief Build a sizeof or alignof expression given an expression
4030 /// operand.
4031 ExprResult
4032 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4033                                      UnaryExprOrTypeTrait ExprKind) {
4034   ExprResult PE = CheckPlaceholderExpr(E);
4035   if (PE.isInvalid())
4036     return ExprError();
4037 
4038   E = PE.get();
4039 
4040   // Verify that the operand is valid.
4041   bool isInvalid = false;
4042   if (E->isTypeDependent()) {
4043     // Delay type-checking for type-dependent expressions.
4044   } else if (ExprKind == UETT_AlignOf) {
4045     isInvalid = CheckAlignOfExpr(*this, E);
4046   } else if (ExprKind == UETT_VecStep) {
4047     isInvalid = CheckVecStepExpr(E);
4048   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4049       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4050       isInvalid = true;
4051   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4052     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4053     isInvalid = true;
4054   } else {
4055     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4056   }
4057 
4058   if (isInvalid)
4059     return ExprError();
4060 
4061   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4062     PE = TransformToPotentiallyEvaluated(E);
4063     if (PE.isInvalid()) return ExprError();
4064     E = PE.get();
4065   }
4066 
4067   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4068   return new (Context) UnaryExprOrTypeTraitExpr(
4069       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4070 }
4071 
4072 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4073 /// expr and the same for @c alignof and @c __alignof
4074 /// Note that the ArgRange is invalid if isType is false.
4075 ExprResult
4076 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4077                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4078                                     void *TyOrEx, SourceRange ArgRange) {
4079   // If error parsing type, ignore.
4080   if (!TyOrEx) return ExprError();
4081 
4082   if (IsType) {
4083     TypeSourceInfo *TInfo;
4084     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4085     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4086   }
4087 
4088   Expr *ArgEx = (Expr *)TyOrEx;
4089   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4090   return Result;
4091 }
4092 
4093 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4094                                      bool IsReal) {
4095   if (V.get()->isTypeDependent())
4096     return S.Context.DependentTy;
4097 
4098   // _Real and _Imag are only l-values for normal l-values.
4099   if (V.get()->getObjectKind() != OK_Ordinary) {
4100     V = S.DefaultLvalueConversion(V.get());
4101     if (V.isInvalid())
4102       return QualType();
4103   }
4104 
4105   // These operators return the element type of a complex type.
4106   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4107     return CT->getElementType();
4108 
4109   // Otherwise they pass through real integer and floating point types here.
4110   if (V.get()->getType()->isArithmeticType())
4111     return V.get()->getType();
4112 
4113   // Test for placeholders.
4114   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4115   if (PR.isInvalid()) return QualType();
4116   if (PR.get() != V.get()) {
4117     V = PR;
4118     return CheckRealImagOperand(S, V, Loc, IsReal);
4119   }
4120 
4121   // Reject anything else.
4122   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4123     << (IsReal ? "__real" : "__imag");
4124   return QualType();
4125 }
4126 
4127 
4128 
4129 ExprResult
4130 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4131                           tok::TokenKind Kind, Expr *Input) {
4132   UnaryOperatorKind Opc;
4133   switch (Kind) {
4134   default: llvm_unreachable("Unknown unary op!");
4135   case tok::plusplus:   Opc = UO_PostInc; break;
4136   case tok::minusminus: Opc = UO_PostDec; break;
4137   }
4138 
4139   // Since this might is a postfix expression, get rid of ParenListExprs.
4140   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4141   if (Result.isInvalid()) return ExprError();
4142   Input = Result.get();
4143 
4144   return BuildUnaryOp(S, OpLoc, Opc, Input);
4145 }
4146 
4147 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4148 ///
4149 /// \return true on error
4150 static bool checkArithmeticOnObjCPointer(Sema &S,
4151                                          SourceLocation opLoc,
4152                                          Expr *op) {
4153   assert(op->getType()->isObjCObjectPointerType());
4154   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4155       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4156     return false;
4157 
4158   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4159     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4160     << op->getSourceRange();
4161   return true;
4162 }
4163 
4164 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4165   auto *BaseNoParens = Base->IgnoreParens();
4166   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4167     return MSProp->getPropertyDecl()->getType()->isArrayType();
4168   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4169 }
4170 
4171 ExprResult
4172 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4173                               Expr *idx, SourceLocation rbLoc) {
4174   if (base && !base->getType().isNull() &&
4175       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4176     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4177                                     /*Length=*/nullptr, rbLoc);
4178 
4179   // Since this might be a postfix expression, get rid of ParenListExprs.
4180   if (isa<ParenListExpr>(base)) {
4181     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4182     if (result.isInvalid()) return ExprError();
4183     base = result.get();
4184   }
4185 
4186   // Handle any non-overload placeholder types in the base and index
4187   // expressions.  We can't handle overloads here because the other
4188   // operand might be an overloadable type, in which case the overload
4189   // resolution for the operator overload should get the first crack
4190   // at the overload.
4191   bool IsMSPropertySubscript = false;
4192   if (base->getType()->isNonOverloadPlaceholderType()) {
4193     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4194     if (!IsMSPropertySubscript) {
4195       ExprResult result = CheckPlaceholderExpr(base);
4196       if (result.isInvalid())
4197         return ExprError();
4198       base = result.get();
4199     }
4200   }
4201   if (idx->getType()->isNonOverloadPlaceholderType()) {
4202     ExprResult result = CheckPlaceholderExpr(idx);
4203     if (result.isInvalid()) return ExprError();
4204     idx = result.get();
4205   }
4206 
4207   // Build an unanalyzed expression if either operand is type-dependent.
4208   if (getLangOpts().CPlusPlus &&
4209       (base->isTypeDependent() || idx->isTypeDependent())) {
4210     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4211                                             VK_LValue, OK_Ordinary, rbLoc);
4212   }
4213 
4214   // MSDN, property (C++)
4215   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4216   // This attribute can also be used in the declaration of an empty array in a
4217   // class or structure definition. For example:
4218   // __declspec(property(get=GetX, put=PutX)) int x[];
4219   // The above statement indicates that x[] can be used with one or more array
4220   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4221   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4222   if (IsMSPropertySubscript) {
4223     // Build MS property subscript expression if base is MS property reference
4224     // or MS property subscript.
4225     return new (Context) MSPropertySubscriptExpr(
4226         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4227   }
4228 
4229   // Use C++ overloaded-operator rules if either operand has record
4230   // type.  The spec says to do this if either type is *overloadable*,
4231   // but enum types can't declare subscript operators or conversion
4232   // operators, so there's nothing interesting for overload resolution
4233   // to do if there aren't any record types involved.
4234   //
4235   // ObjC pointers have their own subscripting logic that is not tied
4236   // to overload resolution and so should not take this path.
4237   if (getLangOpts().CPlusPlus &&
4238       (base->getType()->isRecordType() ||
4239        (!base->getType()->isObjCObjectPointerType() &&
4240         idx->getType()->isRecordType()))) {
4241     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4242   }
4243 
4244   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4245 }
4246 
4247 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4248                                           Expr *LowerBound,
4249                                           SourceLocation ColonLoc, Expr *Length,
4250                                           SourceLocation RBLoc) {
4251   if (Base->getType()->isPlaceholderType() &&
4252       !Base->getType()->isSpecificPlaceholderType(
4253           BuiltinType::OMPArraySection)) {
4254     ExprResult Result = CheckPlaceholderExpr(Base);
4255     if (Result.isInvalid())
4256       return ExprError();
4257     Base = Result.get();
4258   }
4259   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4260     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4261     if (Result.isInvalid())
4262       return ExprError();
4263     Result = DefaultLvalueConversion(Result.get());
4264     if (Result.isInvalid())
4265       return ExprError();
4266     LowerBound = Result.get();
4267   }
4268   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4269     ExprResult Result = CheckPlaceholderExpr(Length);
4270     if (Result.isInvalid())
4271       return ExprError();
4272     Result = DefaultLvalueConversion(Result.get());
4273     if (Result.isInvalid())
4274       return ExprError();
4275     Length = Result.get();
4276   }
4277 
4278   // Build an unanalyzed expression if either operand is type-dependent.
4279   if (Base->isTypeDependent() ||
4280       (LowerBound &&
4281        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4282       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4283     return new (Context)
4284         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4285                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4286   }
4287 
4288   // Perform default conversions.
4289   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4290   QualType ResultTy;
4291   if (OriginalTy->isAnyPointerType()) {
4292     ResultTy = OriginalTy->getPointeeType();
4293   } else if (OriginalTy->isArrayType()) {
4294     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4295   } else {
4296     return ExprError(
4297         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4298         << Base->getSourceRange());
4299   }
4300   // C99 6.5.2.1p1
4301   if (LowerBound) {
4302     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4303                                                       LowerBound);
4304     if (Res.isInvalid())
4305       return ExprError(Diag(LowerBound->getExprLoc(),
4306                             diag::err_omp_typecheck_section_not_integer)
4307                        << 0 << LowerBound->getSourceRange());
4308     LowerBound = Res.get();
4309 
4310     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4311         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4312       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4313           << 0 << LowerBound->getSourceRange();
4314   }
4315   if (Length) {
4316     auto Res =
4317         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4318     if (Res.isInvalid())
4319       return ExprError(Diag(Length->getExprLoc(),
4320                             diag::err_omp_typecheck_section_not_integer)
4321                        << 1 << Length->getSourceRange());
4322     Length = Res.get();
4323 
4324     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4325         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4326       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4327           << 1 << Length->getSourceRange();
4328   }
4329 
4330   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4331   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4332   // type. Note that functions are not objects, and that (in C99 parlance)
4333   // incomplete types are not object types.
4334   if (ResultTy->isFunctionType()) {
4335     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4336         << ResultTy << Base->getSourceRange();
4337     return ExprError();
4338   }
4339 
4340   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4341                           diag::err_omp_section_incomplete_type, Base))
4342     return ExprError();
4343 
4344   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4345     llvm::APSInt LowerBoundValue;
4346     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4347       // OpenMP 4.5, [2.4 Array Sections]
4348       // The array section must be a subset of the original array.
4349       if (LowerBoundValue.isNegative()) {
4350         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4351             << LowerBound->getSourceRange();
4352         return ExprError();
4353       }
4354     }
4355   }
4356 
4357   if (Length) {
4358     llvm::APSInt LengthValue;
4359     if (Length->EvaluateAsInt(LengthValue, Context)) {
4360       // OpenMP 4.5, [2.4 Array Sections]
4361       // The length must evaluate to non-negative integers.
4362       if (LengthValue.isNegative()) {
4363         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4364             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4365             << Length->getSourceRange();
4366         return ExprError();
4367       }
4368     }
4369   } else if (ColonLoc.isValid() &&
4370              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4371                                       !OriginalTy->isVariableArrayType()))) {
4372     // OpenMP 4.5, [2.4 Array Sections]
4373     // When the size of the array dimension is not known, the length must be
4374     // specified explicitly.
4375     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4376         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4377     return ExprError();
4378   }
4379 
4380   if (!Base->getType()->isSpecificPlaceholderType(
4381           BuiltinType::OMPArraySection)) {
4382     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4383     if (Result.isInvalid())
4384       return ExprError();
4385     Base = Result.get();
4386   }
4387   return new (Context)
4388       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4389                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4390 }
4391 
4392 ExprResult
4393 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4394                                       Expr *Idx, SourceLocation RLoc) {
4395   Expr *LHSExp = Base;
4396   Expr *RHSExp = Idx;
4397 
4398   ExprValueKind VK = VK_LValue;
4399   ExprObjectKind OK = OK_Ordinary;
4400 
4401   // Per C++ core issue 1213, the result is an xvalue if either operand is
4402   // a non-lvalue array, and an lvalue otherwise.
4403   if (getLangOpts().CPlusPlus11 &&
4404       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4405        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4406     VK = VK_XValue;
4407 
4408   // Perform default conversions.
4409   if (!LHSExp->getType()->getAs<VectorType>()) {
4410     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4411     if (Result.isInvalid())
4412       return ExprError();
4413     LHSExp = Result.get();
4414   }
4415   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4416   if (Result.isInvalid())
4417     return ExprError();
4418   RHSExp = Result.get();
4419 
4420   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4421 
4422   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4423   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4424   // in the subscript position. As a result, we need to derive the array base
4425   // and index from the expression types.
4426   Expr *BaseExpr, *IndexExpr;
4427   QualType ResultType;
4428   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4429     BaseExpr = LHSExp;
4430     IndexExpr = RHSExp;
4431     ResultType = Context.DependentTy;
4432   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4433     BaseExpr = LHSExp;
4434     IndexExpr = RHSExp;
4435     ResultType = PTy->getPointeeType();
4436   } else if (const ObjCObjectPointerType *PTy =
4437                LHSTy->getAs<ObjCObjectPointerType>()) {
4438     BaseExpr = LHSExp;
4439     IndexExpr = RHSExp;
4440 
4441     // Use custom logic if this should be the pseudo-object subscript
4442     // expression.
4443     if (!LangOpts.isSubscriptPointerArithmetic())
4444       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4445                                           nullptr);
4446 
4447     ResultType = PTy->getPointeeType();
4448   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4449      // Handle the uncommon case of "123[Ptr]".
4450     BaseExpr = RHSExp;
4451     IndexExpr = LHSExp;
4452     ResultType = PTy->getPointeeType();
4453   } else if (const ObjCObjectPointerType *PTy =
4454                RHSTy->getAs<ObjCObjectPointerType>()) {
4455      // Handle the uncommon case of "123[Ptr]".
4456     BaseExpr = RHSExp;
4457     IndexExpr = LHSExp;
4458     ResultType = PTy->getPointeeType();
4459     if (!LangOpts.isSubscriptPointerArithmetic()) {
4460       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4461         << ResultType << BaseExpr->getSourceRange();
4462       return ExprError();
4463     }
4464   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4465     BaseExpr = LHSExp;    // vectors: V[123]
4466     IndexExpr = RHSExp;
4467     VK = LHSExp->getValueKind();
4468     if (VK != VK_RValue)
4469       OK = OK_VectorComponent;
4470 
4471     // FIXME: need to deal with const...
4472     ResultType = VTy->getElementType();
4473   } else if (LHSTy->isArrayType()) {
4474     // If we see an array that wasn't promoted by
4475     // DefaultFunctionArrayLvalueConversion, it must be an array that
4476     // wasn't promoted because of the C90 rule that doesn't
4477     // allow promoting non-lvalue arrays.  Warn, then
4478     // force the promotion here.
4479     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4480         LHSExp->getSourceRange();
4481     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4482                                CK_ArrayToPointerDecay).get();
4483     LHSTy = LHSExp->getType();
4484 
4485     BaseExpr = LHSExp;
4486     IndexExpr = RHSExp;
4487     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4488   } else if (RHSTy->isArrayType()) {
4489     // Same as previous, except for 123[f().a] case
4490     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4491         RHSExp->getSourceRange();
4492     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4493                                CK_ArrayToPointerDecay).get();
4494     RHSTy = RHSExp->getType();
4495 
4496     BaseExpr = RHSExp;
4497     IndexExpr = LHSExp;
4498     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4499   } else {
4500     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4501        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4502   }
4503   // C99 6.5.2.1p1
4504   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4505     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4506                      << IndexExpr->getSourceRange());
4507 
4508   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4509        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4510          && !IndexExpr->isTypeDependent())
4511     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4512 
4513   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4514   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4515   // type. Note that Functions are not objects, and that (in C99 parlance)
4516   // incomplete types are not object types.
4517   if (ResultType->isFunctionType()) {
4518     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4519       << ResultType << BaseExpr->getSourceRange();
4520     return ExprError();
4521   }
4522 
4523   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4524     // GNU extension: subscripting on pointer to void
4525     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4526       << BaseExpr->getSourceRange();
4527 
4528     // C forbids expressions of unqualified void type from being l-values.
4529     // See IsCForbiddenLValueType.
4530     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4531   } else if (!ResultType->isDependentType() &&
4532       RequireCompleteType(LLoc, ResultType,
4533                           diag::err_subscript_incomplete_type, BaseExpr))
4534     return ExprError();
4535 
4536   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4537          !ResultType.isCForbiddenLValueType());
4538 
4539   return new (Context)
4540       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4541 }
4542 
4543 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4544                                   ParmVarDecl *Param) {
4545   if (Param->hasUnparsedDefaultArg()) {
4546     Diag(CallLoc,
4547          diag::err_use_of_default_argument_to_function_declared_later) <<
4548       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4549     Diag(UnparsedDefaultArgLocs[Param],
4550          diag::note_default_argument_declared_here);
4551     return true;
4552   }
4553 
4554   if (Param->hasUninstantiatedDefaultArg()) {
4555     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4556 
4557     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4558                                                  Param);
4559 
4560     // Instantiate the expression.
4561     MultiLevelTemplateArgumentList MutiLevelArgList
4562       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4563 
4564     InstantiatingTemplate Inst(*this, CallLoc, Param,
4565                                MutiLevelArgList.getInnermost());
4566     if (Inst.isInvalid())
4567       return true;
4568     if (Inst.isAlreadyInstantiating()) {
4569       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4570       Param->setInvalidDecl();
4571       return true;
4572     }
4573 
4574     ExprResult Result;
4575     {
4576       // C++ [dcl.fct.default]p5:
4577       //   The names in the [default argument] expression are bound, and
4578       //   the semantic constraints are checked, at the point where the
4579       //   default argument expression appears.
4580       ContextRAII SavedContext(*this, FD);
4581       LocalInstantiationScope Local(*this);
4582       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4583                                 /*DirectInit*/false);
4584     }
4585     if (Result.isInvalid())
4586       return true;
4587 
4588     // Check the expression as an initializer for the parameter.
4589     InitializedEntity Entity
4590       = InitializedEntity::InitializeParameter(Context, Param);
4591     InitializationKind Kind
4592       = InitializationKind::CreateCopy(Param->getLocation(),
4593              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4594     Expr *ResultE = Result.getAs<Expr>();
4595 
4596     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4597     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4598     if (Result.isInvalid())
4599       return true;
4600 
4601     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4602                                  Param->getOuterLocStart());
4603     if (Result.isInvalid())
4604       return true;
4605 
4606     // Remember the instantiated default argument.
4607     Param->setDefaultArg(Result.getAs<Expr>());
4608     if (ASTMutationListener *L = getASTMutationListener()) {
4609       L->DefaultArgumentInstantiated(Param);
4610     }
4611   }
4612 
4613   // If the default argument expression is not set yet, we are building it now.
4614   if (!Param->hasInit()) {
4615     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4616     Param->setInvalidDecl();
4617     return true;
4618   }
4619 
4620   // If the default expression creates temporaries, we need to
4621   // push them to the current stack of expression temporaries so they'll
4622   // be properly destroyed.
4623   // FIXME: We should really be rebuilding the default argument with new
4624   // bound temporaries; see the comment in PR5810.
4625   // We don't need to do that with block decls, though, because
4626   // blocks in default argument expression can never capture anything.
4627   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4628     // Set the "needs cleanups" bit regardless of whether there are
4629     // any explicit objects.
4630     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4631 
4632     // Append all the objects to the cleanup list.  Right now, this
4633     // should always be a no-op, because blocks in default argument
4634     // expressions should never be able to capture anything.
4635     assert(!Init->getNumObjects() &&
4636            "default argument expression has capturing blocks?");
4637   }
4638 
4639   // We already type-checked the argument, so we know it works.
4640   // Just mark all of the declarations in this potentially-evaluated expression
4641   // as being "referenced".
4642   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4643                                    /*SkipLocalVariables=*/true);
4644   return false;
4645 }
4646 
4647 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4648                                         FunctionDecl *FD, ParmVarDecl *Param) {
4649   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4650     return ExprError();
4651   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4652 }
4653 
4654 Sema::VariadicCallType
4655 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4656                           Expr *Fn) {
4657   if (Proto && Proto->isVariadic()) {
4658     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4659       return VariadicConstructor;
4660     else if (Fn && Fn->getType()->isBlockPointerType())
4661       return VariadicBlock;
4662     else if (FDecl) {
4663       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4664         if (Method->isInstance())
4665           return VariadicMethod;
4666     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4667       return VariadicMethod;
4668     return VariadicFunction;
4669   }
4670   return VariadicDoesNotApply;
4671 }
4672 
4673 namespace {
4674 class FunctionCallCCC : public FunctionCallFilterCCC {
4675 public:
4676   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4677                   unsigned NumArgs, MemberExpr *ME)
4678       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4679         FunctionName(FuncName) {}
4680 
4681   bool ValidateCandidate(const TypoCorrection &candidate) override {
4682     if (!candidate.getCorrectionSpecifier() ||
4683         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4684       return false;
4685     }
4686 
4687     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4688   }
4689 
4690 private:
4691   const IdentifierInfo *const FunctionName;
4692 };
4693 }
4694 
4695 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4696                                                FunctionDecl *FDecl,
4697                                                ArrayRef<Expr *> Args) {
4698   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4699   DeclarationName FuncName = FDecl->getDeclName();
4700   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4701 
4702   if (TypoCorrection Corrected = S.CorrectTypo(
4703           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4704           S.getScopeForContext(S.CurContext), nullptr,
4705           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4706                                              Args.size(), ME),
4707           Sema::CTK_ErrorRecovery)) {
4708     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4709       if (Corrected.isOverloaded()) {
4710         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4711         OverloadCandidateSet::iterator Best;
4712         for (NamedDecl *CD : Corrected) {
4713           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4714             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4715                                    OCS);
4716         }
4717         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4718         case OR_Success:
4719           ND = Best->FoundDecl;
4720           Corrected.setCorrectionDecl(ND);
4721           break;
4722         default:
4723           break;
4724         }
4725       }
4726       ND = ND->getUnderlyingDecl();
4727       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4728         return Corrected;
4729     }
4730   }
4731   return TypoCorrection();
4732 }
4733 
4734 /// ConvertArgumentsForCall - Converts the arguments specified in
4735 /// Args/NumArgs to the parameter types of the function FDecl with
4736 /// function prototype Proto. Call is the call expression itself, and
4737 /// Fn is the function expression. For a C++ member function, this
4738 /// routine does not attempt to convert the object argument. Returns
4739 /// true if the call is ill-formed.
4740 bool
4741 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4742                               FunctionDecl *FDecl,
4743                               const FunctionProtoType *Proto,
4744                               ArrayRef<Expr *> Args,
4745                               SourceLocation RParenLoc,
4746                               bool IsExecConfig) {
4747   // Bail out early if calling a builtin with custom typechecking.
4748   if (FDecl)
4749     if (unsigned ID = FDecl->getBuiltinID())
4750       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4751         return false;
4752 
4753   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4754   // assignment, to the types of the corresponding parameter, ...
4755   unsigned NumParams = Proto->getNumParams();
4756   bool Invalid = false;
4757   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4758   unsigned FnKind = Fn->getType()->isBlockPointerType()
4759                        ? 1 /* block */
4760                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4761                                        : 0 /* function */);
4762 
4763   // If too few arguments are available (and we don't have default
4764   // arguments for the remaining parameters), don't make the call.
4765   if (Args.size() < NumParams) {
4766     if (Args.size() < MinArgs) {
4767       TypoCorrection TC;
4768       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4769         unsigned diag_id =
4770             MinArgs == NumParams && !Proto->isVariadic()
4771                 ? diag::err_typecheck_call_too_few_args_suggest
4772                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4773         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4774                                         << static_cast<unsigned>(Args.size())
4775                                         << TC.getCorrectionRange());
4776       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4777         Diag(RParenLoc,
4778              MinArgs == NumParams && !Proto->isVariadic()
4779                  ? diag::err_typecheck_call_too_few_args_one
4780                  : diag::err_typecheck_call_too_few_args_at_least_one)
4781             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4782       else
4783         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4784                             ? diag::err_typecheck_call_too_few_args
4785                             : diag::err_typecheck_call_too_few_args_at_least)
4786             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4787             << Fn->getSourceRange();
4788 
4789       // Emit the location of the prototype.
4790       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4791         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4792           << FDecl;
4793 
4794       return true;
4795     }
4796     Call->setNumArgs(Context, NumParams);
4797   }
4798 
4799   // If too many are passed and not variadic, error on the extras and drop
4800   // them.
4801   if (Args.size() > NumParams) {
4802     if (!Proto->isVariadic()) {
4803       TypoCorrection TC;
4804       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4805         unsigned diag_id =
4806             MinArgs == NumParams && !Proto->isVariadic()
4807                 ? diag::err_typecheck_call_too_many_args_suggest
4808                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4809         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4810                                         << static_cast<unsigned>(Args.size())
4811                                         << TC.getCorrectionRange());
4812       } else if (NumParams == 1 && FDecl &&
4813                  FDecl->getParamDecl(0)->getDeclName())
4814         Diag(Args[NumParams]->getLocStart(),
4815              MinArgs == NumParams
4816                  ? diag::err_typecheck_call_too_many_args_one
4817                  : diag::err_typecheck_call_too_many_args_at_most_one)
4818             << FnKind << FDecl->getParamDecl(0)
4819             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4820             << SourceRange(Args[NumParams]->getLocStart(),
4821                            Args.back()->getLocEnd());
4822       else
4823         Diag(Args[NumParams]->getLocStart(),
4824              MinArgs == NumParams
4825                  ? diag::err_typecheck_call_too_many_args
4826                  : diag::err_typecheck_call_too_many_args_at_most)
4827             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4828             << Fn->getSourceRange()
4829             << SourceRange(Args[NumParams]->getLocStart(),
4830                            Args.back()->getLocEnd());
4831 
4832       // Emit the location of the prototype.
4833       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4834         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4835           << FDecl;
4836 
4837       // This deletes the extra arguments.
4838       Call->setNumArgs(Context, NumParams);
4839       return true;
4840     }
4841   }
4842   SmallVector<Expr *, 8> AllArgs;
4843   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4844 
4845   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4846                                    Proto, 0, Args, AllArgs, CallType);
4847   if (Invalid)
4848     return true;
4849   unsigned TotalNumArgs = AllArgs.size();
4850   for (unsigned i = 0; i < TotalNumArgs; ++i)
4851     Call->setArg(i, AllArgs[i]);
4852 
4853   return false;
4854 }
4855 
4856 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4857                                   const FunctionProtoType *Proto,
4858                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4859                                   SmallVectorImpl<Expr *> &AllArgs,
4860                                   VariadicCallType CallType, bool AllowExplicit,
4861                                   bool IsListInitialization) {
4862   unsigned NumParams = Proto->getNumParams();
4863   bool Invalid = false;
4864   size_t ArgIx = 0;
4865   // Continue to check argument types (even if we have too few/many args).
4866   for (unsigned i = FirstParam; i < NumParams; i++) {
4867     QualType ProtoArgType = Proto->getParamType(i);
4868 
4869     Expr *Arg;
4870     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4871     if (ArgIx < Args.size()) {
4872       Arg = Args[ArgIx++];
4873 
4874       if (RequireCompleteType(Arg->getLocStart(),
4875                               ProtoArgType,
4876                               diag::err_call_incomplete_argument, Arg))
4877         return true;
4878 
4879       // Strip the unbridged-cast placeholder expression off, if applicable.
4880       bool CFAudited = false;
4881       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4882           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4883           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4884         Arg = stripARCUnbridgedCast(Arg);
4885       else if (getLangOpts().ObjCAutoRefCount &&
4886                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4887                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4888         CFAudited = true;
4889 
4890       InitializedEntity Entity =
4891           Param ? InitializedEntity::InitializeParameter(Context, Param,
4892                                                          ProtoArgType)
4893                 : InitializedEntity::InitializeParameter(
4894                       Context, ProtoArgType, Proto->isParamConsumed(i));
4895 
4896       // Remember that parameter belongs to a CF audited API.
4897       if (CFAudited)
4898         Entity.setParameterCFAudited();
4899 
4900       ExprResult ArgE = PerformCopyInitialization(
4901           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4902       if (ArgE.isInvalid())
4903         return true;
4904 
4905       Arg = ArgE.getAs<Expr>();
4906     } else {
4907       assert(Param && "can't use default arguments without a known callee");
4908 
4909       ExprResult ArgExpr =
4910         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4911       if (ArgExpr.isInvalid())
4912         return true;
4913 
4914       Arg = ArgExpr.getAs<Expr>();
4915     }
4916 
4917     // Check for array bounds violations for each argument to the call. This
4918     // check only triggers warnings when the argument isn't a more complex Expr
4919     // with its own checking, such as a BinaryOperator.
4920     CheckArrayAccess(Arg);
4921 
4922     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4923     CheckStaticArrayArgument(CallLoc, Param, Arg);
4924 
4925     AllArgs.push_back(Arg);
4926   }
4927 
4928   // If this is a variadic call, handle args passed through "...".
4929   if (CallType != VariadicDoesNotApply) {
4930     // Assume that extern "C" functions with variadic arguments that
4931     // return __unknown_anytype aren't *really* variadic.
4932     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4933         FDecl->isExternC()) {
4934       for (Expr *A : Args.slice(ArgIx)) {
4935         QualType paramType; // ignored
4936         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4937         Invalid |= arg.isInvalid();
4938         AllArgs.push_back(arg.get());
4939       }
4940 
4941     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4942     } else {
4943       for (Expr *A : Args.slice(ArgIx)) {
4944         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4945         Invalid |= Arg.isInvalid();
4946         AllArgs.push_back(Arg.get());
4947       }
4948     }
4949 
4950     // Check for array bounds violations.
4951     for (Expr *A : Args.slice(ArgIx))
4952       CheckArrayAccess(A);
4953   }
4954   return Invalid;
4955 }
4956 
4957 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4958   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4959   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4960     TL = DTL.getOriginalLoc();
4961   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4962     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4963       << ATL.getLocalSourceRange();
4964 }
4965 
4966 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4967 /// array parameter, check that it is non-null, and that if it is formed by
4968 /// array-to-pointer decay, the underlying array is sufficiently large.
4969 ///
4970 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4971 /// array type derivation, then for each call to the function, the value of the
4972 /// corresponding actual argument shall provide access to the first element of
4973 /// an array with at least as many elements as specified by the size expression.
4974 void
4975 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4976                                ParmVarDecl *Param,
4977                                const Expr *ArgExpr) {
4978   // Static array parameters are not supported in C++.
4979   if (!Param || getLangOpts().CPlusPlus)
4980     return;
4981 
4982   QualType OrigTy = Param->getOriginalType();
4983 
4984   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4985   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4986     return;
4987 
4988   if (ArgExpr->isNullPointerConstant(Context,
4989                                      Expr::NPC_NeverValueDependent)) {
4990     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4991     DiagnoseCalleeStaticArrayParam(*this, Param);
4992     return;
4993   }
4994 
4995   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4996   if (!CAT)
4997     return;
4998 
4999   const ConstantArrayType *ArgCAT =
5000     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5001   if (!ArgCAT)
5002     return;
5003 
5004   if (ArgCAT->getSize().ult(CAT->getSize())) {
5005     Diag(CallLoc, diag::warn_static_array_too_small)
5006       << ArgExpr->getSourceRange()
5007       << (unsigned) ArgCAT->getSize().getZExtValue()
5008       << (unsigned) CAT->getSize().getZExtValue();
5009     DiagnoseCalleeStaticArrayParam(*this, Param);
5010   }
5011 }
5012 
5013 /// Given a function expression of unknown-any type, try to rebuild it
5014 /// to have a function type.
5015 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5016 
5017 /// Is the given type a placeholder that we need to lower out
5018 /// immediately during argument processing?
5019 static bool isPlaceholderToRemoveAsArg(QualType type) {
5020   // Placeholders are never sugared.
5021   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5022   if (!placeholder) return false;
5023 
5024   switch (placeholder->getKind()) {
5025   // Ignore all the non-placeholder types.
5026 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5027   case BuiltinType::Id:
5028 #include "clang/Basic/OpenCLImageTypes.def"
5029 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5030 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5031 #include "clang/AST/BuiltinTypes.def"
5032     return false;
5033 
5034   // We cannot lower out overload sets; they might validly be resolved
5035   // by the call machinery.
5036   case BuiltinType::Overload:
5037     return false;
5038 
5039   // Unbridged casts in ARC can be handled in some call positions and
5040   // should be left in place.
5041   case BuiltinType::ARCUnbridgedCast:
5042     return false;
5043 
5044   // Pseudo-objects should be converted as soon as possible.
5045   case BuiltinType::PseudoObject:
5046     return true;
5047 
5048   // The debugger mode could theoretically but currently does not try
5049   // to resolve unknown-typed arguments based on known parameter types.
5050   case BuiltinType::UnknownAny:
5051     return true;
5052 
5053   // These are always invalid as call arguments and should be reported.
5054   case BuiltinType::BoundMember:
5055   case BuiltinType::BuiltinFn:
5056   case BuiltinType::OMPArraySection:
5057     return true;
5058 
5059   }
5060   llvm_unreachable("bad builtin type kind");
5061 }
5062 
5063 /// Check an argument list for placeholders that we won't try to
5064 /// handle later.
5065 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5066   // Apply this processing to all the arguments at once instead of
5067   // dying at the first failure.
5068   bool hasInvalid = false;
5069   for (size_t i = 0, e = args.size(); i != e; i++) {
5070     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5071       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5072       if (result.isInvalid()) hasInvalid = true;
5073       else args[i] = result.get();
5074     } else if (hasInvalid) {
5075       (void)S.CorrectDelayedTyposInExpr(args[i]);
5076     }
5077   }
5078   return hasInvalid;
5079 }
5080 
5081 /// If a builtin function has a pointer argument with no explicit address
5082 /// space, then it should be able to accept a pointer to any address
5083 /// space as input.  In order to do this, we need to replace the
5084 /// standard builtin declaration with one that uses the same address space
5085 /// as the call.
5086 ///
5087 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5088 ///                  it does not contain any pointer arguments without
5089 ///                  an address space qualifer.  Otherwise the rewritten
5090 ///                  FunctionDecl is returned.
5091 /// TODO: Handle pointer return types.
5092 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5093                                                 const FunctionDecl *FDecl,
5094                                                 MultiExprArg ArgExprs) {
5095 
5096   QualType DeclType = FDecl->getType();
5097   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5098 
5099   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5100       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5101     return nullptr;
5102 
5103   bool NeedsNewDecl = false;
5104   unsigned i = 0;
5105   SmallVector<QualType, 8> OverloadParams;
5106 
5107   for (QualType ParamType : FT->param_types()) {
5108 
5109     // Convert array arguments to pointer to simplify type lookup.
5110     ExprResult ArgRes =
5111         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5112     if (ArgRes.isInvalid())
5113       return nullptr;
5114     Expr *Arg = ArgRes.get();
5115     QualType ArgType = Arg->getType();
5116     if (!ParamType->isPointerType() ||
5117         ParamType.getQualifiers().hasAddressSpace() ||
5118         !ArgType->isPointerType() ||
5119         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5120       OverloadParams.push_back(ParamType);
5121       continue;
5122     }
5123 
5124     NeedsNewDecl = true;
5125     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5126 
5127     QualType PointeeType = ParamType->getPointeeType();
5128     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5129     OverloadParams.push_back(Context.getPointerType(PointeeType));
5130   }
5131 
5132   if (!NeedsNewDecl)
5133     return nullptr;
5134 
5135   FunctionProtoType::ExtProtoInfo EPI;
5136   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5137                                                 OverloadParams, EPI);
5138   DeclContext *Parent = Context.getTranslationUnitDecl();
5139   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5140                                                     FDecl->getLocation(),
5141                                                     FDecl->getLocation(),
5142                                                     FDecl->getIdentifier(),
5143                                                     OverloadTy,
5144                                                     /*TInfo=*/nullptr,
5145                                                     SC_Extern, false,
5146                                                     /*hasPrototype=*/true);
5147   SmallVector<ParmVarDecl*, 16> Params;
5148   FT = cast<FunctionProtoType>(OverloadTy);
5149   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5150     QualType ParamType = FT->getParamType(i);
5151     ParmVarDecl *Parm =
5152         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5153                                 SourceLocation(), nullptr, ParamType,
5154                                 /*TInfo=*/nullptr, SC_None, nullptr);
5155     Parm->setScopeInfo(0, i);
5156     Params.push_back(Parm);
5157   }
5158   OverloadDecl->setParams(Params);
5159   return OverloadDecl;
5160 }
5161 
5162 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5163                                     FunctionDecl *Callee,
5164                                     MultiExprArg ArgExprs) {
5165   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5166   // similar attributes) really don't like it when functions are called with an
5167   // invalid number of args.
5168   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5169                          /*PartialOverloading=*/false) &&
5170       !Callee->isVariadic())
5171     return;
5172   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5173     return;
5174 
5175   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5176     S.Diag(Fn->getLocStart(),
5177            isa<CXXMethodDecl>(Callee)
5178                ? diag::err_ovl_no_viable_member_function_in_call
5179                : diag::err_ovl_no_viable_function_in_call)
5180         << Callee << Callee->getSourceRange();
5181     S.Diag(Callee->getLocation(),
5182            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5183         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5184     return;
5185   }
5186 }
5187 
5188 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5189 /// This provides the location of the left/right parens and a list of comma
5190 /// locations.
5191 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5192                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5193                                Expr *ExecConfig, bool IsExecConfig) {
5194   // Since this might be a postfix expression, get rid of ParenListExprs.
5195   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5196   if (Result.isInvalid()) return ExprError();
5197   Fn = Result.get();
5198 
5199   if (checkArgsForPlaceholders(*this, ArgExprs))
5200     return ExprError();
5201 
5202   if (getLangOpts().CPlusPlus) {
5203     // If this is a pseudo-destructor expression, build the call immediately.
5204     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5205       if (!ArgExprs.empty()) {
5206         // Pseudo-destructor calls should not have any arguments.
5207         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5208             << FixItHint::CreateRemoval(
5209                    SourceRange(ArgExprs.front()->getLocStart(),
5210                                ArgExprs.back()->getLocEnd()));
5211       }
5212 
5213       return new (Context)
5214           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5215     }
5216     if (Fn->getType() == Context.PseudoObjectTy) {
5217       ExprResult result = CheckPlaceholderExpr(Fn);
5218       if (result.isInvalid()) return ExprError();
5219       Fn = result.get();
5220     }
5221 
5222     // Determine whether this is a dependent call inside a C++ template,
5223     // in which case we won't do any semantic analysis now.
5224     bool Dependent = false;
5225     if (Fn->isTypeDependent())
5226       Dependent = true;
5227     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5228       Dependent = true;
5229 
5230     if (Dependent) {
5231       if (ExecConfig) {
5232         return new (Context) CUDAKernelCallExpr(
5233             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5234             Context.DependentTy, VK_RValue, RParenLoc);
5235       } else {
5236         return new (Context) CallExpr(
5237             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5238       }
5239     }
5240 
5241     // Determine whether this is a call to an object (C++ [over.call.object]).
5242     if (Fn->getType()->isRecordType())
5243       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5244                                           RParenLoc);
5245 
5246     if (Fn->getType() == Context.UnknownAnyTy) {
5247       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5248       if (result.isInvalid()) return ExprError();
5249       Fn = result.get();
5250     }
5251 
5252     if (Fn->getType() == Context.BoundMemberTy) {
5253       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5254                                        RParenLoc);
5255     }
5256   }
5257 
5258   // Check for overloaded calls.  This can happen even in C due to extensions.
5259   if (Fn->getType() == Context.OverloadTy) {
5260     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5261 
5262     // We aren't supposed to apply this logic for if there'Scope an '&'
5263     // involved.
5264     if (!find.HasFormOfMemberPointer) {
5265       OverloadExpr *ovl = find.Expression;
5266       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5267         return BuildOverloadedCallExpr(
5268             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5269             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5270       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5271                                        RParenLoc);
5272     }
5273   }
5274 
5275   // If we're directly calling a function, get the appropriate declaration.
5276   if (Fn->getType() == Context.UnknownAnyTy) {
5277     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5278     if (result.isInvalid()) return ExprError();
5279     Fn = result.get();
5280   }
5281 
5282   Expr *NakedFn = Fn->IgnoreParens();
5283 
5284   bool CallingNDeclIndirectly = false;
5285   NamedDecl *NDecl = nullptr;
5286   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5287     if (UnOp->getOpcode() == UO_AddrOf) {
5288       CallingNDeclIndirectly = true;
5289       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5290     }
5291   }
5292 
5293   if (isa<DeclRefExpr>(NakedFn)) {
5294     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5295 
5296     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5297     if (FDecl && FDecl->getBuiltinID()) {
5298       // Rewrite the function decl for this builtin by replacing parameters
5299       // with no explicit address space with the address space of the arguments
5300       // in ArgExprs.
5301       if ((FDecl =
5302                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5303         NDecl = FDecl;
5304         Fn = DeclRefExpr::Create(
5305             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5306             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5307       }
5308     }
5309   } else if (isa<MemberExpr>(NakedFn))
5310     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5311 
5312   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5313     if (CallingNDeclIndirectly &&
5314         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5315                                            Fn->getLocStart()))
5316       return ExprError();
5317 
5318     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5319       return ExprError();
5320 
5321     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5322   }
5323 
5324   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5325                                ExecConfig, IsExecConfig);
5326 }
5327 
5328 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5329 ///
5330 /// __builtin_astype( value, dst type )
5331 ///
5332 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5333                                  SourceLocation BuiltinLoc,
5334                                  SourceLocation RParenLoc) {
5335   ExprValueKind VK = VK_RValue;
5336   ExprObjectKind OK = OK_Ordinary;
5337   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5338   QualType SrcTy = E->getType();
5339   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5340     return ExprError(Diag(BuiltinLoc,
5341                           diag::err_invalid_astype_of_different_size)
5342                      << DstTy
5343                      << SrcTy
5344                      << E->getSourceRange());
5345   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5346 }
5347 
5348 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5349 /// provided arguments.
5350 ///
5351 /// __builtin_convertvector( value, dst type )
5352 ///
5353 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5354                                         SourceLocation BuiltinLoc,
5355                                         SourceLocation RParenLoc) {
5356   TypeSourceInfo *TInfo;
5357   GetTypeFromParser(ParsedDestTy, &TInfo);
5358   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5359 }
5360 
5361 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5362 /// i.e. an expression not of \p OverloadTy.  The expression should
5363 /// unary-convert to an expression of function-pointer or
5364 /// block-pointer type.
5365 ///
5366 /// \param NDecl the declaration being called, if available
5367 ExprResult
5368 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5369                             SourceLocation LParenLoc,
5370                             ArrayRef<Expr *> Args,
5371                             SourceLocation RParenLoc,
5372                             Expr *Config, bool IsExecConfig) {
5373   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5374   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5375 
5376   // Functions with 'interrupt' attribute cannot be called directly.
5377   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5378     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5379     return ExprError();
5380   }
5381 
5382   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5383   // so there's some risk when calling out to non-interrupt handler functions
5384   // that the callee might not preserve them. This is easy to diagnose here,
5385   // but can be very challenging to debug.
5386   if (auto *Caller = getCurFunctionDecl())
5387     if (Caller->hasAttr<ARMInterruptAttr>())
5388       if (!FDecl->hasAttr<ARMInterruptAttr>())
5389         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5390 
5391   // Promote the function operand.
5392   // We special-case function promotion here because we only allow promoting
5393   // builtin functions to function pointers in the callee of a call.
5394   ExprResult Result;
5395   if (BuiltinID &&
5396       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5397     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5398                                CK_BuiltinFnToFnPtr).get();
5399   } else {
5400     Result = CallExprUnaryConversions(Fn);
5401   }
5402   if (Result.isInvalid())
5403     return ExprError();
5404   Fn = Result.get();
5405 
5406   // Make the call expr early, before semantic checks.  This guarantees cleanup
5407   // of arguments and function on error.
5408   CallExpr *TheCall;
5409   if (Config)
5410     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5411                                                cast<CallExpr>(Config), Args,
5412                                                Context.BoolTy, VK_RValue,
5413                                                RParenLoc);
5414   else
5415     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5416                                      VK_RValue, RParenLoc);
5417 
5418   if (!getLangOpts().CPlusPlus) {
5419     // C cannot always handle TypoExpr nodes in builtin calls and direct
5420     // function calls as their argument checking don't necessarily handle
5421     // dependent types properly, so make sure any TypoExprs have been
5422     // dealt with.
5423     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5424     if (!Result.isUsable()) return ExprError();
5425     TheCall = dyn_cast<CallExpr>(Result.get());
5426     if (!TheCall) return Result;
5427     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5428   }
5429 
5430   // Bail out early if calling a builtin with custom typechecking.
5431   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5432     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5433 
5434  retry:
5435   const FunctionType *FuncT;
5436   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5437     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5438     // have type pointer to function".
5439     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5440     if (!FuncT)
5441       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5442                          << Fn->getType() << Fn->getSourceRange());
5443   } else if (const BlockPointerType *BPT =
5444                Fn->getType()->getAs<BlockPointerType>()) {
5445     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5446   } else {
5447     // Handle calls to expressions of unknown-any type.
5448     if (Fn->getType() == Context.UnknownAnyTy) {
5449       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5450       if (rewrite.isInvalid()) return ExprError();
5451       Fn = rewrite.get();
5452       TheCall->setCallee(Fn);
5453       goto retry;
5454     }
5455 
5456     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5457       << Fn->getType() << Fn->getSourceRange());
5458   }
5459 
5460   if (getLangOpts().CUDA) {
5461     if (Config) {
5462       // CUDA: Kernel calls must be to global functions
5463       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5464         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5465             << FDecl->getName() << Fn->getSourceRange());
5466 
5467       // CUDA: Kernel function must have 'void' return type
5468       if (!FuncT->getReturnType()->isVoidType())
5469         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5470             << Fn->getType() << Fn->getSourceRange());
5471     } else {
5472       // CUDA: Calls to global functions must be configured
5473       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5474         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5475             << FDecl->getName() << Fn->getSourceRange());
5476     }
5477   }
5478 
5479   // Check for a valid return type
5480   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5481                           FDecl))
5482     return ExprError();
5483 
5484   // We know the result type of the call, set it.
5485   TheCall->setType(FuncT->getCallResultType(Context));
5486   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5487 
5488   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5489   if (Proto) {
5490     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5491                                 IsExecConfig))
5492       return ExprError();
5493   } else {
5494     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5495 
5496     if (FDecl) {
5497       // Check if we have too few/too many template arguments, based
5498       // on our knowledge of the function definition.
5499       const FunctionDecl *Def = nullptr;
5500       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5501         Proto = Def->getType()->getAs<FunctionProtoType>();
5502        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5503           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5504           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5505       }
5506 
5507       // If the function we're calling isn't a function prototype, but we have
5508       // a function prototype from a prior declaratiom, use that prototype.
5509       if (!FDecl->hasPrototype())
5510         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5511     }
5512 
5513     // Promote the arguments (C99 6.5.2.2p6).
5514     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5515       Expr *Arg = Args[i];
5516 
5517       if (Proto && i < Proto->getNumParams()) {
5518         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5519             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5520         ExprResult ArgE =
5521             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5522         if (ArgE.isInvalid())
5523           return true;
5524 
5525         Arg = ArgE.getAs<Expr>();
5526 
5527       } else {
5528         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5529 
5530         if (ArgE.isInvalid())
5531           return true;
5532 
5533         Arg = ArgE.getAs<Expr>();
5534       }
5535 
5536       if (RequireCompleteType(Arg->getLocStart(),
5537                               Arg->getType(),
5538                               diag::err_call_incomplete_argument, Arg))
5539         return ExprError();
5540 
5541       TheCall->setArg(i, Arg);
5542     }
5543   }
5544 
5545   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5546     if (!Method->isStatic())
5547       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5548         << Fn->getSourceRange());
5549 
5550   // Check for sentinels
5551   if (NDecl)
5552     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5553 
5554   // Do special checking on direct calls to functions.
5555   if (FDecl) {
5556     if (CheckFunctionCall(FDecl, TheCall, Proto))
5557       return ExprError();
5558 
5559     if (BuiltinID)
5560       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5561   } else if (NDecl) {
5562     if (CheckPointerCall(NDecl, TheCall, Proto))
5563       return ExprError();
5564   } else {
5565     if (CheckOtherCall(TheCall, Proto))
5566       return ExprError();
5567   }
5568 
5569   return MaybeBindToTemporary(TheCall);
5570 }
5571 
5572 ExprResult
5573 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5574                            SourceLocation RParenLoc, Expr *InitExpr) {
5575   assert(Ty && "ActOnCompoundLiteral(): missing type");
5576   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5577 
5578   TypeSourceInfo *TInfo;
5579   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5580   if (!TInfo)
5581     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5582 
5583   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5584 }
5585 
5586 ExprResult
5587 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5588                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5589   QualType literalType = TInfo->getType();
5590 
5591   if (literalType->isArrayType()) {
5592     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5593           diag::err_illegal_decl_array_incomplete_type,
5594           SourceRange(LParenLoc,
5595                       LiteralExpr->getSourceRange().getEnd())))
5596       return ExprError();
5597     if (literalType->isVariableArrayType())
5598       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5599         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5600   } else if (!literalType->isDependentType() &&
5601              RequireCompleteType(LParenLoc, literalType,
5602                diag::err_typecheck_decl_incomplete_type,
5603                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5604     return ExprError();
5605 
5606   InitializedEntity Entity
5607     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5608   InitializationKind Kind
5609     = InitializationKind::CreateCStyleCast(LParenLoc,
5610                                            SourceRange(LParenLoc, RParenLoc),
5611                                            /*InitList=*/true);
5612   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5613   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5614                                       &literalType);
5615   if (Result.isInvalid())
5616     return ExprError();
5617   LiteralExpr = Result.get();
5618 
5619   bool isFileScope = !CurContext->isFunctionOrMethod();
5620   if (isFileScope &&
5621       !LiteralExpr->isTypeDependent() &&
5622       !LiteralExpr->isValueDependent() &&
5623       !literalType->isDependentType()) { // 6.5.2.5p3
5624     if (CheckForConstantInitializer(LiteralExpr, literalType))
5625       return ExprError();
5626   }
5627 
5628   // In C, compound literals are l-values for some reason.
5629   // For GCC compatibility, in C++, file-scope array compound literals with
5630   // constant initializers are also l-values, and compound literals are
5631   // otherwise prvalues.
5632   //
5633   // (GCC also treats C++ list-initialized file-scope array prvalues with
5634   // constant initializers as l-values, but that's non-conforming, so we don't
5635   // follow it there.)
5636   //
5637   // FIXME: It would be better to handle the lvalue cases as materializing and
5638   // lifetime-extending a temporary object, but our materialized temporaries
5639   // representation only supports lifetime extension from a variable, not "out
5640   // of thin air".
5641   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5642   // is bound to the result of applying array-to-pointer decay to the compound
5643   // literal.
5644   // FIXME: GCC supports compound literals of reference type, which should
5645   // obviously have a value kind derived from the kind of reference involved.
5646   ExprValueKind VK =
5647       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5648           ? VK_RValue
5649           : VK_LValue;
5650 
5651   return MaybeBindToTemporary(
5652       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5653                                         VK, LiteralExpr, isFileScope));
5654 }
5655 
5656 ExprResult
5657 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5658                     SourceLocation RBraceLoc) {
5659   // Immediately handle non-overload placeholders.  Overloads can be
5660   // resolved contextually, but everything else here can't.
5661   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5662     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5663       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5664 
5665       // Ignore failures; dropping the entire initializer list because
5666       // of one failure would be terrible for indexing/etc.
5667       if (result.isInvalid()) continue;
5668 
5669       InitArgList[I] = result.get();
5670     }
5671   }
5672 
5673   // Semantic analysis for initializers is done by ActOnDeclarator() and
5674   // CheckInitializer() - it requires knowledge of the object being intialized.
5675 
5676   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5677                                                RBraceLoc);
5678   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5679   return E;
5680 }
5681 
5682 /// Do an explicit extend of the given block pointer if we're in ARC.
5683 void Sema::maybeExtendBlockObject(ExprResult &E) {
5684   assert(E.get()->getType()->isBlockPointerType());
5685   assert(E.get()->isRValue());
5686 
5687   // Only do this in an r-value context.
5688   if (!getLangOpts().ObjCAutoRefCount) return;
5689 
5690   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5691                                CK_ARCExtendBlockObject, E.get(),
5692                                /*base path*/ nullptr, VK_RValue);
5693   Cleanup.setExprNeedsCleanups(true);
5694 }
5695 
5696 /// Prepare a conversion of the given expression to an ObjC object
5697 /// pointer type.
5698 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5699   QualType type = E.get()->getType();
5700   if (type->isObjCObjectPointerType()) {
5701     return CK_BitCast;
5702   } else if (type->isBlockPointerType()) {
5703     maybeExtendBlockObject(E);
5704     return CK_BlockPointerToObjCPointerCast;
5705   } else {
5706     assert(type->isPointerType());
5707     return CK_CPointerToObjCPointerCast;
5708   }
5709 }
5710 
5711 /// Prepares for a scalar cast, performing all the necessary stages
5712 /// except the final cast and returning the kind required.
5713 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5714   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5715   // Also, callers should have filtered out the invalid cases with
5716   // pointers.  Everything else should be possible.
5717 
5718   QualType SrcTy = Src.get()->getType();
5719   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5720     return CK_NoOp;
5721 
5722   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5723   case Type::STK_MemberPointer:
5724     llvm_unreachable("member pointer type in C");
5725 
5726   case Type::STK_CPointer:
5727   case Type::STK_BlockPointer:
5728   case Type::STK_ObjCObjectPointer:
5729     switch (DestTy->getScalarTypeKind()) {
5730     case Type::STK_CPointer: {
5731       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5732       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5733       if (SrcAS != DestAS)
5734         return CK_AddressSpaceConversion;
5735       return CK_BitCast;
5736     }
5737     case Type::STK_BlockPointer:
5738       return (SrcKind == Type::STK_BlockPointer
5739                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5740     case Type::STK_ObjCObjectPointer:
5741       if (SrcKind == Type::STK_ObjCObjectPointer)
5742         return CK_BitCast;
5743       if (SrcKind == Type::STK_CPointer)
5744         return CK_CPointerToObjCPointerCast;
5745       maybeExtendBlockObject(Src);
5746       return CK_BlockPointerToObjCPointerCast;
5747     case Type::STK_Bool:
5748       return CK_PointerToBoolean;
5749     case Type::STK_Integral:
5750       return CK_PointerToIntegral;
5751     case Type::STK_Floating:
5752     case Type::STK_FloatingComplex:
5753     case Type::STK_IntegralComplex:
5754     case Type::STK_MemberPointer:
5755       llvm_unreachable("illegal cast from pointer");
5756     }
5757     llvm_unreachable("Should have returned before this");
5758 
5759   case Type::STK_Bool: // casting from bool is like casting from an integer
5760   case Type::STK_Integral:
5761     switch (DestTy->getScalarTypeKind()) {
5762     case Type::STK_CPointer:
5763     case Type::STK_ObjCObjectPointer:
5764     case Type::STK_BlockPointer:
5765       if (Src.get()->isNullPointerConstant(Context,
5766                                            Expr::NPC_ValueDependentIsNull))
5767         return CK_NullToPointer;
5768       return CK_IntegralToPointer;
5769     case Type::STK_Bool:
5770       return CK_IntegralToBoolean;
5771     case Type::STK_Integral:
5772       return CK_IntegralCast;
5773     case Type::STK_Floating:
5774       return CK_IntegralToFloating;
5775     case Type::STK_IntegralComplex:
5776       Src = ImpCastExprToType(Src.get(),
5777                       DestTy->castAs<ComplexType>()->getElementType(),
5778                       CK_IntegralCast);
5779       return CK_IntegralRealToComplex;
5780     case Type::STK_FloatingComplex:
5781       Src = ImpCastExprToType(Src.get(),
5782                       DestTy->castAs<ComplexType>()->getElementType(),
5783                       CK_IntegralToFloating);
5784       return CK_FloatingRealToComplex;
5785     case Type::STK_MemberPointer:
5786       llvm_unreachable("member pointer type in C");
5787     }
5788     llvm_unreachable("Should have returned before this");
5789 
5790   case Type::STK_Floating:
5791     switch (DestTy->getScalarTypeKind()) {
5792     case Type::STK_Floating:
5793       return CK_FloatingCast;
5794     case Type::STK_Bool:
5795       return CK_FloatingToBoolean;
5796     case Type::STK_Integral:
5797       return CK_FloatingToIntegral;
5798     case Type::STK_FloatingComplex:
5799       Src = ImpCastExprToType(Src.get(),
5800                               DestTy->castAs<ComplexType>()->getElementType(),
5801                               CK_FloatingCast);
5802       return CK_FloatingRealToComplex;
5803     case Type::STK_IntegralComplex:
5804       Src = ImpCastExprToType(Src.get(),
5805                               DestTy->castAs<ComplexType>()->getElementType(),
5806                               CK_FloatingToIntegral);
5807       return CK_IntegralRealToComplex;
5808     case Type::STK_CPointer:
5809     case Type::STK_ObjCObjectPointer:
5810     case Type::STK_BlockPointer:
5811       llvm_unreachable("valid float->pointer cast?");
5812     case Type::STK_MemberPointer:
5813       llvm_unreachable("member pointer type in C");
5814     }
5815     llvm_unreachable("Should have returned before this");
5816 
5817   case Type::STK_FloatingComplex:
5818     switch (DestTy->getScalarTypeKind()) {
5819     case Type::STK_FloatingComplex:
5820       return CK_FloatingComplexCast;
5821     case Type::STK_IntegralComplex:
5822       return CK_FloatingComplexToIntegralComplex;
5823     case Type::STK_Floating: {
5824       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5825       if (Context.hasSameType(ET, DestTy))
5826         return CK_FloatingComplexToReal;
5827       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5828       return CK_FloatingCast;
5829     }
5830     case Type::STK_Bool:
5831       return CK_FloatingComplexToBoolean;
5832     case Type::STK_Integral:
5833       Src = ImpCastExprToType(Src.get(),
5834                               SrcTy->castAs<ComplexType>()->getElementType(),
5835                               CK_FloatingComplexToReal);
5836       return CK_FloatingToIntegral;
5837     case Type::STK_CPointer:
5838     case Type::STK_ObjCObjectPointer:
5839     case Type::STK_BlockPointer:
5840       llvm_unreachable("valid complex float->pointer cast?");
5841     case Type::STK_MemberPointer:
5842       llvm_unreachable("member pointer type in C");
5843     }
5844     llvm_unreachable("Should have returned before this");
5845 
5846   case Type::STK_IntegralComplex:
5847     switch (DestTy->getScalarTypeKind()) {
5848     case Type::STK_FloatingComplex:
5849       return CK_IntegralComplexToFloatingComplex;
5850     case Type::STK_IntegralComplex:
5851       return CK_IntegralComplexCast;
5852     case Type::STK_Integral: {
5853       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5854       if (Context.hasSameType(ET, DestTy))
5855         return CK_IntegralComplexToReal;
5856       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5857       return CK_IntegralCast;
5858     }
5859     case Type::STK_Bool:
5860       return CK_IntegralComplexToBoolean;
5861     case Type::STK_Floating:
5862       Src = ImpCastExprToType(Src.get(),
5863                               SrcTy->castAs<ComplexType>()->getElementType(),
5864                               CK_IntegralComplexToReal);
5865       return CK_IntegralToFloating;
5866     case Type::STK_CPointer:
5867     case Type::STK_ObjCObjectPointer:
5868     case Type::STK_BlockPointer:
5869       llvm_unreachable("valid complex int->pointer cast?");
5870     case Type::STK_MemberPointer:
5871       llvm_unreachable("member pointer type in C");
5872     }
5873     llvm_unreachable("Should have returned before this");
5874   }
5875 
5876   llvm_unreachable("Unhandled scalar cast");
5877 }
5878 
5879 static bool breakDownVectorType(QualType type, uint64_t &len,
5880                                 QualType &eltType) {
5881   // Vectors are simple.
5882   if (const VectorType *vecType = type->getAs<VectorType>()) {
5883     len = vecType->getNumElements();
5884     eltType = vecType->getElementType();
5885     assert(eltType->isScalarType());
5886     return true;
5887   }
5888 
5889   // We allow lax conversion to and from non-vector types, but only if
5890   // they're real types (i.e. non-complex, non-pointer scalar types).
5891   if (!type->isRealType()) return false;
5892 
5893   len = 1;
5894   eltType = type;
5895   return true;
5896 }
5897 
5898 /// Are the two types lax-compatible vector types?  That is, given
5899 /// that one of them is a vector, do they have equal storage sizes,
5900 /// where the storage size is the number of elements times the element
5901 /// size?
5902 ///
5903 /// This will also return false if either of the types is neither a
5904 /// vector nor a real type.
5905 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5906   assert(destTy->isVectorType() || srcTy->isVectorType());
5907 
5908   // Disallow lax conversions between scalars and ExtVectors (these
5909   // conversions are allowed for other vector types because common headers
5910   // depend on them).  Most scalar OP ExtVector cases are handled by the
5911   // splat path anyway, which does what we want (convert, not bitcast).
5912   // What this rules out for ExtVectors is crazy things like char4*float.
5913   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5914   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5915 
5916   uint64_t srcLen, destLen;
5917   QualType srcEltTy, destEltTy;
5918   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5919   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5920 
5921   // ASTContext::getTypeSize will return the size rounded up to a
5922   // power of 2, so instead of using that, we need to use the raw
5923   // element size multiplied by the element count.
5924   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5925   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5926 
5927   return (srcLen * srcEltSize == destLen * destEltSize);
5928 }
5929 
5930 /// Is this a legal conversion between two types, one of which is
5931 /// known to be a vector type?
5932 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5933   assert(destTy->isVectorType() || srcTy->isVectorType());
5934 
5935   if (!Context.getLangOpts().LaxVectorConversions)
5936     return false;
5937   return areLaxCompatibleVectorTypes(srcTy, destTy);
5938 }
5939 
5940 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5941                            CastKind &Kind) {
5942   assert(VectorTy->isVectorType() && "Not a vector type!");
5943 
5944   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5945     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5946       return Diag(R.getBegin(),
5947                   Ty->isVectorType() ?
5948                   diag::err_invalid_conversion_between_vectors :
5949                   diag::err_invalid_conversion_between_vector_and_integer)
5950         << VectorTy << Ty << R;
5951   } else
5952     return Diag(R.getBegin(),
5953                 diag::err_invalid_conversion_between_vector_and_scalar)
5954       << VectorTy << Ty << R;
5955 
5956   Kind = CK_BitCast;
5957   return false;
5958 }
5959 
5960 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5961   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5962 
5963   if (DestElemTy == SplattedExpr->getType())
5964     return SplattedExpr;
5965 
5966   assert(DestElemTy->isFloatingType() ||
5967          DestElemTy->isIntegralOrEnumerationType());
5968 
5969   CastKind CK;
5970   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5971     // OpenCL requires that we convert `true` boolean expressions to -1, but
5972     // only when splatting vectors.
5973     if (DestElemTy->isFloatingType()) {
5974       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5975       // in two steps: boolean to signed integral, then to floating.
5976       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5977                                                  CK_BooleanToSignedIntegral);
5978       SplattedExpr = CastExprRes.get();
5979       CK = CK_IntegralToFloating;
5980     } else {
5981       CK = CK_BooleanToSignedIntegral;
5982     }
5983   } else {
5984     ExprResult CastExprRes = SplattedExpr;
5985     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5986     if (CastExprRes.isInvalid())
5987       return ExprError();
5988     SplattedExpr = CastExprRes.get();
5989   }
5990   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5991 }
5992 
5993 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5994                                     Expr *CastExpr, CastKind &Kind) {
5995   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5996 
5997   QualType SrcTy = CastExpr->getType();
5998 
5999   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6000   // an ExtVectorType.
6001   // In OpenCL, casts between vectors of different types are not allowed.
6002   // (See OpenCL 6.2).
6003   if (SrcTy->isVectorType()) {
6004     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6005         || (getLangOpts().OpenCL &&
6006             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6007       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6008         << DestTy << SrcTy << R;
6009       return ExprError();
6010     }
6011     Kind = CK_BitCast;
6012     return CastExpr;
6013   }
6014 
6015   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6016   // conversion will take place first from scalar to elt type, and then
6017   // splat from elt type to vector.
6018   if (SrcTy->isPointerType())
6019     return Diag(R.getBegin(),
6020                 diag::err_invalid_conversion_between_vector_and_scalar)
6021       << DestTy << SrcTy << R;
6022 
6023   Kind = CK_VectorSplat;
6024   return prepareVectorSplat(DestTy, CastExpr);
6025 }
6026 
6027 ExprResult
6028 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6029                     Declarator &D, ParsedType &Ty,
6030                     SourceLocation RParenLoc, Expr *CastExpr) {
6031   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6032          "ActOnCastExpr(): missing type or expr");
6033 
6034   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6035   if (D.isInvalidType())
6036     return ExprError();
6037 
6038   if (getLangOpts().CPlusPlus) {
6039     // Check that there are no default arguments (C++ only).
6040     CheckExtraCXXDefaultArguments(D);
6041   } else {
6042     // Make sure any TypoExprs have been dealt with.
6043     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6044     if (!Res.isUsable())
6045       return ExprError();
6046     CastExpr = Res.get();
6047   }
6048 
6049   checkUnusedDeclAttributes(D);
6050 
6051   QualType castType = castTInfo->getType();
6052   Ty = CreateParsedType(castType, castTInfo);
6053 
6054   bool isVectorLiteral = false;
6055 
6056   // Check for an altivec or OpenCL literal,
6057   // i.e. all the elements are integer constants.
6058   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6059   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6060   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6061        && castType->isVectorType() && (PE || PLE)) {
6062     if (PLE && PLE->getNumExprs() == 0) {
6063       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6064       return ExprError();
6065     }
6066     if (PE || PLE->getNumExprs() == 1) {
6067       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6068       if (!E->getType()->isVectorType())
6069         isVectorLiteral = true;
6070     }
6071     else
6072       isVectorLiteral = true;
6073   }
6074 
6075   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6076   // then handle it as such.
6077   if (isVectorLiteral)
6078     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6079 
6080   // If the Expr being casted is a ParenListExpr, handle it specially.
6081   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6082   // sequence of BinOp comma operators.
6083   if (isa<ParenListExpr>(CastExpr)) {
6084     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6085     if (Result.isInvalid()) return ExprError();
6086     CastExpr = Result.get();
6087   }
6088 
6089   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6090       !getSourceManager().isInSystemMacro(LParenLoc))
6091     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6092 
6093   CheckTollFreeBridgeCast(castType, CastExpr);
6094 
6095   CheckObjCBridgeRelatedCast(castType, CastExpr);
6096 
6097   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6098 
6099   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6100 }
6101 
6102 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6103                                     SourceLocation RParenLoc, Expr *E,
6104                                     TypeSourceInfo *TInfo) {
6105   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6106          "Expected paren or paren list expression");
6107 
6108   Expr **exprs;
6109   unsigned numExprs;
6110   Expr *subExpr;
6111   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6112   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6113     LiteralLParenLoc = PE->getLParenLoc();
6114     LiteralRParenLoc = PE->getRParenLoc();
6115     exprs = PE->getExprs();
6116     numExprs = PE->getNumExprs();
6117   } else { // isa<ParenExpr> by assertion at function entrance
6118     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6119     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6120     subExpr = cast<ParenExpr>(E)->getSubExpr();
6121     exprs = &subExpr;
6122     numExprs = 1;
6123   }
6124 
6125   QualType Ty = TInfo->getType();
6126   assert(Ty->isVectorType() && "Expected vector type");
6127 
6128   SmallVector<Expr *, 8> initExprs;
6129   const VectorType *VTy = Ty->getAs<VectorType>();
6130   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6131 
6132   // '(...)' form of vector initialization in AltiVec: the number of
6133   // initializers must be one or must match the size of the vector.
6134   // If a single value is specified in the initializer then it will be
6135   // replicated to all the components of the vector
6136   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6137     // The number of initializers must be one or must match the size of the
6138     // vector. If a single value is specified in the initializer then it will
6139     // be replicated to all the components of the vector
6140     if (numExprs == 1) {
6141       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6142       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6143       if (Literal.isInvalid())
6144         return ExprError();
6145       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6146                                   PrepareScalarCast(Literal, ElemTy));
6147       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6148     }
6149     else if (numExprs < numElems) {
6150       Diag(E->getExprLoc(),
6151            diag::err_incorrect_number_of_vector_initializers);
6152       return ExprError();
6153     }
6154     else
6155       initExprs.append(exprs, exprs + numExprs);
6156   }
6157   else {
6158     // For OpenCL, when the number of initializers is a single value,
6159     // it will be replicated to all components of the vector.
6160     if (getLangOpts().OpenCL &&
6161         VTy->getVectorKind() == VectorType::GenericVector &&
6162         numExprs == 1) {
6163         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6164         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6165         if (Literal.isInvalid())
6166           return ExprError();
6167         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6168                                     PrepareScalarCast(Literal, ElemTy));
6169         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6170     }
6171 
6172     initExprs.append(exprs, exprs + numExprs);
6173   }
6174   // FIXME: This means that pretty-printing the final AST will produce curly
6175   // braces instead of the original commas.
6176   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6177                                                    initExprs, LiteralRParenLoc);
6178   initE->setType(Ty);
6179   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6180 }
6181 
6182 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6183 /// the ParenListExpr into a sequence of comma binary operators.
6184 ExprResult
6185 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6186   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6187   if (!E)
6188     return OrigExpr;
6189 
6190   ExprResult Result(E->getExpr(0));
6191 
6192   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6193     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6194                         E->getExpr(i));
6195 
6196   if (Result.isInvalid()) return ExprError();
6197 
6198   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6199 }
6200 
6201 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6202                                     SourceLocation R,
6203                                     MultiExprArg Val) {
6204   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6205   return expr;
6206 }
6207 
6208 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6209 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6210 /// emitted.
6211 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6212                                       SourceLocation QuestionLoc) {
6213   Expr *NullExpr = LHSExpr;
6214   Expr *NonPointerExpr = RHSExpr;
6215   Expr::NullPointerConstantKind NullKind =
6216       NullExpr->isNullPointerConstant(Context,
6217                                       Expr::NPC_ValueDependentIsNotNull);
6218 
6219   if (NullKind == Expr::NPCK_NotNull) {
6220     NullExpr = RHSExpr;
6221     NonPointerExpr = LHSExpr;
6222     NullKind =
6223         NullExpr->isNullPointerConstant(Context,
6224                                         Expr::NPC_ValueDependentIsNotNull);
6225   }
6226 
6227   if (NullKind == Expr::NPCK_NotNull)
6228     return false;
6229 
6230   if (NullKind == Expr::NPCK_ZeroExpression)
6231     return false;
6232 
6233   if (NullKind == Expr::NPCK_ZeroLiteral) {
6234     // In this case, check to make sure that we got here from a "NULL"
6235     // string in the source code.
6236     NullExpr = NullExpr->IgnoreParenImpCasts();
6237     SourceLocation loc = NullExpr->getExprLoc();
6238     if (!findMacroSpelling(loc, "NULL"))
6239       return false;
6240   }
6241 
6242   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6243   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6244       << NonPointerExpr->getType() << DiagType
6245       << NonPointerExpr->getSourceRange();
6246   return true;
6247 }
6248 
6249 /// \brief Return false if the condition expression is valid, true otherwise.
6250 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6251   QualType CondTy = Cond->getType();
6252 
6253   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6254   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6255     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6256       << CondTy << Cond->getSourceRange();
6257     return true;
6258   }
6259 
6260   // C99 6.5.15p2
6261   if (CondTy->isScalarType()) return false;
6262 
6263   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6264     << CondTy << Cond->getSourceRange();
6265   return true;
6266 }
6267 
6268 /// \brief Handle when one or both operands are void type.
6269 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6270                                          ExprResult &RHS) {
6271     Expr *LHSExpr = LHS.get();
6272     Expr *RHSExpr = RHS.get();
6273 
6274     if (!LHSExpr->getType()->isVoidType())
6275       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6276         << RHSExpr->getSourceRange();
6277     if (!RHSExpr->getType()->isVoidType())
6278       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6279         << LHSExpr->getSourceRange();
6280     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6281     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6282     return S.Context.VoidTy;
6283 }
6284 
6285 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6286 /// true otherwise.
6287 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6288                                         QualType PointerTy) {
6289   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6290       !NullExpr.get()->isNullPointerConstant(S.Context,
6291                                             Expr::NPC_ValueDependentIsNull))
6292     return true;
6293 
6294   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6295   return false;
6296 }
6297 
6298 /// \brief Checks compatibility between two pointers and return the resulting
6299 /// type.
6300 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6301                                                      ExprResult &RHS,
6302                                                      SourceLocation Loc) {
6303   QualType LHSTy = LHS.get()->getType();
6304   QualType RHSTy = RHS.get()->getType();
6305 
6306   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6307     // Two identical pointers types are always compatible.
6308     return LHSTy;
6309   }
6310 
6311   QualType lhptee, rhptee;
6312 
6313   // Get the pointee types.
6314   bool IsBlockPointer = false;
6315   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6316     lhptee = LHSBTy->getPointeeType();
6317     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6318     IsBlockPointer = true;
6319   } else {
6320     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6321     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6322   }
6323 
6324   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6325   // differently qualified versions of compatible types, the result type is
6326   // a pointer to an appropriately qualified version of the composite
6327   // type.
6328 
6329   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6330   // clause doesn't make sense for our extensions. E.g. address space 2 should
6331   // be incompatible with address space 3: they may live on different devices or
6332   // anything.
6333   Qualifiers lhQual = lhptee.getQualifiers();
6334   Qualifiers rhQual = rhptee.getQualifiers();
6335 
6336   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6337   lhQual.removeCVRQualifiers();
6338   rhQual.removeCVRQualifiers();
6339 
6340   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6341   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6342 
6343   // For OpenCL:
6344   // 1. If LHS and RHS types match exactly and:
6345   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6346   //  (b) AS overlap => generate addrspacecast
6347   //  (c) AS don't overlap => give an error
6348   // 2. if LHS and RHS types don't match:
6349   //  (a) AS match => use standard C rules, generate bitcast
6350   //  (b) AS overlap => generate addrspacecast instead of bitcast
6351   //  (c) AS don't overlap => give an error
6352 
6353   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6354   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6355 
6356   // OpenCL cases 1c, 2a, 2b, and 2c.
6357   if (CompositeTy.isNull()) {
6358     // In this situation, we assume void* type. No especially good
6359     // reason, but this is what gcc does, and we do have to pick
6360     // to get a consistent AST.
6361     QualType incompatTy;
6362     if (S.getLangOpts().OpenCL) {
6363       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6364       // spaces is disallowed.
6365       unsigned ResultAddrSpace;
6366       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6367         // Cases 2a and 2b.
6368         ResultAddrSpace = lhQual.getAddressSpace();
6369       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6370         // Cases 2a and 2b.
6371         ResultAddrSpace = rhQual.getAddressSpace();
6372       } else {
6373         // Cases 1c and 2c.
6374         S.Diag(Loc,
6375                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6376             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6377             << RHS.get()->getSourceRange();
6378         return QualType();
6379       }
6380 
6381       // Continue handling cases 2a and 2b.
6382       incompatTy = S.Context.getPointerType(
6383           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6384       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6385                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6386                                     ? CK_AddressSpaceConversion /* 2b */
6387                                     : CK_BitCast /* 2a */);
6388       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6389                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6390                                     ? CK_AddressSpaceConversion /* 2b */
6391                                     : CK_BitCast /* 2a */);
6392     } else {
6393       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6394           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6395           << RHS.get()->getSourceRange();
6396       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6397       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6398       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6399     }
6400     return incompatTy;
6401   }
6402 
6403   // The pointer types are compatible.
6404   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6405   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6406   if (IsBlockPointer)
6407     ResultTy = S.Context.getBlockPointerType(ResultTy);
6408   else {
6409     // Cases 1a and 1b for OpenCL.
6410     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6411     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6412                       ? CK_BitCast /* 1a */
6413                       : CK_AddressSpaceConversion /* 1b */;
6414     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6415                       ? CK_BitCast /* 1a */
6416                       : CK_AddressSpaceConversion /* 1b */;
6417     ResultTy = S.Context.getPointerType(ResultTy);
6418   }
6419 
6420   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6421   // if the target type does not change.
6422   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6423   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6424   return ResultTy;
6425 }
6426 
6427 /// \brief Return the resulting type when the operands are both block pointers.
6428 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6429                                                           ExprResult &LHS,
6430                                                           ExprResult &RHS,
6431                                                           SourceLocation Loc) {
6432   QualType LHSTy = LHS.get()->getType();
6433   QualType RHSTy = RHS.get()->getType();
6434 
6435   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6436     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6437       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6438       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6439       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6440       return destType;
6441     }
6442     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6443       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6444       << RHS.get()->getSourceRange();
6445     return QualType();
6446   }
6447 
6448   // We have 2 block pointer types.
6449   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6450 }
6451 
6452 /// \brief Return the resulting type when the operands are both pointers.
6453 static QualType
6454 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6455                                             ExprResult &RHS,
6456                                             SourceLocation Loc) {
6457   // get the pointer types
6458   QualType LHSTy = LHS.get()->getType();
6459   QualType RHSTy = RHS.get()->getType();
6460 
6461   // get the "pointed to" types
6462   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6463   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6464 
6465   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6466   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6467     // Figure out necessary qualifiers (C99 6.5.15p6)
6468     QualType destPointee
6469       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6470     QualType destType = S.Context.getPointerType(destPointee);
6471     // Add qualifiers if necessary.
6472     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6473     // Promote to void*.
6474     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6475     return destType;
6476   }
6477   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6478     QualType destPointee
6479       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6480     QualType destType = S.Context.getPointerType(destPointee);
6481     // Add qualifiers if necessary.
6482     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6483     // Promote to void*.
6484     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6485     return destType;
6486   }
6487 
6488   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6489 }
6490 
6491 /// \brief Return false if the first expression is not an integer and the second
6492 /// expression is not a pointer, true otherwise.
6493 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6494                                         Expr* PointerExpr, SourceLocation Loc,
6495                                         bool IsIntFirstExpr) {
6496   if (!PointerExpr->getType()->isPointerType() ||
6497       !Int.get()->getType()->isIntegerType())
6498     return false;
6499 
6500   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6501   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6502 
6503   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6504     << Expr1->getType() << Expr2->getType()
6505     << Expr1->getSourceRange() << Expr2->getSourceRange();
6506   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6507                             CK_IntegralToPointer);
6508   return true;
6509 }
6510 
6511 /// \brief Simple conversion between integer and floating point types.
6512 ///
6513 /// Used when handling the OpenCL conditional operator where the
6514 /// condition is a vector while the other operands are scalar.
6515 ///
6516 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6517 /// types are either integer or floating type. Between the two
6518 /// operands, the type with the higher rank is defined as the "result
6519 /// type". The other operand needs to be promoted to the same type. No
6520 /// other type promotion is allowed. We cannot use
6521 /// UsualArithmeticConversions() for this purpose, since it always
6522 /// promotes promotable types.
6523 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6524                                             ExprResult &RHS,
6525                                             SourceLocation QuestionLoc) {
6526   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6527   if (LHS.isInvalid())
6528     return QualType();
6529   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6530   if (RHS.isInvalid())
6531     return QualType();
6532 
6533   // For conversion purposes, we ignore any qualifiers.
6534   // For example, "const float" and "float" are equivalent.
6535   QualType LHSType =
6536     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6537   QualType RHSType =
6538     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6539 
6540   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6541     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6542       << LHSType << LHS.get()->getSourceRange();
6543     return QualType();
6544   }
6545 
6546   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6547     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6548       << RHSType << RHS.get()->getSourceRange();
6549     return QualType();
6550   }
6551 
6552   // If both types are identical, no conversion is needed.
6553   if (LHSType == RHSType)
6554     return LHSType;
6555 
6556   // Now handle "real" floating types (i.e. float, double, long double).
6557   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6558     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6559                                  /*IsCompAssign = */ false);
6560 
6561   // Finally, we have two differing integer types.
6562   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6563   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6564 }
6565 
6566 /// \brief Convert scalar operands to a vector that matches the
6567 ///        condition in length.
6568 ///
6569 /// Used when handling the OpenCL conditional operator where the
6570 /// condition is a vector while the other operands are scalar.
6571 ///
6572 /// We first compute the "result type" for the scalar operands
6573 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6574 /// into a vector of that type where the length matches the condition
6575 /// vector type. s6.11.6 requires that the element types of the result
6576 /// and the condition must have the same number of bits.
6577 static QualType
6578 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6579                               QualType CondTy, SourceLocation QuestionLoc) {
6580   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6581   if (ResTy.isNull()) return QualType();
6582 
6583   const VectorType *CV = CondTy->getAs<VectorType>();
6584   assert(CV);
6585 
6586   // Determine the vector result type
6587   unsigned NumElements = CV->getNumElements();
6588   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6589 
6590   // Ensure that all types have the same number of bits
6591   if (S.Context.getTypeSize(CV->getElementType())
6592       != S.Context.getTypeSize(ResTy)) {
6593     // Since VectorTy is created internally, it does not pretty print
6594     // with an OpenCL name. Instead, we just print a description.
6595     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6596     SmallString<64> Str;
6597     llvm::raw_svector_ostream OS(Str);
6598     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6599     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6600       << CondTy << OS.str();
6601     return QualType();
6602   }
6603 
6604   // Convert operands to the vector result type
6605   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6606   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6607 
6608   return VectorTy;
6609 }
6610 
6611 /// \brief Return false if this is a valid OpenCL condition vector
6612 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6613                                        SourceLocation QuestionLoc) {
6614   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6615   // integral type.
6616   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6617   assert(CondTy);
6618   QualType EleTy = CondTy->getElementType();
6619   if (EleTy->isIntegerType()) return false;
6620 
6621   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6622     << Cond->getType() << Cond->getSourceRange();
6623   return true;
6624 }
6625 
6626 /// \brief Return false if the vector condition type and the vector
6627 ///        result type are compatible.
6628 ///
6629 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6630 /// number of elements, and their element types have the same number
6631 /// of bits.
6632 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6633                               SourceLocation QuestionLoc) {
6634   const VectorType *CV = CondTy->getAs<VectorType>();
6635   const VectorType *RV = VecResTy->getAs<VectorType>();
6636   assert(CV && RV);
6637 
6638   if (CV->getNumElements() != RV->getNumElements()) {
6639     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6640       << CondTy << VecResTy;
6641     return true;
6642   }
6643 
6644   QualType CVE = CV->getElementType();
6645   QualType RVE = RV->getElementType();
6646 
6647   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6648     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6649       << CondTy << VecResTy;
6650     return true;
6651   }
6652 
6653   return false;
6654 }
6655 
6656 /// \brief Return the resulting type for the conditional operator in
6657 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6658 ///        s6.3.i) when the condition is a vector type.
6659 static QualType
6660 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6661                              ExprResult &LHS, ExprResult &RHS,
6662                              SourceLocation QuestionLoc) {
6663   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6664   if (Cond.isInvalid())
6665     return QualType();
6666   QualType CondTy = Cond.get()->getType();
6667 
6668   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6669     return QualType();
6670 
6671   // If either operand is a vector then find the vector type of the
6672   // result as specified in OpenCL v1.1 s6.3.i.
6673   if (LHS.get()->getType()->isVectorType() ||
6674       RHS.get()->getType()->isVectorType()) {
6675     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6676                                               /*isCompAssign*/false,
6677                                               /*AllowBothBool*/true,
6678                                               /*AllowBoolConversions*/false);
6679     if (VecResTy.isNull()) return QualType();
6680     // The result type must match the condition type as specified in
6681     // OpenCL v1.1 s6.11.6.
6682     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6683       return QualType();
6684     return VecResTy;
6685   }
6686 
6687   // Both operands are scalar.
6688   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6689 }
6690 
6691 /// \brief Return true if the Expr is block type
6692 static bool checkBlockType(Sema &S, const Expr *E) {
6693   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6694     QualType Ty = CE->getCallee()->getType();
6695     if (Ty->isBlockPointerType()) {
6696       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6697       return true;
6698     }
6699   }
6700   return false;
6701 }
6702 
6703 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6704 /// In that case, LHS = cond.
6705 /// C99 6.5.15
6706 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6707                                         ExprResult &RHS, ExprValueKind &VK,
6708                                         ExprObjectKind &OK,
6709                                         SourceLocation QuestionLoc) {
6710 
6711   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6712   if (!LHSResult.isUsable()) return QualType();
6713   LHS = LHSResult;
6714 
6715   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6716   if (!RHSResult.isUsable()) return QualType();
6717   RHS = RHSResult;
6718 
6719   // C++ is sufficiently different to merit its own checker.
6720   if (getLangOpts().CPlusPlus)
6721     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6722 
6723   VK = VK_RValue;
6724   OK = OK_Ordinary;
6725 
6726   // The OpenCL operator with a vector condition is sufficiently
6727   // different to merit its own checker.
6728   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6729     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6730 
6731   // First, check the condition.
6732   Cond = UsualUnaryConversions(Cond.get());
6733   if (Cond.isInvalid())
6734     return QualType();
6735   if (checkCondition(*this, Cond.get(), QuestionLoc))
6736     return QualType();
6737 
6738   // Now check the two expressions.
6739   if (LHS.get()->getType()->isVectorType() ||
6740       RHS.get()->getType()->isVectorType())
6741     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6742                                /*AllowBothBool*/true,
6743                                /*AllowBoolConversions*/false);
6744 
6745   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6746   if (LHS.isInvalid() || RHS.isInvalid())
6747     return QualType();
6748 
6749   QualType LHSTy = LHS.get()->getType();
6750   QualType RHSTy = RHS.get()->getType();
6751 
6752   // Diagnose attempts to convert between __float128 and long double where
6753   // such conversions currently can't be handled.
6754   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6755     Diag(QuestionLoc,
6756          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6757       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6758     return QualType();
6759   }
6760 
6761   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6762   // selection operator (?:).
6763   if (getLangOpts().OpenCL &&
6764       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6765     return QualType();
6766   }
6767 
6768   // If both operands have arithmetic type, do the usual arithmetic conversions
6769   // to find a common type: C99 6.5.15p3,5.
6770   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6771     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6772     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6773 
6774     return ResTy;
6775   }
6776 
6777   // If both operands are the same structure or union type, the result is that
6778   // type.
6779   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6780     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6781       if (LHSRT->getDecl() == RHSRT->getDecl())
6782         // "If both the operands have structure or union type, the result has
6783         // that type."  This implies that CV qualifiers are dropped.
6784         return LHSTy.getUnqualifiedType();
6785     // FIXME: Type of conditional expression must be complete in C mode.
6786   }
6787 
6788   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6789   // The following || allows only one side to be void (a GCC-ism).
6790   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6791     return checkConditionalVoidType(*this, LHS, RHS);
6792   }
6793 
6794   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6795   // the type of the other operand."
6796   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6797   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6798 
6799   // All objective-c pointer type analysis is done here.
6800   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6801                                                         QuestionLoc);
6802   if (LHS.isInvalid() || RHS.isInvalid())
6803     return QualType();
6804   if (!compositeType.isNull())
6805     return compositeType;
6806 
6807 
6808   // Handle block pointer types.
6809   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6810     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6811                                                      QuestionLoc);
6812 
6813   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6814   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6815     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6816                                                        QuestionLoc);
6817 
6818   // GCC compatibility: soften pointer/integer mismatch.  Note that
6819   // null pointers have been filtered out by this point.
6820   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6821       /*isIntFirstExpr=*/true))
6822     return RHSTy;
6823   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6824       /*isIntFirstExpr=*/false))
6825     return LHSTy;
6826 
6827   // Emit a better diagnostic if one of the expressions is a null pointer
6828   // constant and the other is not a pointer type. In this case, the user most
6829   // likely forgot to take the address of the other expression.
6830   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6831     return QualType();
6832 
6833   // Otherwise, the operands are not compatible.
6834   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6835     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6836     << RHS.get()->getSourceRange();
6837   return QualType();
6838 }
6839 
6840 /// FindCompositeObjCPointerType - Helper method to find composite type of
6841 /// two objective-c pointer types of the two input expressions.
6842 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6843                                             SourceLocation QuestionLoc) {
6844   QualType LHSTy = LHS.get()->getType();
6845   QualType RHSTy = RHS.get()->getType();
6846 
6847   // Handle things like Class and struct objc_class*.  Here we case the result
6848   // to the pseudo-builtin, because that will be implicitly cast back to the
6849   // redefinition type if an attempt is made to access its fields.
6850   if (LHSTy->isObjCClassType() &&
6851       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6852     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6853     return LHSTy;
6854   }
6855   if (RHSTy->isObjCClassType() &&
6856       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6857     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6858     return RHSTy;
6859   }
6860   // And the same for struct objc_object* / id
6861   if (LHSTy->isObjCIdType() &&
6862       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6863     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6864     return LHSTy;
6865   }
6866   if (RHSTy->isObjCIdType() &&
6867       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6868     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6869     return RHSTy;
6870   }
6871   // And the same for struct objc_selector* / SEL
6872   if (Context.isObjCSelType(LHSTy) &&
6873       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6874     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6875     return LHSTy;
6876   }
6877   if (Context.isObjCSelType(RHSTy) &&
6878       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6879     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6880     return RHSTy;
6881   }
6882   // Check constraints for Objective-C object pointers types.
6883   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6884 
6885     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6886       // Two identical object pointer types are always compatible.
6887       return LHSTy;
6888     }
6889     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6890     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6891     QualType compositeType = LHSTy;
6892 
6893     // If both operands are interfaces and either operand can be
6894     // assigned to the other, use that type as the composite
6895     // type. This allows
6896     //   xxx ? (A*) a : (B*) b
6897     // where B is a subclass of A.
6898     //
6899     // Additionally, as for assignment, if either type is 'id'
6900     // allow silent coercion. Finally, if the types are
6901     // incompatible then make sure to use 'id' as the composite
6902     // type so the result is acceptable for sending messages to.
6903 
6904     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6905     // It could return the composite type.
6906     if (!(compositeType =
6907           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6908       // Nothing more to do.
6909     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6910       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6911     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6912       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6913     } else if ((LHSTy->isObjCQualifiedIdType() ||
6914                 RHSTy->isObjCQualifiedIdType()) &&
6915                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6916       // Need to handle "id<xx>" explicitly.
6917       // GCC allows qualified id and any Objective-C type to devolve to
6918       // id. Currently localizing to here until clear this should be
6919       // part of ObjCQualifiedIdTypesAreCompatible.
6920       compositeType = Context.getObjCIdType();
6921     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6922       compositeType = Context.getObjCIdType();
6923     } else {
6924       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6925       << LHSTy << RHSTy
6926       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6927       QualType incompatTy = Context.getObjCIdType();
6928       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6929       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6930       return incompatTy;
6931     }
6932     // The object pointer types are compatible.
6933     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6934     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6935     return compositeType;
6936   }
6937   // Check Objective-C object pointer types and 'void *'
6938   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6939     if (getLangOpts().ObjCAutoRefCount) {
6940       // ARC forbids the implicit conversion of object pointers to 'void *',
6941       // so these types are not compatible.
6942       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6943           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6944       LHS = RHS = true;
6945       return QualType();
6946     }
6947     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6948     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6949     QualType destPointee
6950     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6951     QualType destType = Context.getPointerType(destPointee);
6952     // Add qualifiers if necessary.
6953     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6954     // Promote to void*.
6955     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6956     return destType;
6957   }
6958   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6959     if (getLangOpts().ObjCAutoRefCount) {
6960       // ARC forbids the implicit conversion of object pointers to 'void *',
6961       // so these types are not compatible.
6962       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6963           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6964       LHS = RHS = true;
6965       return QualType();
6966     }
6967     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6968     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6969     QualType destPointee
6970     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6971     QualType destType = Context.getPointerType(destPointee);
6972     // Add qualifiers if necessary.
6973     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6974     // Promote to void*.
6975     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6976     return destType;
6977   }
6978   return QualType();
6979 }
6980 
6981 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6982 /// ParenRange in parentheses.
6983 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6984                                const PartialDiagnostic &Note,
6985                                SourceRange ParenRange) {
6986   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6987   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6988       EndLoc.isValid()) {
6989     Self.Diag(Loc, Note)
6990       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6991       << FixItHint::CreateInsertion(EndLoc, ")");
6992   } else {
6993     // We can't display the parentheses, so just show the bare note.
6994     Self.Diag(Loc, Note) << ParenRange;
6995   }
6996 }
6997 
6998 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6999   return BinaryOperator::isAdditiveOp(Opc) ||
7000          BinaryOperator::isMultiplicativeOp(Opc) ||
7001          BinaryOperator::isShiftOp(Opc);
7002 }
7003 
7004 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7005 /// expression, either using a built-in or overloaded operator,
7006 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7007 /// expression.
7008 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7009                                    Expr **RHSExprs) {
7010   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7011   E = E->IgnoreImpCasts();
7012   E = E->IgnoreConversionOperator();
7013   E = E->IgnoreImpCasts();
7014 
7015   // Built-in binary operator.
7016   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7017     if (IsArithmeticOp(OP->getOpcode())) {
7018       *Opcode = OP->getOpcode();
7019       *RHSExprs = OP->getRHS();
7020       return true;
7021     }
7022   }
7023 
7024   // Overloaded operator.
7025   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7026     if (Call->getNumArgs() != 2)
7027       return false;
7028 
7029     // Make sure this is really a binary operator that is safe to pass into
7030     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7031     OverloadedOperatorKind OO = Call->getOperator();
7032     if (OO < OO_Plus || OO > OO_Arrow ||
7033         OO == OO_PlusPlus || OO == OO_MinusMinus)
7034       return false;
7035 
7036     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7037     if (IsArithmeticOp(OpKind)) {
7038       *Opcode = OpKind;
7039       *RHSExprs = Call->getArg(1);
7040       return true;
7041     }
7042   }
7043 
7044   return false;
7045 }
7046 
7047 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7048 /// or is a logical expression such as (x==y) which has int type, but is
7049 /// commonly interpreted as boolean.
7050 static bool ExprLooksBoolean(Expr *E) {
7051   E = E->IgnoreParenImpCasts();
7052 
7053   if (E->getType()->isBooleanType())
7054     return true;
7055   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7056     return OP->isComparisonOp() || OP->isLogicalOp();
7057   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7058     return OP->getOpcode() == UO_LNot;
7059   if (E->getType()->isPointerType())
7060     return true;
7061 
7062   return false;
7063 }
7064 
7065 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7066 /// and binary operator are mixed in a way that suggests the programmer assumed
7067 /// the conditional operator has higher precedence, for example:
7068 /// "int x = a + someBinaryCondition ? 1 : 2".
7069 static void DiagnoseConditionalPrecedence(Sema &Self,
7070                                           SourceLocation OpLoc,
7071                                           Expr *Condition,
7072                                           Expr *LHSExpr,
7073                                           Expr *RHSExpr) {
7074   BinaryOperatorKind CondOpcode;
7075   Expr *CondRHS;
7076 
7077   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7078     return;
7079   if (!ExprLooksBoolean(CondRHS))
7080     return;
7081 
7082   // The condition is an arithmetic binary expression, with a right-
7083   // hand side that looks boolean, so warn.
7084 
7085   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7086       << Condition->getSourceRange()
7087       << BinaryOperator::getOpcodeStr(CondOpcode);
7088 
7089   SuggestParentheses(Self, OpLoc,
7090     Self.PDiag(diag::note_precedence_silence)
7091       << BinaryOperator::getOpcodeStr(CondOpcode),
7092     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7093 
7094   SuggestParentheses(Self, OpLoc,
7095     Self.PDiag(diag::note_precedence_conditional_first),
7096     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7097 }
7098 
7099 /// Compute the nullability of a conditional expression.
7100 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7101                                               QualType LHSTy, QualType RHSTy,
7102                                               ASTContext &Ctx) {
7103   if (!ResTy->isAnyPointerType())
7104     return ResTy;
7105 
7106   auto GetNullability = [&Ctx](QualType Ty) {
7107     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7108     if (Kind)
7109       return *Kind;
7110     return NullabilityKind::Unspecified;
7111   };
7112 
7113   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7114   NullabilityKind MergedKind;
7115 
7116   // Compute nullability of a binary conditional expression.
7117   if (IsBin) {
7118     if (LHSKind == NullabilityKind::NonNull)
7119       MergedKind = NullabilityKind::NonNull;
7120     else
7121       MergedKind = RHSKind;
7122   // Compute nullability of a normal conditional expression.
7123   } else {
7124     if (LHSKind == NullabilityKind::Nullable ||
7125         RHSKind == NullabilityKind::Nullable)
7126       MergedKind = NullabilityKind::Nullable;
7127     else if (LHSKind == NullabilityKind::NonNull)
7128       MergedKind = RHSKind;
7129     else if (RHSKind == NullabilityKind::NonNull)
7130       MergedKind = LHSKind;
7131     else
7132       MergedKind = NullabilityKind::Unspecified;
7133   }
7134 
7135   // Return if ResTy already has the correct nullability.
7136   if (GetNullability(ResTy) == MergedKind)
7137     return ResTy;
7138 
7139   // Strip all nullability from ResTy.
7140   while (ResTy->getNullability(Ctx))
7141     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7142 
7143   // Create a new AttributedType with the new nullability kind.
7144   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7145   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7146 }
7147 
7148 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7149 /// in the case of a the GNU conditional expr extension.
7150 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7151                                     SourceLocation ColonLoc,
7152                                     Expr *CondExpr, Expr *LHSExpr,
7153                                     Expr *RHSExpr) {
7154   if (!getLangOpts().CPlusPlus) {
7155     // C cannot handle TypoExpr nodes in the condition because it
7156     // doesn't handle dependent types properly, so make sure any TypoExprs have
7157     // been dealt with before checking the operands.
7158     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7159     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7160     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7161 
7162     if (!CondResult.isUsable())
7163       return ExprError();
7164 
7165     if (LHSExpr) {
7166       if (!LHSResult.isUsable())
7167         return ExprError();
7168     }
7169 
7170     if (!RHSResult.isUsable())
7171       return ExprError();
7172 
7173     CondExpr = CondResult.get();
7174     LHSExpr = LHSResult.get();
7175     RHSExpr = RHSResult.get();
7176   }
7177 
7178   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7179   // was the condition.
7180   OpaqueValueExpr *opaqueValue = nullptr;
7181   Expr *commonExpr = nullptr;
7182   if (!LHSExpr) {
7183     commonExpr = CondExpr;
7184     // Lower out placeholder types first.  This is important so that we don't
7185     // try to capture a placeholder. This happens in few cases in C++; such
7186     // as Objective-C++'s dictionary subscripting syntax.
7187     if (commonExpr->hasPlaceholderType()) {
7188       ExprResult result = CheckPlaceholderExpr(commonExpr);
7189       if (!result.isUsable()) return ExprError();
7190       commonExpr = result.get();
7191     }
7192     // We usually want to apply unary conversions *before* saving, except
7193     // in the special case of a C++ l-value conditional.
7194     if (!(getLangOpts().CPlusPlus
7195           && !commonExpr->isTypeDependent()
7196           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7197           && commonExpr->isGLValue()
7198           && commonExpr->isOrdinaryOrBitFieldObject()
7199           && RHSExpr->isOrdinaryOrBitFieldObject()
7200           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7201       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7202       if (commonRes.isInvalid())
7203         return ExprError();
7204       commonExpr = commonRes.get();
7205     }
7206 
7207     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7208                                                 commonExpr->getType(),
7209                                                 commonExpr->getValueKind(),
7210                                                 commonExpr->getObjectKind(),
7211                                                 commonExpr);
7212     LHSExpr = CondExpr = opaqueValue;
7213   }
7214 
7215   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7216   ExprValueKind VK = VK_RValue;
7217   ExprObjectKind OK = OK_Ordinary;
7218   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7219   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7220                                              VK, OK, QuestionLoc);
7221   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7222       RHS.isInvalid())
7223     return ExprError();
7224 
7225   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7226                                 RHS.get());
7227 
7228   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7229 
7230   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7231                                          Context);
7232 
7233   if (!commonExpr)
7234     return new (Context)
7235         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7236                             RHS.get(), result, VK, OK);
7237 
7238   return new (Context) BinaryConditionalOperator(
7239       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7240       ColonLoc, result, VK, OK);
7241 }
7242 
7243 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7244 // being closely modeled after the C99 spec:-). The odd characteristic of this
7245 // routine is it effectively iqnores the qualifiers on the top level pointee.
7246 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7247 // FIXME: add a couple examples in this comment.
7248 static Sema::AssignConvertType
7249 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7250   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7251   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7252 
7253   // get the "pointed to" type (ignoring qualifiers at the top level)
7254   const Type *lhptee, *rhptee;
7255   Qualifiers lhq, rhq;
7256   std::tie(lhptee, lhq) =
7257       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7258   std::tie(rhptee, rhq) =
7259       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7260 
7261   Sema::AssignConvertType ConvTy = Sema::Compatible;
7262 
7263   // C99 6.5.16.1p1: This following citation is common to constraints
7264   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7265   // qualifiers of the type *pointed to* by the right;
7266 
7267   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7268   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7269       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7270     // Ignore lifetime for further calculation.
7271     lhq.removeObjCLifetime();
7272     rhq.removeObjCLifetime();
7273   }
7274 
7275   if (!lhq.compatiblyIncludes(rhq)) {
7276     // Treat address-space mismatches as fatal.  TODO: address subspaces
7277     if (!lhq.isAddressSpaceSupersetOf(rhq))
7278       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7279 
7280     // It's okay to add or remove GC or lifetime qualifiers when converting to
7281     // and from void*.
7282     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7283                         .compatiblyIncludes(
7284                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7285              && (lhptee->isVoidType() || rhptee->isVoidType()))
7286       ; // keep old
7287 
7288     // Treat lifetime mismatches as fatal.
7289     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7290       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7291 
7292     // For GCC/MS compatibility, other qualifier mismatches are treated
7293     // as still compatible in C.
7294     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7295   }
7296 
7297   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7298   // incomplete type and the other is a pointer to a qualified or unqualified
7299   // version of void...
7300   if (lhptee->isVoidType()) {
7301     if (rhptee->isIncompleteOrObjectType())
7302       return ConvTy;
7303 
7304     // As an extension, we allow cast to/from void* to function pointer.
7305     assert(rhptee->isFunctionType());
7306     return Sema::FunctionVoidPointer;
7307   }
7308 
7309   if (rhptee->isVoidType()) {
7310     if (lhptee->isIncompleteOrObjectType())
7311       return ConvTy;
7312 
7313     // As an extension, we allow cast to/from void* to function pointer.
7314     assert(lhptee->isFunctionType());
7315     return Sema::FunctionVoidPointer;
7316   }
7317 
7318   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7319   // unqualified versions of compatible types, ...
7320   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7321   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7322     // Check if the pointee types are compatible ignoring the sign.
7323     // We explicitly check for char so that we catch "char" vs
7324     // "unsigned char" on systems where "char" is unsigned.
7325     if (lhptee->isCharType())
7326       ltrans = S.Context.UnsignedCharTy;
7327     else if (lhptee->hasSignedIntegerRepresentation())
7328       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7329 
7330     if (rhptee->isCharType())
7331       rtrans = S.Context.UnsignedCharTy;
7332     else if (rhptee->hasSignedIntegerRepresentation())
7333       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7334 
7335     if (ltrans == rtrans) {
7336       // Types are compatible ignoring the sign. Qualifier incompatibility
7337       // takes priority over sign incompatibility because the sign
7338       // warning can be disabled.
7339       if (ConvTy != Sema::Compatible)
7340         return ConvTy;
7341 
7342       return Sema::IncompatiblePointerSign;
7343     }
7344 
7345     // If we are a multi-level pointer, it's possible that our issue is simply
7346     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7347     // the eventual target type is the same and the pointers have the same
7348     // level of indirection, this must be the issue.
7349     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7350       do {
7351         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7352         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7353       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7354 
7355       if (lhptee == rhptee)
7356         return Sema::IncompatibleNestedPointerQualifiers;
7357     }
7358 
7359     // General pointer incompatibility takes priority over qualifiers.
7360     return Sema::IncompatiblePointer;
7361   }
7362   if (!S.getLangOpts().CPlusPlus &&
7363       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7364     return Sema::IncompatiblePointer;
7365   return ConvTy;
7366 }
7367 
7368 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7369 /// block pointer types are compatible or whether a block and normal pointer
7370 /// are compatible. It is more restrict than comparing two function pointer
7371 // types.
7372 static Sema::AssignConvertType
7373 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7374                                     QualType RHSType) {
7375   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7376   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7377 
7378   QualType lhptee, rhptee;
7379 
7380   // get the "pointed to" type (ignoring qualifiers at the top level)
7381   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7382   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7383 
7384   // In C++, the types have to match exactly.
7385   if (S.getLangOpts().CPlusPlus)
7386     return Sema::IncompatibleBlockPointer;
7387 
7388   Sema::AssignConvertType ConvTy = Sema::Compatible;
7389 
7390   // For blocks we enforce that qualifiers are identical.
7391   Qualifiers LQuals = lhptee.getLocalQualifiers();
7392   Qualifiers RQuals = rhptee.getLocalQualifiers();
7393   if (S.getLangOpts().OpenCL) {
7394     LQuals.removeAddressSpace();
7395     RQuals.removeAddressSpace();
7396   }
7397   if (LQuals != RQuals)
7398     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7399 
7400   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7401     return Sema::IncompatibleBlockPointer;
7402 
7403   return ConvTy;
7404 }
7405 
7406 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7407 /// for assignment compatibility.
7408 static Sema::AssignConvertType
7409 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7410                                    QualType RHSType) {
7411   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7412   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7413 
7414   if (LHSType->isObjCBuiltinType()) {
7415     // Class is not compatible with ObjC object pointers.
7416     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7417         !RHSType->isObjCQualifiedClassType())
7418       return Sema::IncompatiblePointer;
7419     return Sema::Compatible;
7420   }
7421   if (RHSType->isObjCBuiltinType()) {
7422     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7423         !LHSType->isObjCQualifiedClassType())
7424       return Sema::IncompatiblePointer;
7425     return Sema::Compatible;
7426   }
7427   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7428   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7429 
7430   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7431       // make an exception for id<P>
7432       !LHSType->isObjCQualifiedIdType())
7433     return Sema::CompatiblePointerDiscardsQualifiers;
7434 
7435   if (S.Context.typesAreCompatible(LHSType, RHSType))
7436     return Sema::Compatible;
7437   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7438     return Sema::IncompatibleObjCQualifiedId;
7439   return Sema::IncompatiblePointer;
7440 }
7441 
7442 Sema::AssignConvertType
7443 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7444                                  QualType LHSType, QualType RHSType) {
7445   // Fake up an opaque expression.  We don't actually care about what
7446   // cast operations are required, so if CheckAssignmentConstraints
7447   // adds casts to this they'll be wasted, but fortunately that doesn't
7448   // usually happen on valid code.
7449   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7450   ExprResult RHSPtr = &RHSExpr;
7451   CastKind K = CK_Invalid;
7452 
7453   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7454 }
7455 
7456 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7457 /// has code to accommodate several GCC extensions when type checking
7458 /// pointers. Here are some objectionable examples that GCC considers warnings:
7459 ///
7460 ///  int a, *pint;
7461 ///  short *pshort;
7462 ///  struct foo *pfoo;
7463 ///
7464 ///  pint = pshort; // warning: assignment from incompatible pointer type
7465 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7466 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7467 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7468 ///
7469 /// As a result, the code for dealing with pointers is more complex than the
7470 /// C99 spec dictates.
7471 ///
7472 /// Sets 'Kind' for any result kind except Incompatible.
7473 Sema::AssignConvertType
7474 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7475                                  CastKind &Kind, bool ConvertRHS) {
7476   QualType RHSType = RHS.get()->getType();
7477   QualType OrigLHSType = LHSType;
7478 
7479   // Get canonical types.  We're not formatting these types, just comparing
7480   // them.
7481   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7482   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7483 
7484   // Common case: no conversion required.
7485   if (LHSType == RHSType) {
7486     Kind = CK_NoOp;
7487     return Compatible;
7488   }
7489 
7490   // If we have an atomic type, try a non-atomic assignment, then just add an
7491   // atomic qualification step.
7492   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7493     Sema::AssignConvertType result =
7494       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7495     if (result != Compatible)
7496       return result;
7497     if (Kind != CK_NoOp && ConvertRHS)
7498       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7499     Kind = CK_NonAtomicToAtomic;
7500     return Compatible;
7501   }
7502 
7503   // If the left-hand side is a reference type, then we are in a
7504   // (rare!) case where we've allowed the use of references in C,
7505   // e.g., as a parameter type in a built-in function. In this case,
7506   // just make sure that the type referenced is compatible with the
7507   // right-hand side type. The caller is responsible for adjusting
7508   // LHSType so that the resulting expression does not have reference
7509   // type.
7510   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7511     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7512       Kind = CK_LValueBitCast;
7513       return Compatible;
7514     }
7515     return Incompatible;
7516   }
7517 
7518   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7519   // to the same ExtVector type.
7520   if (LHSType->isExtVectorType()) {
7521     if (RHSType->isExtVectorType())
7522       return Incompatible;
7523     if (RHSType->isArithmeticType()) {
7524       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7525       if (ConvertRHS)
7526         RHS = prepareVectorSplat(LHSType, RHS.get());
7527       Kind = CK_VectorSplat;
7528       return Compatible;
7529     }
7530   }
7531 
7532   // Conversions to or from vector type.
7533   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7534     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7535       // Allow assignments of an AltiVec vector type to an equivalent GCC
7536       // vector type and vice versa
7537       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7538         Kind = CK_BitCast;
7539         return Compatible;
7540       }
7541 
7542       // If we are allowing lax vector conversions, and LHS and RHS are both
7543       // vectors, the total size only needs to be the same. This is a bitcast;
7544       // no bits are changed but the result type is different.
7545       if (isLaxVectorConversion(RHSType, LHSType)) {
7546         Kind = CK_BitCast;
7547         return IncompatibleVectors;
7548       }
7549     }
7550 
7551     // When the RHS comes from another lax conversion (e.g. binops between
7552     // scalars and vectors) the result is canonicalized as a vector. When the
7553     // LHS is also a vector, the lax is allowed by the condition above. Handle
7554     // the case where LHS is a scalar.
7555     if (LHSType->isScalarType()) {
7556       const VectorType *VecType = RHSType->getAs<VectorType>();
7557       if (VecType && VecType->getNumElements() == 1 &&
7558           isLaxVectorConversion(RHSType, LHSType)) {
7559         ExprResult *VecExpr = &RHS;
7560         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7561         Kind = CK_BitCast;
7562         return Compatible;
7563       }
7564     }
7565 
7566     return Incompatible;
7567   }
7568 
7569   // Diagnose attempts to convert between __float128 and long double where
7570   // such conversions currently can't be handled.
7571   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7572     return Incompatible;
7573 
7574   // Arithmetic conversions.
7575   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7576       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7577     if (ConvertRHS)
7578       Kind = PrepareScalarCast(RHS, LHSType);
7579     return Compatible;
7580   }
7581 
7582   // Conversions to normal pointers.
7583   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7584     // U* -> T*
7585     if (isa<PointerType>(RHSType)) {
7586       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7587       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7588       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7589       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7590     }
7591 
7592     // int -> T*
7593     if (RHSType->isIntegerType()) {
7594       Kind = CK_IntegralToPointer; // FIXME: null?
7595       return IntToPointer;
7596     }
7597 
7598     // C pointers are not compatible with ObjC object pointers,
7599     // with two exceptions:
7600     if (isa<ObjCObjectPointerType>(RHSType)) {
7601       //  - conversions to void*
7602       if (LHSPointer->getPointeeType()->isVoidType()) {
7603         Kind = CK_BitCast;
7604         return Compatible;
7605       }
7606 
7607       //  - conversions from 'Class' to the redefinition type
7608       if (RHSType->isObjCClassType() &&
7609           Context.hasSameType(LHSType,
7610                               Context.getObjCClassRedefinitionType())) {
7611         Kind = CK_BitCast;
7612         return Compatible;
7613       }
7614 
7615       Kind = CK_BitCast;
7616       return IncompatiblePointer;
7617     }
7618 
7619     // U^ -> void*
7620     if (RHSType->getAs<BlockPointerType>()) {
7621       if (LHSPointer->getPointeeType()->isVoidType()) {
7622         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7623         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7624                                   ->getPointeeType()
7625                                   .getAddressSpace();
7626         Kind =
7627             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7628         return Compatible;
7629       }
7630     }
7631 
7632     return Incompatible;
7633   }
7634 
7635   // Conversions to block pointers.
7636   if (isa<BlockPointerType>(LHSType)) {
7637     // U^ -> T^
7638     if (RHSType->isBlockPointerType()) {
7639       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7640                                 ->getPointeeType()
7641                                 .getAddressSpace();
7642       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7643                                 ->getPointeeType()
7644                                 .getAddressSpace();
7645       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7646       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7647     }
7648 
7649     // int or null -> T^
7650     if (RHSType->isIntegerType()) {
7651       Kind = CK_IntegralToPointer; // FIXME: null
7652       return IntToBlockPointer;
7653     }
7654 
7655     // id -> T^
7656     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7657       Kind = CK_AnyPointerToBlockPointerCast;
7658       return Compatible;
7659     }
7660 
7661     // void* -> T^
7662     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7663       if (RHSPT->getPointeeType()->isVoidType()) {
7664         Kind = CK_AnyPointerToBlockPointerCast;
7665         return Compatible;
7666       }
7667 
7668     return Incompatible;
7669   }
7670 
7671   // Conversions to Objective-C pointers.
7672   if (isa<ObjCObjectPointerType>(LHSType)) {
7673     // A* -> B*
7674     if (RHSType->isObjCObjectPointerType()) {
7675       Kind = CK_BitCast;
7676       Sema::AssignConvertType result =
7677         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7678       if (getLangOpts().ObjCAutoRefCount &&
7679           result == Compatible &&
7680           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7681         result = IncompatibleObjCWeakRef;
7682       return result;
7683     }
7684 
7685     // int or null -> A*
7686     if (RHSType->isIntegerType()) {
7687       Kind = CK_IntegralToPointer; // FIXME: null
7688       return IntToPointer;
7689     }
7690 
7691     // In general, C pointers are not compatible with ObjC object pointers,
7692     // with two exceptions:
7693     if (isa<PointerType>(RHSType)) {
7694       Kind = CK_CPointerToObjCPointerCast;
7695 
7696       //  - conversions from 'void*'
7697       if (RHSType->isVoidPointerType()) {
7698         return Compatible;
7699       }
7700 
7701       //  - conversions to 'Class' from its redefinition type
7702       if (LHSType->isObjCClassType() &&
7703           Context.hasSameType(RHSType,
7704                               Context.getObjCClassRedefinitionType())) {
7705         return Compatible;
7706       }
7707 
7708       return IncompatiblePointer;
7709     }
7710 
7711     // Only under strict condition T^ is compatible with an Objective-C pointer.
7712     if (RHSType->isBlockPointerType() &&
7713         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7714       if (ConvertRHS)
7715         maybeExtendBlockObject(RHS);
7716       Kind = CK_BlockPointerToObjCPointerCast;
7717       return Compatible;
7718     }
7719 
7720     return Incompatible;
7721   }
7722 
7723   // Conversions from pointers that are not covered by the above.
7724   if (isa<PointerType>(RHSType)) {
7725     // T* -> _Bool
7726     if (LHSType == Context.BoolTy) {
7727       Kind = CK_PointerToBoolean;
7728       return Compatible;
7729     }
7730 
7731     // T* -> int
7732     if (LHSType->isIntegerType()) {
7733       Kind = CK_PointerToIntegral;
7734       return PointerToInt;
7735     }
7736 
7737     return Incompatible;
7738   }
7739 
7740   // Conversions from Objective-C pointers that are not covered by the above.
7741   if (isa<ObjCObjectPointerType>(RHSType)) {
7742     // T* -> _Bool
7743     if (LHSType == Context.BoolTy) {
7744       Kind = CK_PointerToBoolean;
7745       return Compatible;
7746     }
7747 
7748     // T* -> int
7749     if (LHSType->isIntegerType()) {
7750       Kind = CK_PointerToIntegral;
7751       return PointerToInt;
7752     }
7753 
7754     return Incompatible;
7755   }
7756 
7757   // struct A -> struct B
7758   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7759     if (Context.typesAreCompatible(LHSType, RHSType)) {
7760       Kind = CK_NoOp;
7761       return Compatible;
7762     }
7763   }
7764 
7765   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7766     Kind = CK_IntToOCLSampler;
7767     return Compatible;
7768   }
7769 
7770   return Incompatible;
7771 }
7772 
7773 /// \brief Constructs a transparent union from an expression that is
7774 /// used to initialize the transparent union.
7775 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7776                                       ExprResult &EResult, QualType UnionType,
7777                                       FieldDecl *Field) {
7778   // Build an initializer list that designates the appropriate member
7779   // of the transparent union.
7780   Expr *E = EResult.get();
7781   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7782                                                    E, SourceLocation());
7783   Initializer->setType(UnionType);
7784   Initializer->setInitializedFieldInUnion(Field);
7785 
7786   // Build a compound literal constructing a value of the transparent
7787   // union type from this initializer list.
7788   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7789   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7790                                         VK_RValue, Initializer, false);
7791 }
7792 
7793 Sema::AssignConvertType
7794 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7795                                                ExprResult &RHS) {
7796   QualType RHSType = RHS.get()->getType();
7797 
7798   // If the ArgType is a Union type, we want to handle a potential
7799   // transparent_union GCC extension.
7800   const RecordType *UT = ArgType->getAsUnionType();
7801   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7802     return Incompatible;
7803 
7804   // The field to initialize within the transparent union.
7805   RecordDecl *UD = UT->getDecl();
7806   FieldDecl *InitField = nullptr;
7807   // It's compatible if the expression matches any of the fields.
7808   for (auto *it : UD->fields()) {
7809     if (it->getType()->isPointerType()) {
7810       // If the transparent union contains a pointer type, we allow:
7811       // 1) void pointer
7812       // 2) null pointer constant
7813       if (RHSType->isPointerType())
7814         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7815           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7816           InitField = it;
7817           break;
7818         }
7819 
7820       if (RHS.get()->isNullPointerConstant(Context,
7821                                            Expr::NPC_ValueDependentIsNull)) {
7822         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7823                                 CK_NullToPointer);
7824         InitField = it;
7825         break;
7826       }
7827     }
7828 
7829     CastKind Kind = CK_Invalid;
7830     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7831           == Compatible) {
7832       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7833       InitField = it;
7834       break;
7835     }
7836   }
7837 
7838   if (!InitField)
7839     return Incompatible;
7840 
7841   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7842   return Compatible;
7843 }
7844 
7845 Sema::AssignConvertType
7846 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7847                                        bool Diagnose,
7848                                        bool DiagnoseCFAudited,
7849                                        bool ConvertRHS) {
7850   // We need to be able to tell the caller whether we diagnosed a problem, if
7851   // they ask us to issue diagnostics.
7852   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7853 
7854   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7855   // we can't avoid *all* modifications at the moment, so we need some somewhere
7856   // to put the updated value.
7857   ExprResult LocalRHS = CallerRHS;
7858   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7859 
7860   if (getLangOpts().CPlusPlus) {
7861     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7862       // C++ 5.17p3: If the left operand is not of class type, the
7863       // expression is implicitly converted (C++ 4) to the
7864       // cv-unqualified type of the left operand.
7865       QualType RHSType = RHS.get()->getType();
7866       if (Diagnose) {
7867         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7868                                         AA_Assigning);
7869       } else {
7870         ImplicitConversionSequence ICS =
7871             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7872                                   /*SuppressUserConversions=*/false,
7873                                   /*AllowExplicit=*/false,
7874                                   /*InOverloadResolution=*/false,
7875                                   /*CStyle=*/false,
7876                                   /*AllowObjCWritebackConversion=*/false);
7877         if (ICS.isFailure())
7878           return Incompatible;
7879         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7880                                         ICS, AA_Assigning);
7881       }
7882       if (RHS.isInvalid())
7883         return Incompatible;
7884       Sema::AssignConvertType result = Compatible;
7885       if (getLangOpts().ObjCAutoRefCount &&
7886           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7887         result = IncompatibleObjCWeakRef;
7888       return result;
7889     }
7890 
7891     // FIXME: Currently, we fall through and treat C++ classes like C
7892     // structures.
7893     // FIXME: We also fall through for atomics; not sure what should
7894     // happen there, though.
7895   } else if (RHS.get()->getType() == Context.OverloadTy) {
7896     // As a set of extensions to C, we support overloading on functions. These
7897     // functions need to be resolved here.
7898     DeclAccessPair DAP;
7899     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7900             RHS.get(), LHSType, /*Complain=*/false, DAP))
7901       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7902     else
7903       return Incompatible;
7904   }
7905 
7906   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7907   // a null pointer constant.
7908   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7909        LHSType->isBlockPointerType()) &&
7910       RHS.get()->isNullPointerConstant(Context,
7911                                        Expr::NPC_ValueDependentIsNull)) {
7912     if (Diagnose || ConvertRHS) {
7913       CastKind Kind;
7914       CXXCastPath Path;
7915       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7916                              /*IgnoreBaseAccess=*/false, Diagnose);
7917       if (ConvertRHS)
7918         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7919     }
7920     return Compatible;
7921   }
7922 
7923   // This check seems unnatural, however it is necessary to ensure the proper
7924   // conversion of functions/arrays. If the conversion were done for all
7925   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7926   // expressions that suppress this implicit conversion (&, sizeof).
7927   //
7928   // Suppress this for references: C++ 8.5.3p5.
7929   if (!LHSType->isReferenceType()) {
7930     // FIXME: We potentially allocate here even if ConvertRHS is false.
7931     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7932     if (RHS.isInvalid())
7933       return Incompatible;
7934   }
7935 
7936   Expr *PRE = RHS.get()->IgnoreParenCasts();
7937   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7938     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7939     if (PDecl && !PDecl->hasDefinition()) {
7940       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7941       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7942     }
7943   }
7944 
7945   CastKind Kind = CK_Invalid;
7946   Sema::AssignConvertType result =
7947     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7948 
7949   // C99 6.5.16.1p2: The value of the right operand is converted to the
7950   // type of the assignment expression.
7951   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7952   // so that we can use references in built-in functions even in C.
7953   // The getNonReferenceType() call makes sure that the resulting expression
7954   // does not have reference type.
7955   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7956     QualType Ty = LHSType.getNonLValueExprType(Context);
7957     Expr *E = RHS.get();
7958 
7959     // Check for various Objective-C errors. If we are not reporting
7960     // diagnostics and just checking for errors, e.g., during overload
7961     // resolution, return Incompatible to indicate the failure.
7962     if (getLangOpts().ObjCAutoRefCount &&
7963         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7964                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7965       if (!Diagnose)
7966         return Incompatible;
7967     }
7968     if (getLangOpts().ObjC1 &&
7969         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7970                                            E->getType(), E, Diagnose) ||
7971          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7972       if (!Diagnose)
7973         return Incompatible;
7974       // Replace the expression with a corrected version and continue so we
7975       // can find further errors.
7976       RHS = E;
7977       return Compatible;
7978     }
7979 
7980     if (ConvertRHS)
7981       RHS = ImpCastExprToType(E, Ty, Kind);
7982   }
7983   return result;
7984 }
7985 
7986 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7987                                ExprResult &RHS) {
7988   Diag(Loc, diag::err_typecheck_invalid_operands)
7989     << LHS.get()->getType() << RHS.get()->getType()
7990     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7991   return QualType();
7992 }
7993 
7994 /// Try to convert a value of non-vector type to a vector type by converting
7995 /// the type to the element type of the vector and then performing a splat.
7996 /// If the language is OpenCL, we only use conversions that promote scalar
7997 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7998 /// for float->int.
7999 ///
8000 /// \param scalar - if non-null, actually perform the conversions
8001 /// \return true if the operation fails (but without diagnosing the failure)
8002 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8003                                      QualType scalarTy,
8004                                      QualType vectorEltTy,
8005                                      QualType vectorTy) {
8006   // The conversion to apply to the scalar before splatting it,
8007   // if necessary.
8008   CastKind scalarCast = CK_Invalid;
8009 
8010   if (vectorEltTy->isIntegralType(S.Context)) {
8011     if (!scalarTy->isIntegralType(S.Context))
8012       return true;
8013     if (S.getLangOpts().OpenCL &&
8014         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8015       return true;
8016     scalarCast = CK_IntegralCast;
8017   } else if (vectorEltTy->isRealFloatingType()) {
8018     if (scalarTy->isRealFloatingType()) {
8019       if (S.getLangOpts().OpenCL &&
8020           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8021         return true;
8022       scalarCast = CK_FloatingCast;
8023     }
8024     else if (scalarTy->isIntegralType(S.Context))
8025       scalarCast = CK_IntegralToFloating;
8026     else
8027       return true;
8028   } else {
8029     return true;
8030   }
8031 
8032   // Adjust scalar if desired.
8033   if (scalar) {
8034     if (scalarCast != CK_Invalid)
8035       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8036     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8037   }
8038   return false;
8039 }
8040 
8041 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8042                                    SourceLocation Loc, bool IsCompAssign,
8043                                    bool AllowBothBool,
8044                                    bool AllowBoolConversions) {
8045   if (!IsCompAssign) {
8046     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8047     if (LHS.isInvalid())
8048       return QualType();
8049   }
8050   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8051   if (RHS.isInvalid())
8052     return QualType();
8053 
8054   // For conversion purposes, we ignore any qualifiers.
8055   // For example, "const float" and "float" are equivalent.
8056   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8057   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8058 
8059   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8060   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8061   assert(LHSVecType || RHSVecType);
8062 
8063   // AltiVec-style "vector bool op vector bool" combinations are allowed
8064   // for some operators but not others.
8065   if (!AllowBothBool &&
8066       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8067       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8068     return InvalidOperands(Loc, LHS, RHS);
8069 
8070   // If the vector types are identical, return.
8071   if (Context.hasSameType(LHSType, RHSType))
8072     return LHSType;
8073 
8074   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8075   if (LHSVecType && RHSVecType &&
8076       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8077     if (isa<ExtVectorType>(LHSVecType)) {
8078       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8079       return LHSType;
8080     }
8081 
8082     if (!IsCompAssign)
8083       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8084     return RHSType;
8085   }
8086 
8087   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8088   // can be mixed, with the result being the non-bool type.  The non-bool
8089   // operand must have integer element type.
8090   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8091       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8092       (Context.getTypeSize(LHSVecType->getElementType()) ==
8093        Context.getTypeSize(RHSVecType->getElementType()))) {
8094     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8095         LHSVecType->getElementType()->isIntegerType() &&
8096         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8097       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8098       return LHSType;
8099     }
8100     if (!IsCompAssign &&
8101         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8102         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8103         RHSVecType->getElementType()->isIntegerType()) {
8104       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8105       return RHSType;
8106     }
8107   }
8108 
8109   // If there's an ext-vector type and a scalar, try to convert the scalar to
8110   // the vector element type and splat.
8111   // FIXME: this should also work for regular vector types as supported in GCC.
8112   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8113     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8114                                   LHSVecType->getElementType(), LHSType))
8115       return LHSType;
8116   }
8117   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8118     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8119                                   LHSType, RHSVecType->getElementType(),
8120                                   RHSType))
8121       return RHSType;
8122   }
8123 
8124   // FIXME: The code below also handles convertion between vectors and
8125   // non-scalars, we should break this down into fine grained specific checks
8126   // and emit proper diagnostics.
8127   QualType VecType = LHSVecType ? LHSType : RHSType;
8128   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8129   QualType OtherType = LHSVecType ? RHSType : LHSType;
8130   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8131   if (isLaxVectorConversion(OtherType, VecType)) {
8132     // If we're allowing lax vector conversions, only the total (data) size
8133     // needs to be the same. For non compound assignment, if one of the types is
8134     // scalar, the result is always the vector type.
8135     if (!IsCompAssign) {
8136       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8137       return VecType;
8138     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8139     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8140     // type. Note that this is already done by non-compound assignments in
8141     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8142     // <1 x T> -> T. The result is also a vector type.
8143     } else if (OtherType->isExtVectorType() ||
8144                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8145       ExprResult *RHSExpr = &RHS;
8146       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8147       return VecType;
8148     }
8149   }
8150 
8151   // Okay, the expression is invalid.
8152 
8153   // If there's a non-vector, non-real operand, diagnose that.
8154   if ((!RHSVecType && !RHSType->isRealType()) ||
8155       (!LHSVecType && !LHSType->isRealType())) {
8156     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8157       << LHSType << RHSType
8158       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8159     return QualType();
8160   }
8161 
8162   // OpenCL V1.1 6.2.6.p1:
8163   // If the operands are of more than one vector type, then an error shall
8164   // occur. Implicit conversions between vector types are not permitted, per
8165   // section 6.2.1.
8166   if (getLangOpts().OpenCL &&
8167       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8168       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8169     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8170                                                            << RHSType;
8171     return QualType();
8172   }
8173 
8174   // Otherwise, use the generic diagnostic.
8175   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8176     << LHSType << RHSType
8177     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8178   return QualType();
8179 }
8180 
8181 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8182 // expression.  These are mainly cases where the null pointer is used as an
8183 // integer instead of a pointer.
8184 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8185                                 SourceLocation Loc, bool IsCompare) {
8186   // The canonical way to check for a GNU null is with isNullPointerConstant,
8187   // but we use a bit of a hack here for speed; this is a relatively
8188   // hot path, and isNullPointerConstant is slow.
8189   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8190   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8191 
8192   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8193 
8194   // Avoid analyzing cases where the result will either be invalid (and
8195   // diagnosed as such) or entirely valid and not something to warn about.
8196   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8197       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8198     return;
8199 
8200   // Comparison operations would not make sense with a null pointer no matter
8201   // what the other expression is.
8202   if (!IsCompare) {
8203     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8204         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8205         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8206     return;
8207   }
8208 
8209   // The rest of the operations only make sense with a null pointer
8210   // if the other expression is a pointer.
8211   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8212       NonNullType->canDecayToPointerType())
8213     return;
8214 
8215   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8216       << LHSNull /* LHS is NULL */ << NonNullType
8217       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8218 }
8219 
8220 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8221                                                ExprResult &RHS,
8222                                                SourceLocation Loc, bool IsDiv) {
8223   // Check for division/remainder by zero.
8224   llvm::APSInt RHSValue;
8225   if (!RHS.get()->isValueDependent() &&
8226       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8227     S.DiagRuntimeBehavior(Loc, RHS.get(),
8228                           S.PDiag(diag::warn_remainder_division_by_zero)
8229                             << IsDiv << RHS.get()->getSourceRange());
8230 }
8231 
8232 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8233                                            SourceLocation Loc,
8234                                            bool IsCompAssign, bool IsDiv) {
8235   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8236 
8237   if (LHS.get()->getType()->isVectorType() ||
8238       RHS.get()->getType()->isVectorType())
8239     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8240                                /*AllowBothBool*/getLangOpts().AltiVec,
8241                                /*AllowBoolConversions*/false);
8242 
8243   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8244   if (LHS.isInvalid() || RHS.isInvalid())
8245     return QualType();
8246 
8247 
8248   if (compType.isNull() || !compType->isArithmeticType())
8249     return InvalidOperands(Loc, LHS, RHS);
8250   if (IsDiv)
8251     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8252   return compType;
8253 }
8254 
8255 QualType Sema::CheckRemainderOperands(
8256   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8257   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8258 
8259   if (LHS.get()->getType()->isVectorType() ||
8260       RHS.get()->getType()->isVectorType()) {
8261     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8262         RHS.get()->getType()->hasIntegerRepresentation())
8263       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8264                                  /*AllowBothBool*/getLangOpts().AltiVec,
8265                                  /*AllowBoolConversions*/false);
8266     return InvalidOperands(Loc, LHS, RHS);
8267   }
8268 
8269   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8270   if (LHS.isInvalid() || RHS.isInvalid())
8271     return QualType();
8272 
8273   if (compType.isNull() || !compType->isIntegerType())
8274     return InvalidOperands(Loc, LHS, RHS);
8275   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8276   return compType;
8277 }
8278 
8279 /// \brief Diagnose invalid arithmetic on two void pointers.
8280 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8281                                                 Expr *LHSExpr, Expr *RHSExpr) {
8282   S.Diag(Loc, S.getLangOpts().CPlusPlus
8283                 ? diag::err_typecheck_pointer_arith_void_type
8284                 : diag::ext_gnu_void_ptr)
8285     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8286                             << RHSExpr->getSourceRange();
8287 }
8288 
8289 /// \brief Diagnose invalid arithmetic on a void pointer.
8290 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8291                                             Expr *Pointer) {
8292   S.Diag(Loc, S.getLangOpts().CPlusPlus
8293                 ? diag::err_typecheck_pointer_arith_void_type
8294                 : diag::ext_gnu_void_ptr)
8295     << 0 /* one pointer */ << Pointer->getSourceRange();
8296 }
8297 
8298 /// \brief Diagnose invalid arithmetic on two function pointers.
8299 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8300                                                     Expr *LHS, Expr *RHS) {
8301   assert(LHS->getType()->isAnyPointerType());
8302   assert(RHS->getType()->isAnyPointerType());
8303   S.Diag(Loc, S.getLangOpts().CPlusPlus
8304                 ? diag::err_typecheck_pointer_arith_function_type
8305                 : diag::ext_gnu_ptr_func_arith)
8306     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8307     // We only show the second type if it differs from the first.
8308     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8309                                                    RHS->getType())
8310     << RHS->getType()->getPointeeType()
8311     << LHS->getSourceRange() << RHS->getSourceRange();
8312 }
8313 
8314 /// \brief Diagnose invalid arithmetic on a function pointer.
8315 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8316                                                 Expr *Pointer) {
8317   assert(Pointer->getType()->isAnyPointerType());
8318   S.Diag(Loc, S.getLangOpts().CPlusPlus
8319                 ? diag::err_typecheck_pointer_arith_function_type
8320                 : diag::ext_gnu_ptr_func_arith)
8321     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8322     << 0 /* one pointer, so only one type */
8323     << Pointer->getSourceRange();
8324 }
8325 
8326 /// \brief Emit error if Operand is incomplete pointer type
8327 ///
8328 /// \returns True if pointer has incomplete type
8329 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8330                                                  Expr *Operand) {
8331   QualType ResType = Operand->getType();
8332   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8333     ResType = ResAtomicType->getValueType();
8334 
8335   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8336   QualType PointeeTy = ResType->getPointeeType();
8337   return S.RequireCompleteType(Loc, PointeeTy,
8338                                diag::err_typecheck_arithmetic_incomplete_type,
8339                                PointeeTy, Operand->getSourceRange());
8340 }
8341 
8342 /// \brief Check the validity of an arithmetic pointer operand.
8343 ///
8344 /// If the operand has pointer type, this code will check for pointer types
8345 /// which are invalid in arithmetic operations. These will be diagnosed
8346 /// appropriately, including whether or not the use is supported as an
8347 /// extension.
8348 ///
8349 /// \returns True when the operand is valid to use (even if as an extension).
8350 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8351                                             Expr *Operand) {
8352   QualType ResType = Operand->getType();
8353   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8354     ResType = ResAtomicType->getValueType();
8355 
8356   if (!ResType->isAnyPointerType()) return true;
8357 
8358   QualType PointeeTy = ResType->getPointeeType();
8359   if (PointeeTy->isVoidType()) {
8360     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8361     return !S.getLangOpts().CPlusPlus;
8362   }
8363   if (PointeeTy->isFunctionType()) {
8364     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8365     return !S.getLangOpts().CPlusPlus;
8366   }
8367 
8368   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8369 
8370   return true;
8371 }
8372 
8373 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8374 /// operands.
8375 ///
8376 /// This routine will diagnose any invalid arithmetic on pointer operands much
8377 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8378 /// for emitting a single diagnostic even for operations where both LHS and RHS
8379 /// are (potentially problematic) pointers.
8380 ///
8381 /// \returns True when the operand is valid to use (even if as an extension).
8382 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8383                                                 Expr *LHSExpr, Expr *RHSExpr) {
8384   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8385   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8386   if (!isLHSPointer && !isRHSPointer) return true;
8387 
8388   QualType LHSPointeeTy, RHSPointeeTy;
8389   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8390   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8391 
8392   // if both are pointers check if operation is valid wrt address spaces
8393   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8394     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8395     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8396     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8397       S.Diag(Loc,
8398              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8399           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8400           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8401       return false;
8402     }
8403   }
8404 
8405   // Check for arithmetic on pointers to incomplete types.
8406   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8407   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8408   if (isLHSVoidPtr || isRHSVoidPtr) {
8409     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8410     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8411     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8412 
8413     return !S.getLangOpts().CPlusPlus;
8414   }
8415 
8416   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8417   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8418   if (isLHSFuncPtr || isRHSFuncPtr) {
8419     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8420     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8421                                                                 RHSExpr);
8422     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8423 
8424     return !S.getLangOpts().CPlusPlus;
8425   }
8426 
8427   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8428     return false;
8429   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8430     return false;
8431 
8432   return true;
8433 }
8434 
8435 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8436 /// literal.
8437 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8438                                   Expr *LHSExpr, Expr *RHSExpr) {
8439   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8440   Expr* IndexExpr = RHSExpr;
8441   if (!StrExpr) {
8442     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8443     IndexExpr = LHSExpr;
8444   }
8445 
8446   bool IsStringPlusInt = StrExpr &&
8447       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8448   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8449     return;
8450 
8451   llvm::APSInt index;
8452   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8453     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8454     if (index.isNonNegative() &&
8455         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8456                               index.isUnsigned()))
8457       return;
8458   }
8459 
8460   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8461   Self.Diag(OpLoc, diag::warn_string_plus_int)
8462       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8463 
8464   // Only print a fixit for "str" + int, not for int + "str".
8465   if (IndexExpr == RHSExpr) {
8466     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8467     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8468         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8469         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8470         << FixItHint::CreateInsertion(EndLoc, "]");
8471   } else
8472     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8473 }
8474 
8475 /// \brief Emit a warning when adding a char literal to a string.
8476 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8477                                    Expr *LHSExpr, Expr *RHSExpr) {
8478   const Expr *StringRefExpr = LHSExpr;
8479   const CharacterLiteral *CharExpr =
8480       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8481 
8482   if (!CharExpr) {
8483     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8484     StringRefExpr = RHSExpr;
8485   }
8486 
8487   if (!CharExpr || !StringRefExpr)
8488     return;
8489 
8490   const QualType StringType = StringRefExpr->getType();
8491 
8492   // Return if not a PointerType.
8493   if (!StringType->isAnyPointerType())
8494     return;
8495 
8496   // Return if not a CharacterType.
8497   if (!StringType->getPointeeType()->isAnyCharacterType())
8498     return;
8499 
8500   ASTContext &Ctx = Self.getASTContext();
8501   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8502 
8503   const QualType CharType = CharExpr->getType();
8504   if (!CharType->isAnyCharacterType() &&
8505       CharType->isIntegerType() &&
8506       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8507     Self.Diag(OpLoc, diag::warn_string_plus_char)
8508         << DiagRange << Ctx.CharTy;
8509   } else {
8510     Self.Diag(OpLoc, diag::warn_string_plus_char)
8511         << DiagRange << CharExpr->getType();
8512   }
8513 
8514   // Only print a fixit for str + char, not for char + str.
8515   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8516     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8517     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8518         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8519         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8520         << FixItHint::CreateInsertion(EndLoc, "]");
8521   } else {
8522     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8523   }
8524 }
8525 
8526 /// \brief Emit error when two pointers are incompatible.
8527 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8528                                            Expr *LHSExpr, Expr *RHSExpr) {
8529   assert(LHSExpr->getType()->isAnyPointerType());
8530   assert(RHSExpr->getType()->isAnyPointerType());
8531   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8532     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8533     << RHSExpr->getSourceRange();
8534 }
8535 
8536 // C99 6.5.6
8537 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8538                                      SourceLocation Loc, BinaryOperatorKind Opc,
8539                                      QualType* CompLHSTy) {
8540   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8541 
8542   if (LHS.get()->getType()->isVectorType() ||
8543       RHS.get()->getType()->isVectorType()) {
8544     QualType compType = CheckVectorOperands(
8545         LHS, RHS, Loc, CompLHSTy,
8546         /*AllowBothBool*/getLangOpts().AltiVec,
8547         /*AllowBoolConversions*/getLangOpts().ZVector);
8548     if (CompLHSTy) *CompLHSTy = compType;
8549     return compType;
8550   }
8551 
8552   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8553   if (LHS.isInvalid() || RHS.isInvalid())
8554     return QualType();
8555 
8556   // Diagnose "string literal" '+' int and string '+' "char literal".
8557   if (Opc == BO_Add) {
8558     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8559     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8560   }
8561 
8562   // handle the common case first (both operands are arithmetic).
8563   if (!compType.isNull() && compType->isArithmeticType()) {
8564     if (CompLHSTy) *CompLHSTy = compType;
8565     return compType;
8566   }
8567 
8568   // Type-checking.  Ultimately the pointer's going to be in PExp;
8569   // note that we bias towards the LHS being the pointer.
8570   Expr *PExp = LHS.get(), *IExp = RHS.get();
8571 
8572   bool isObjCPointer;
8573   if (PExp->getType()->isPointerType()) {
8574     isObjCPointer = false;
8575   } else if (PExp->getType()->isObjCObjectPointerType()) {
8576     isObjCPointer = true;
8577   } else {
8578     std::swap(PExp, IExp);
8579     if (PExp->getType()->isPointerType()) {
8580       isObjCPointer = false;
8581     } else if (PExp->getType()->isObjCObjectPointerType()) {
8582       isObjCPointer = true;
8583     } else {
8584       return InvalidOperands(Loc, LHS, RHS);
8585     }
8586   }
8587   assert(PExp->getType()->isAnyPointerType());
8588 
8589   if (!IExp->getType()->isIntegerType())
8590     return InvalidOperands(Loc, LHS, RHS);
8591 
8592   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8593     return QualType();
8594 
8595   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8596     return QualType();
8597 
8598   // Check array bounds for pointer arithemtic
8599   CheckArrayAccess(PExp, IExp);
8600 
8601   if (CompLHSTy) {
8602     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8603     if (LHSTy.isNull()) {
8604       LHSTy = LHS.get()->getType();
8605       if (LHSTy->isPromotableIntegerType())
8606         LHSTy = Context.getPromotedIntegerType(LHSTy);
8607     }
8608     *CompLHSTy = LHSTy;
8609   }
8610 
8611   return PExp->getType();
8612 }
8613 
8614 // C99 6.5.6
8615 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8616                                         SourceLocation Loc,
8617                                         QualType* CompLHSTy) {
8618   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8619 
8620   if (LHS.get()->getType()->isVectorType() ||
8621       RHS.get()->getType()->isVectorType()) {
8622     QualType compType = CheckVectorOperands(
8623         LHS, RHS, Loc, CompLHSTy,
8624         /*AllowBothBool*/getLangOpts().AltiVec,
8625         /*AllowBoolConversions*/getLangOpts().ZVector);
8626     if (CompLHSTy) *CompLHSTy = compType;
8627     return compType;
8628   }
8629 
8630   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8631   if (LHS.isInvalid() || RHS.isInvalid())
8632     return QualType();
8633 
8634   // Enforce type constraints: C99 6.5.6p3.
8635 
8636   // Handle the common case first (both operands are arithmetic).
8637   if (!compType.isNull() && compType->isArithmeticType()) {
8638     if (CompLHSTy) *CompLHSTy = compType;
8639     return compType;
8640   }
8641 
8642   // Either ptr - int   or   ptr - ptr.
8643   if (LHS.get()->getType()->isAnyPointerType()) {
8644     QualType lpointee = LHS.get()->getType()->getPointeeType();
8645 
8646     // Diagnose bad cases where we step over interface counts.
8647     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8648         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8649       return QualType();
8650 
8651     // The result type of a pointer-int computation is the pointer type.
8652     if (RHS.get()->getType()->isIntegerType()) {
8653       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8654         return QualType();
8655 
8656       // Check array bounds for pointer arithemtic
8657       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8658                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8659 
8660       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8661       return LHS.get()->getType();
8662     }
8663 
8664     // Handle pointer-pointer subtractions.
8665     if (const PointerType *RHSPTy
8666           = RHS.get()->getType()->getAs<PointerType>()) {
8667       QualType rpointee = RHSPTy->getPointeeType();
8668 
8669       if (getLangOpts().CPlusPlus) {
8670         // Pointee types must be the same: C++ [expr.add]
8671         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8672           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8673         }
8674       } else {
8675         // Pointee types must be compatible C99 6.5.6p3
8676         if (!Context.typesAreCompatible(
8677                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8678                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8679           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8680           return QualType();
8681         }
8682       }
8683 
8684       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8685                                                LHS.get(), RHS.get()))
8686         return QualType();
8687 
8688       // The pointee type may have zero size.  As an extension, a structure or
8689       // union may have zero size or an array may have zero length.  In this
8690       // case subtraction does not make sense.
8691       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8692         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8693         if (ElementSize.isZero()) {
8694           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8695             << rpointee.getUnqualifiedType()
8696             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8697         }
8698       }
8699 
8700       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8701       return Context.getPointerDiffType();
8702     }
8703   }
8704 
8705   return InvalidOperands(Loc, LHS, RHS);
8706 }
8707 
8708 static bool isScopedEnumerationType(QualType T) {
8709   if (const EnumType *ET = T->getAs<EnumType>())
8710     return ET->getDecl()->isScoped();
8711   return false;
8712 }
8713 
8714 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8715                                    SourceLocation Loc, BinaryOperatorKind Opc,
8716                                    QualType LHSType) {
8717   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8718   // so skip remaining warnings as we don't want to modify values within Sema.
8719   if (S.getLangOpts().OpenCL)
8720     return;
8721 
8722   llvm::APSInt Right;
8723   // Check right/shifter operand
8724   if (RHS.get()->isValueDependent() ||
8725       !RHS.get()->EvaluateAsInt(Right, S.Context))
8726     return;
8727 
8728   if (Right.isNegative()) {
8729     S.DiagRuntimeBehavior(Loc, RHS.get(),
8730                           S.PDiag(diag::warn_shift_negative)
8731                             << RHS.get()->getSourceRange());
8732     return;
8733   }
8734   llvm::APInt LeftBits(Right.getBitWidth(),
8735                        S.Context.getTypeSize(LHS.get()->getType()));
8736   if (Right.uge(LeftBits)) {
8737     S.DiagRuntimeBehavior(Loc, RHS.get(),
8738                           S.PDiag(diag::warn_shift_gt_typewidth)
8739                             << RHS.get()->getSourceRange());
8740     return;
8741   }
8742   if (Opc != BO_Shl)
8743     return;
8744 
8745   // When left shifting an ICE which is signed, we can check for overflow which
8746   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8747   // integers have defined behavior modulo one more than the maximum value
8748   // representable in the result type, so never warn for those.
8749   llvm::APSInt Left;
8750   if (LHS.get()->isValueDependent() ||
8751       LHSType->hasUnsignedIntegerRepresentation() ||
8752       !LHS.get()->EvaluateAsInt(Left, S.Context))
8753     return;
8754 
8755   // If LHS does not have a signed type and non-negative value
8756   // then, the behavior is undefined. Warn about it.
8757   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8758     S.DiagRuntimeBehavior(Loc, LHS.get(),
8759                           S.PDiag(diag::warn_shift_lhs_negative)
8760                             << LHS.get()->getSourceRange());
8761     return;
8762   }
8763 
8764   llvm::APInt ResultBits =
8765       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8766   if (LeftBits.uge(ResultBits))
8767     return;
8768   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8769   Result = Result.shl(Right);
8770 
8771   // Print the bit representation of the signed integer as an unsigned
8772   // hexadecimal number.
8773   SmallString<40> HexResult;
8774   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8775 
8776   // If we are only missing a sign bit, this is less likely to result in actual
8777   // bugs -- if the result is cast back to an unsigned type, it will have the
8778   // expected value. Thus we place this behind a different warning that can be
8779   // turned off separately if needed.
8780   if (LeftBits == ResultBits - 1) {
8781     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8782         << HexResult << LHSType
8783         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8784     return;
8785   }
8786 
8787   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8788     << HexResult.str() << Result.getMinSignedBits() << LHSType
8789     << Left.getBitWidth() << LHS.get()->getSourceRange()
8790     << RHS.get()->getSourceRange();
8791 }
8792 
8793 /// \brief Return the resulting type when a vector is shifted
8794 ///        by a scalar or vector shift amount.
8795 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8796                                  SourceLocation Loc, bool IsCompAssign) {
8797   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8798   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8799       !LHS.get()->getType()->isVectorType()) {
8800     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8801       << RHS.get()->getType() << LHS.get()->getType()
8802       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8803     return QualType();
8804   }
8805 
8806   if (!IsCompAssign) {
8807     LHS = S.UsualUnaryConversions(LHS.get());
8808     if (LHS.isInvalid()) return QualType();
8809   }
8810 
8811   RHS = S.UsualUnaryConversions(RHS.get());
8812   if (RHS.isInvalid()) return QualType();
8813 
8814   QualType LHSType = LHS.get()->getType();
8815   // Note that LHS might be a scalar because the routine calls not only in
8816   // OpenCL case.
8817   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8818   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8819 
8820   // Note that RHS might not be a vector.
8821   QualType RHSType = RHS.get()->getType();
8822   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8823   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8824 
8825   // The operands need to be integers.
8826   if (!LHSEleType->isIntegerType()) {
8827     S.Diag(Loc, diag::err_typecheck_expect_int)
8828       << LHS.get()->getType() << LHS.get()->getSourceRange();
8829     return QualType();
8830   }
8831 
8832   if (!RHSEleType->isIntegerType()) {
8833     S.Diag(Loc, diag::err_typecheck_expect_int)
8834       << RHS.get()->getType() << RHS.get()->getSourceRange();
8835     return QualType();
8836   }
8837 
8838   if (!LHSVecTy) {
8839     assert(RHSVecTy);
8840     if (IsCompAssign)
8841       return RHSType;
8842     if (LHSEleType != RHSEleType) {
8843       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8844       LHSEleType = RHSEleType;
8845     }
8846     QualType VecTy =
8847         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8848     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8849     LHSType = VecTy;
8850   } else if (RHSVecTy) {
8851     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8852     // are applied component-wise. So if RHS is a vector, then ensure
8853     // that the number of elements is the same as LHS...
8854     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8855       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8856         << LHS.get()->getType() << RHS.get()->getType()
8857         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8858       return QualType();
8859     }
8860     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8861       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8862       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8863       if (LHSBT != RHSBT &&
8864           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8865         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8866             << LHS.get()->getType() << RHS.get()->getType()
8867             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8868       }
8869     }
8870   } else {
8871     // ...else expand RHS to match the number of elements in LHS.
8872     QualType VecTy =
8873       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8874     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8875   }
8876 
8877   return LHSType;
8878 }
8879 
8880 // C99 6.5.7
8881 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8882                                   SourceLocation Loc, BinaryOperatorKind Opc,
8883                                   bool IsCompAssign) {
8884   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8885 
8886   // Vector shifts promote their scalar inputs to vector type.
8887   if (LHS.get()->getType()->isVectorType() ||
8888       RHS.get()->getType()->isVectorType()) {
8889     if (LangOpts.ZVector) {
8890       // The shift operators for the z vector extensions work basically
8891       // like general shifts, except that neither the LHS nor the RHS is
8892       // allowed to be a "vector bool".
8893       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8894         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8895           return InvalidOperands(Loc, LHS, RHS);
8896       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8897         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8898           return InvalidOperands(Loc, LHS, RHS);
8899     }
8900     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8901   }
8902 
8903   // Shifts don't perform usual arithmetic conversions, they just do integer
8904   // promotions on each operand. C99 6.5.7p3
8905 
8906   // For the LHS, do usual unary conversions, but then reset them away
8907   // if this is a compound assignment.
8908   ExprResult OldLHS = LHS;
8909   LHS = UsualUnaryConversions(LHS.get());
8910   if (LHS.isInvalid())
8911     return QualType();
8912   QualType LHSType = LHS.get()->getType();
8913   if (IsCompAssign) LHS = OldLHS;
8914 
8915   // The RHS is simpler.
8916   RHS = UsualUnaryConversions(RHS.get());
8917   if (RHS.isInvalid())
8918     return QualType();
8919   QualType RHSType = RHS.get()->getType();
8920 
8921   // C99 6.5.7p2: Each of the operands shall have integer type.
8922   if (!LHSType->hasIntegerRepresentation() ||
8923       !RHSType->hasIntegerRepresentation())
8924     return InvalidOperands(Loc, LHS, RHS);
8925 
8926   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8927   // hasIntegerRepresentation() above instead of this.
8928   if (isScopedEnumerationType(LHSType) ||
8929       isScopedEnumerationType(RHSType)) {
8930     return InvalidOperands(Loc, LHS, RHS);
8931   }
8932   // Sanity-check shift operands
8933   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8934 
8935   // "The type of the result is that of the promoted left operand."
8936   return LHSType;
8937 }
8938 
8939 static bool IsWithinTemplateSpecialization(Decl *D) {
8940   if (DeclContext *DC = D->getDeclContext()) {
8941     if (isa<ClassTemplateSpecializationDecl>(DC))
8942       return true;
8943     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8944       return FD->isFunctionTemplateSpecialization();
8945   }
8946   return false;
8947 }
8948 
8949 /// If two different enums are compared, raise a warning.
8950 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8951                                 Expr *RHS) {
8952   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8953   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8954 
8955   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8956   if (!LHSEnumType)
8957     return;
8958   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8959   if (!RHSEnumType)
8960     return;
8961 
8962   // Ignore anonymous enums.
8963   if (!LHSEnumType->getDecl()->getIdentifier())
8964     return;
8965   if (!RHSEnumType->getDecl()->getIdentifier())
8966     return;
8967 
8968   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8969     return;
8970 
8971   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8972       << LHSStrippedType << RHSStrippedType
8973       << LHS->getSourceRange() << RHS->getSourceRange();
8974 }
8975 
8976 /// \brief Diagnose bad pointer comparisons.
8977 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8978                                               ExprResult &LHS, ExprResult &RHS,
8979                                               bool IsError) {
8980   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8981                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8982     << LHS.get()->getType() << RHS.get()->getType()
8983     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8984 }
8985 
8986 /// \brief Returns false if the pointers are converted to a composite type,
8987 /// true otherwise.
8988 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8989                                            ExprResult &LHS, ExprResult &RHS) {
8990   // C++ [expr.rel]p2:
8991   //   [...] Pointer conversions (4.10) and qualification
8992   //   conversions (4.4) are performed on pointer operands (or on
8993   //   a pointer operand and a null pointer constant) to bring
8994   //   them to their composite pointer type. [...]
8995   //
8996   // C++ [expr.eq]p1 uses the same notion for (in)equality
8997   // comparisons of pointers.
8998 
8999   QualType LHSType = LHS.get()->getType();
9000   QualType RHSType = RHS.get()->getType();
9001   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9002          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9003 
9004   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9005   if (T.isNull()) {
9006     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9007         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9008       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9009     else
9010       S.InvalidOperands(Loc, LHS, RHS);
9011     return true;
9012   }
9013 
9014   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9015   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9016   return false;
9017 }
9018 
9019 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9020                                                     ExprResult &LHS,
9021                                                     ExprResult &RHS,
9022                                                     bool IsError) {
9023   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9024                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9025     << LHS.get()->getType() << RHS.get()->getType()
9026     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9027 }
9028 
9029 static bool isObjCObjectLiteral(ExprResult &E) {
9030   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9031   case Stmt::ObjCArrayLiteralClass:
9032   case Stmt::ObjCDictionaryLiteralClass:
9033   case Stmt::ObjCStringLiteralClass:
9034   case Stmt::ObjCBoxedExprClass:
9035     return true;
9036   default:
9037     // Note that ObjCBoolLiteral is NOT an object literal!
9038     return false;
9039   }
9040 }
9041 
9042 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9043   const ObjCObjectPointerType *Type =
9044     LHS->getType()->getAs<ObjCObjectPointerType>();
9045 
9046   // If this is not actually an Objective-C object, bail out.
9047   if (!Type)
9048     return false;
9049 
9050   // Get the LHS object's interface type.
9051   QualType InterfaceType = Type->getPointeeType();
9052 
9053   // If the RHS isn't an Objective-C object, bail out.
9054   if (!RHS->getType()->isObjCObjectPointerType())
9055     return false;
9056 
9057   // Try to find the -isEqual: method.
9058   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9059   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9060                                                       InterfaceType,
9061                                                       /*instance=*/true);
9062   if (!Method) {
9063     if (Type->isObjCIdType()) {
9064       // For 'id', just check the global pool.
9065       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9066                                                   /*receiverId=*/true);
9067     } else {
9068       // Check protocols.
9069       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9070                                              /*instance=*/true);
9071     }
9072   }
9073 
9074   if (!Method)
9075     return false;
9076 
9077   QualType T = Method->parameters()[0]->getType();
9078   if (!T->isObjCObjectPointerType())
9079     return false;
9080 
9081   QualType R = Method->getReturnType();
9082   if (!R->isScalarType())
9083     return false;
9084 
9085   return true;
9086 }
9087 
9088 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9089   FromE = FromE->IgnoreParenImpCasts();
9090   switch (FromE->getStmtClass()) {
9091     default:
9092       break;
9093     case Stmt::ObjCStringLiteralClass:
9094       // "string literal"
9095       return LK_String;
9096     case Stmt::ObjCArrayLiteralClass:
9097       // "array literal"
9098       return LK_Array;
9099     case Stmt::ObjCDictionaryLiteralClass:
9100       // "dictionary literal"
9101       return LK_Dictionary;
9102     case Stmt::BlockExprClass:
9103       return LK_Block;
9104     case Stmt::ObjCBoxedExprClass: {
9105       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9106       switch (Inner->getStmtClass()) {
9107         case Stmt::IntegerLiteralClass:
9108         case Stmt::FloatingLiteralClass:
9109         case Stmt::CharacterLiteralClass:
9110         case Stmt::ObjCBoolLiteralExprClass:
9111         case Stmt::CXXBoolLiteralExprClass:
9112           // "numeric literal"
9113           return LK_Numeric;
9114         case Stmt::ImplicitCastExprClass: {
9115           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9116           // Boolean literals can be represented by implicit casts.
9117           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9118             return LK_Numeric;
9119           break;
9120         }
9121         default:
9122           break;
9123       }
9124       return LK_Boxed;
9125     }
9126   }
9127   return LK_None;
9128 }
9129 
9130 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9131                                           ExprResult &LHS, ExprResult &RHS,
9132                                           BinaryOperator::Opcode Opc){
9133   Expr *Literal;
9134   Expr *Other;
9135   if (isObjCObjectLiteral(LHS)) {
9136     Literal = LHS.get();
9137     Other = RHS.get();
9138   } else {
9139     Literal = RHS.get();
9140     Other = LHS.get();
9141   }
9142 
9143   // Don't warn on comparisons against nil.
9144   Other = Other->IgnoreParenCasts();
9145   if (Other->isNullPointerConstant(S.getASTContext(),
9146                                    Expr::NPC_ValueDependentIsNotNull))
9147     return;
9148 
9149   // This should be kept in sync with warn_objc_literal_comparison.
9150   // LK_String should always be after the other literals, since it has its own
9151   // warning flag.
9152   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9153   assert(LiteralKind != Sema::LK_Block);
9154   if (LiteralKind == Sema::LK_None) {
9155     llvm_unreachable("Unknown Objective-C object literal kind");
9156   }
9157 
9158   if (LiteralKind == Sema::LK_String)
9159     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9160       << Literal->getSourceRange();
9161   else
9162     S.Diag(Loc, diag::warn_objc_literal_comparison)
9163       << LiteralKind << Literal->getSourceRange();
9164 
9165   if (BinaryOperator::isEqualityOp(Opc) &&
9166       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9167     SourceLocation Start = LHS.get()->getLocStart();
9168     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9169     CharSourceRange OpRange =
9170       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9171 
9172     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9173       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9174       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9175       << FixItHint::CreateInsertion(End, "]");
9176   }
9177 }
9178 
9179 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9180 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9181                                            ExprResult &RHS, SourceLocation Loc,
9182                                            BinaryOperatorKind Opc) {
9183   // Check that left hand side is !something.
9184   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9185   if (!UO || UO->getOpcode() != UO_LNot) return;
9186 
9187   // Only check if the right hand side is non-bool arithmetic type.
9188   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9189 
9190   // Make sure that the something in !something is not bool.
9191   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9192   if (SubExpr->isKnownToHaveBooleanValue()) return;
9193 
9194   // Emit warning.
9195   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9196   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9197       << Loc << IsBitwiseOp;
9198 
9199   // First note suggest !(x < y)
9200   SourceLocation FirstOpen = SubExpr->getLocStart();
9201   SourceLocation FirstClose = RHS.get()->getLocEnd();
9202   FirstClose = S.getLocForEndOfToken(FirstClose);
9203   if (FirstClose.isInvalid())
9204     FirstOpen = SourceLocation();
9205   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9206       << IsBitwiseOp
9207       << FixItHint::CreateInsertion(FirstOpen, "(")
9208       << FixItHint::CreateInsertion(FirstClose, ")");
9209 
9210   // Second note suggests (!x) < y
9211   SourceLocation SecondOpen = LHS.get()->getLocStart();
9212   SourceLocation SecondClose = LHS.get()->getLocEnd();
9213   SecondClose = S.getLocForEndOfToken(SecondClose);
9214   if (SecondClose.isInvalid())
9215     SecondOpen = SourceLocation();
9216   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9217       << FixItHint::CreateInsertion(SecondOpen, "(")
9218       << FixItHint::CreateInsertion(SecondClose, ")");
9219 }
9220 
9221 // Get the decl for a simple expression: a reference to a variable,
9222 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9223 static ValueDecl *getCompareDecl(Expr *E) {
9224   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9225     return DR->getDecl();
9226   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9227     if (Ivar->isFreeIvar())
9228       return Ivar->getDecl();
9229   }
9230   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9231     if (Mem->isImplicitAccess())
9232       return Mem->getMemberDecl();
9233   }
9234   return nullptr;
9235 }
9236 
9237 // C99 6.5.8, C++ [expr.rel]
9238 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9239                                     SourceLocation Loc, BinaryOperatorKind Opc,
9240                                     bool IsRelational) {
9241   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9242 
9243   // Handle vector comparisons separately.
9244   if (LHS.get()->getType()->isVectorType() ||
9245       RHS.get()->getType()->isVectorType())
9246     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9247 
9248   QualType LHSType = LHS.get()->getType();
9249   QualType RHSType = RHS.get()->getType();
9250 
9251   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9252   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9253 
9254   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9255   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9256 
9257   if (!LHSType->hasFloatingRepresentation() &&
9258       !(LHSType->isBlockPointerType() && IsRelational) &&
9259       !LHS.get()->getLocStart().isMacroID() &&
9260       !RHS.get()->getLocStart().isMacroID() &&
9261       ActiveTemplateInstantiations.empty()) {
9262     // For non-floating point types, check for self-comparisons of the form
9263     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9264     // often indicate logic errors in the program.
9265     //
9266     // NOTE: Don't warn about comparison expressions resulting from macro
9267     // expansion. Also don't warn about comparisons which are only self
9268     // comparisons within a template specialization. The warnings should catch
9269     // obvious cases in the definition of the template anyways. The idea is to
9270     // warn when the typed comparison operator will always evaluate to the same
9271     // result.
9272     ValueDecl *DL = getCompareDecl(LHSStripped);
9273     ValueDecl *DR = getCompareDecl(RHSStripped);
9274     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9275       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9276                           << 0 // self-
9277                           << (Opc == BO_EQ
9278                               || Opc == BO_LE
9279                               || Opc == BO_GE));
9280     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9281                !DL->getType()->isReferenceType() &&
9282                !DR->getType()->isReferenceType()) {
9283         // what is it always going to eval to?
9284         char always_evals_to;
9285         switch(Opc) {
9286         case BO_EQ: // e.g. array1 == array2
9287           always_evals_to = 0; // false
9288           break;
9289         case BO_NE: // e.g. array1 != array2
9290           always_evals_to = 1; // true
9291           break;
9292         default:
9293           // best we can say is 'a constant'
9294           always_evals_to = 2; // e.g. array1 <= array2
9295           break;
9296         }
9297         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9298                             << 1 // array
9299                             << always_evals_to);
9300     }
9301 
9302     if (isa<CastExpr>(LHSStripped))
9303       LHSStripped = LHSStripped->IgnoreParenCasts();
9304     if (isa<CastExpr>(RHSStripped))
9305       RHSStripped = RHSStripped->IgnoreParenCasts();
9306 
9307     // Warn about comparisons against a string constant (unless the other
9308     // operand is null), the user probably wants strcmp.
9309     Expr *literalString = nullptr;
9310     Expr *literalStringStripped = nullptr;
9311     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9312         !RHSStripped->isNullPointerConstant(Context,
9313                                             Expr::NPC_ValueDependentIsNull)) {
9314       literalString = LHS.get();
9315       literalStringStripped = LHSStripped;
9316     } else if ((isa<StringLiteral>(RHSStripped) ||
9317                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9318                !LHSStripped->isNullPointerConstant(Context,
9319                                             Expr::NPC_ValueDependentIsNull)) {
9320       literalString = RHS.get();
9321       literalStringStripped = RHSStripped;
9322     }
9323 
9324     if (literalString) {
9325       DiagRuntimeBehavior(Loc, nullptr,
9326         PDiag(diag::warn_stringcompare)
9327           << isa<ObjCEncodeExpr>(literalStringStripped)
9328           << literalString->getSourceRange());
9329     }
9330   }
9331 
9332   // C99 6.5.8p3 / C99 6.5.9p4
9333   UsualArithmeticConversions(LHS, RHS);
9334   if (LHS.isInvalid() || RHS.isInvalid())
9335     return QualType();
9336 
9337   LHSType = LHS.get()->getType();
9338   RHSType = RHS.get()->getType();
9339 
9340   // The result of comparisons is 'bool' in C++, 'int' in C.
9341   QualType ResultTy = Context.getLogicalOperationType();
9342 
9343   if (IsRelational) {
9344     if (LHSType->isRealType() && RHSType->isRealType())
9345       return ResultTy;
9346   } else {
9347     // Check for comparisons of floating point operands using != and ==.
9348     if (LHSType->hasFloatingRepresentation())
9349       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9350 
9351     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9352       return ResultTy;
9353   }
9354 
9355   const Expr::NullPointerConstantKind LHSNullKind =
9356       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9357   const Expr::NullPointerConstantKind RHSNullKind =
9358       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9359   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9360   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9361 
9362   if (!IsRelational && LHSIsNull != RHSIsNull) {
9363     bool IsEquality = Opc == BO_EQ;
9364     if (RHSIsNull)
9365       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9366                                    RHS.get()->getSourceRange());
9367     else
9368       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9369                                    LHS.get()->getSourceRange());
9370   }
9371 
9372   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9373       (RHSType->isIntegerType() && !RHSIsNull)) {
9374     // Skip normal pointer conversion checks in this case; we have better
9375     // diagnostics for this below.
9376   } else if (getLangOpts().CPlusPlus) {
9377     // Equality comparison of a function pointer to a void pointer is invalid,
9378     // but we allow it as an extension.
9379     // FIXME: If we really want to allow this, should it be part of composite
9380     // pointer type computation so it works in conditionals too?
9381     if (!IsRelational &&
9382         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9383          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9384       // This is a gcc extension compatibility comparison.
9385       // In a SFINAE context, we treat this as a hard error to maintain
9386       // conformance with the C++ standard.
9387       diagnoseFunctionPointerToVoidComparison(
9388           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9389 
9390       if (isSFINAEContext())
9391         return QualType();
9392 
9393       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9394       return ResultTy;
9395     }
9396 
9397     // C++ [expr.eq]p2:
9398     //   If at least one operand is a pointer [...] bring them to their
9399     //   composite pointer type.
9400     // C++ [expr.rel]p2:
9401     //   If both operands are pointers, [...] bring them to their composite
9402     //   pointer type.
9403     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9404         (IsRelational ? 2 : 1)) {
9405       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9406         return QualType();
9407       else
9408         return ResultTy;
9409     }
9410   } else if (LHSType->isPointerType() &&
9411              RHSType->isPointerType()) { // C99 6.5.8p2
9412     // All of the following pointer-related warnings are GCC extensions, except
9413     // when handling null pointer constants.
9414     QualType LCanPointeeTy =
9415       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9416     QualType RCanPointeeTy =
9417       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9418 
9419     // C99 6.5.9p2 and C99 6.5.8p2
9420     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9421                                    RCanPointeeTy.getUnqualifiedType())) {
9422       // Valid unless a relational comparison of function pointers
9423       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9424         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9425           << LHSType << RHSType << LHS.get()->getSourceRange()
9426           << RHS.get()->getSourceRange();
9427       }
9428     } else if (!IsRelational &&
9429                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9430       // Valid unless comparison between non-null pointer and function pointer
9431       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9432           && !LHSIsNull && !RHSIsNull)
9433         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9434                                                 /*isError*/false);
9435     } else {
9436       // Invalid
9437       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9438     }
9439     if (LCanPointeeTy != RCanPointeeTy) {
9440       // Treat NULL constant as a special case in OpenCL.
9441       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9442         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9443         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9444           Diag(Loc,
9445                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9446               << LHSType << RHSType << 0 /* comparison */
9447               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9448         }
9449       }
9450       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9451       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9452       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9453                                                : CK_BitCast;
9454       if (LHSIsNull && !RHSIsNull)
9455         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9456       else
9457         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9458     }
9459     return ResultTy;
9460   }
9461 
9462   if (getLangOpts().CPlusPlus) {
9463     // C++ [expr.eq]p4:
9464     //   Two operands of type std::nullptr_t or one operand of type
9465     //   std::nullptr_t and the other a null pointer constant compare equal.
9466     if (!IsRelational && LHSIsNull && RHSIsNull) {
9467       if (LHSType->isNullPtrType()) {
9468         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9469         return ResultTy;
9470       }
9471       if (RHSType->isNullPtrType()) {
9472         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9473         return ResultTy;
9474       }
9475     }
9476 
9477     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9478     // These aren't covered by the composite pointer type rules.
9479     if (!IsRelational && RHSType->isNullPtrType() &&
9480         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9481       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9482       return ResultTy;
9483     }
9484     if (!IsRelational && LHSType->isNullPtrType() &&
9485         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9486       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9487       return ResultTy;
9488     }
9489 
9490     if (IsRelational &&
9491         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9492          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9493       // HACK: Relational comparison of nullptr_t against a pointer type is
9494       // invalid per DR583, but we allow it within std::less<> and friends,
9495       // since otherwise common uses of it break.
9496       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9497       // friends to have std::nullptr_t overload candidates.
9498       DeclContext *DC = CurContext;
9499       if (isa<FunctionDecl>(DC))
9500         DC = DC->getParent();
9501       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9502         if (CTSD->isInStdNamespace() &&
9503             llvm::StringSwitch<bool>(CTSD->getName())
9504                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9505                 .Default(false)) {
9506           if (RHSType->isNullPtrType())
9507             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9508           else
9509             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9510           return ResultTy;
9511         }
9512       }
9513     }
9514 
9515     // C++ [expr.eq]p2:
9516     //   If at least one operand is a pointer to member, [...] bring them to
9517     //   their composite pointer type.
9518     if (!IsRelational &&
9519         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9520       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9521         return QualType();
9522       else
9523         return ResultTy;
9524     }
9525 
9526     // Handle scoped enumeration types specifically, since they don't promote
9527     // to integers.
9528     if (LHS.get()->getType()->isEnumeralType() &&
9529         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9530                                        RHS.get()->getType()))
9531       return ResultTy;
9532   }
9533 
9534   // Handle block pointer types.
9535   if (!IsRelational && LHSType->isBlockPointerType() &&
9536       RHSType->isBlockPointerType()) {
9537     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9538     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9539 
9540     if (!LHSIsNull && !RHSIsNull &&
9541         !Context.typesAreCompatible(lpointee, rpointee)) {
9542       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9543         << LHSType << RHSType << LHS.get()->getSourceRange()
9544         << RHS.get()->getSourceRange();
9545     }
9546     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9547     return ResultTy;
9548   }
9549 
9550   // Allow block pointers to be compared with null pointer constants.
9551   if (!IsRelational
9552       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9553           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9554     if (!LHSIsNull && !RHSIsNull) {
9555       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9556              ->getPointeeType()->isVoidType())
9557             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9558                 ->getPointeeType()->isVoidType())))
9559         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9560           << LHSType << RHSType << LHS.get()->getSourceRange()
9561           << RHS.get()->getSourceRange();
9562     }
9563     if (LHSIsNull && !RHSIsNull)
9564       LHS = ImpCastExprToType(LHS.get(), RHSType,
9565                               RHSType->isPointerType() ? CK_BitCast
9566                                 : CK_AnyPointerToBlockPointerCast);
9567     else
9568       RHS = ImpCastExprToType(RHS.get(), LHSType,
9569                               LHSType->isPointerType() ? CK_BitCast
9570                                 : CK_AnyPointerToBlockPointerCast);
9571     return ResultTy;
9572   }
9573 
9574   if (LHSType->isObjCObjectPointerType() ||
9575       RHSType->isObjCObjectPointerType()) {
9576     const PointerType *LPT = LHSType->getAs<PointerType>();
9577     const PointerType *RPT = RHSType->getAs<PointerType>();
9578     if (LPT || RPT) {
9579       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9580       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9581 
9582       if (!LPtrToVoid && !RPtrToVoid &&
9583           !Context.typesAreCompatible(LHSType, RHSType)) {
9584         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9585                                           /*isError*/false);
9586       }
9587       if (LHSIsNull && !RHSIsNull) {
9588         Expr *E = LHS.get();
9589         if (getLangOpts().ObjCAutoRefCount)
9590           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9591         LHS = ImpCastExprToType(E, RHSType,
9592                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9593       }
9594       else {
9595         Expr *E = RHS.get();
9596         if (getLangOpts().ObjCAutoRefCount)
9597           CheckObjCARCConversion(SourceRange(), LHSType, E,
9598                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9599                                  /*DiagnoseCFAudited=*/false, Opc);
9600         RHS = ImpCastExprToType(E, LHSType,
9601                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9602       }
9603       return ResultTy;
9604     }
9605     if (LHSType->isObjCObjectPointerType() &&
9606         RHSType->isObjCObjectPointerType()) {
9607       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9608         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9609                                           /*isError*/false);
9610       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9611         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9612 
9613       if (LHSIsNull && !RHSIsNull)
9614         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9615       else
9616         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9617       return ResultTy;
9618     }
9619   }
9620   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9621       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9622     unsigned DiagID = 0;
9623     bool isError = false;
9624     if (LangOpts.DebuggerSupport) {
9625       // Under a debugger, allow the comparison of pointers to integers,
9626       // since users tend to want to compare addresses.
9627     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9628                (RHSIsNull && RHSType->isIntegerType())) {
9629       if (IsRelational) {
9630         isError = getLangOpts().CPlusPlus;
9631         DiagID =
9632           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9633                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9634       }
9635     } else if (getLangOpts().CPlusPlus) {
9636       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9637       isError = true;
9638     } else if (IsRelational)
9639       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9640     else
9641       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9642 
9643     if (DiagID) {
9644       Diag(Loc, DiagID)
9645         << LHSType << RHSType << LHS.get()->getSourceRange()
9646         << RHS.get()->getSourceRange();
9647       if (isError)
9648         return QualType();
9649     }
9650 
9651     if (LHSType->isIntegerType())
9652       LHS = ImpCastExprToType(LHS.get(), RHSType,
9653                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9654     else
9655       RHS = ImpCastExprToType(RHS.get(), LHSType,
9656                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9657     return ResultTy;
9658   }
9659 
9660   // Handle block pointers.
9661   if (!IsRelational && RHSIsNull
9662       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9663     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9664     return ResultTy;
9665   }
9666   if (!IsRelational && LHSIsNull
9667       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9668     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9669     return ResultTy;
9670   }
9671 
9672   if (getLangOpts().OpenCLVersion >= 200) {
9673     if (LHSIsNull && RHSType->isQueueT()) {
9674       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9675       return ResultTy;
9676     }
9677 
9678     if (LHSType->isQueueT() && RHSIsNull) {
9679       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9680       return ResultTy;
9681     }
9682   }
9683 
9684   return InvalidOperands(Loc, LHS, RHS);
9685 }
9686 
9687 
9688 // Return a signed type that is of identical size and number of elements.
9689 // For floating point vectors, return an integer type of identical size
9690 // and number of elements.
9691 QualType Sema::GetSignedVectorType(QualType V) {
9692   const VectorType *VTy = V->getAs<VectorType>();
9693   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9694   if (TypeSize == Context.getTypeSize(Context.CharTy))
9695     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9696   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9697     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9698   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9699     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9700   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9701     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9702   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9703          "Unhandled vector element size in vector compare");
9704   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9705 }
9706 
9707 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9708 /// operates on extended vector types.  Instead of producing an IntTy result,
9709 /// like a scalar comparison, a vector comparison produces a vector of integer
9710 /// types.
9711 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9712                                           SourceLocation Loc,
9713                                           bool IsRelational) {
9714   // Check to make sure we're operating on vectors of the same type and width,
9715   // Allowing one side to be a scalar of element type.
9716   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9717                               /*AllowBothBool*/true,
9718                               /*AllowBoolConversions*/getLangOpts().ZVector);
9719   if (vType.isNull())
9720     return vType;
9721 
9722   QualType LHSType = LHS.get()->getType();
9723 
9724   // If AltiVec, the comparison results in a numeric type, i.e.
9725   // bool for C++, int for C
9726   if (getLangOpts().AltiVec &&
9727       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9728     return Context.getLogicalOperationType();
9729 
9730   // For non-floating point types, check for self-comparisons of the form
9731   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9732   // often indicate logic errors in the program.
9733   if (!LHSType->hasFloatingRepresentation() &&
9734       ActiveTemplateInstantiations.empty()) {
9735     if (DeclRefExpr* DRL
9736           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9737       if (DeclRefExpr* DRR
9738             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9739         if (DRL->getDecl() == DRR->getDecl())
9740           DiagRuntimeBehavior(Loc, nullptr,
9741                               PDiag(diag::warn_comparison_always)
9742                                 << 0 // self-
9743                                 << 2 // "a constant"
9744                               );
9745   }
9746 
9747   // Check for comparisons of floating point operands using != and ==.
9748   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9749     assert (RHS.get()->getType()->hasFloatingRepresentation());
9750     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9751   }
9752 
9753   // Return a signed type for the vector.
9754   return GetSignedVectorType(vType);
9755 }
9756 
9757 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9758                                           SourceLocation Loc) {
9759   // Ensure that either both operands are of the same vector type, or
9760   // one operand is of a vector type and the other is of its element type.
9761   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9762                                        /*AllowBothBool*/true,
9763                                        /*AllowBoolConversions*/false);
9764   if (vType.isNull())
9765     return InvalidOperands(Loc, LHS, RHS);
9766   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9767       vType->hasFloatingRepresentation())
9768     return InvalidOperands(Loc, LHS, RHS);
9769 
9770   return GetSignedVectorType(LHS.get()->getType());
9771 }
9772 
9773 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9774                                            SourceLocation Loc,
9775                                            BinaryOperatorKind Opc) {
9776   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9777 
9778   bool IsCompAssign =
9779       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9780 
9781   if (LHS.get()->getType()->isVectorType() ||
9782       RHS.get()->getType()->isVectorType()) {
9783     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9784         RHS.get()->getType()->hasIntegerRepresentation())
9785       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9786                         /*AllowBothBool*/true,
9787                         /*AllowBoolConversions*/getLangOpts().ZVector);
9788     return InvalidOperands(Loc, LHS, RHS);
9789   }
9790 
9791   if (Opc == BO_And)
9792     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9793 
9794   ExprResult LHSResult = LHS, RHSResult = RHS;
9795   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9796                                                  IsCompAssign);
9797   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9798     return QualType();
9799   LHS = LHSResult.get();
9800   RHS = RHSResult.get();
9801 
9802   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9803     return compType;
9804   return InvalidOperands(Loc, LHS, RHS);
9805 }
9806 
9807 // C99 6.5.[13,14]
9808 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9809                                            SourceLocation Loc,
9810                                            BinaryOperatorKind Opc) {
9811   // Check vector operands differently.
9812   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9813     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9814 
9815   // Diagnose cases where the user write a logical and/or but probably meant a
9816   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9817   // is a constant.
9818   if (LHS.get()->getType()->isIntegerType() &&
9819       !LHS.get()->getType()->isBooleanType() &&
9820       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9821       // Don't warn in macros or template instantiations.
9822       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9823     // If the RHS can be constant folded, and if it constant folds to something
9824     // that isn't 0 or 1 (which indicate a potential logical operation that
9825     // happened to fold to true/false) then warn.
9826     // Parens on the RHS are ignored.
9827     llvm::APSInt Result;
9828     if (RHS.get()->EvaluateAsInt(Result, Context))
9829       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9830            !RHS.get()->getExprLoc().isMacroID()) ||
9831           (Result != 0 && Result != 1)) {
9832         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9833           << RHS.get()->getSourceRange()
9834           << (Opc == BO_LAnd ? "&&" : "||");
9835         // Suggest replacing the logical operator with the bitwise version
9836         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9837             << (Opc == BO_LAnd ? "&" : "|")
9838             << FixItHint::CreateReplacement(SourceRange(
9839                                                  Loc, getLocForEndOfToken(Loc)),
9840                                             Opc == BO_LAnd ? "&" : "|");
9841         if (Opc == BO_LAnd)
9842           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9843           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9844               << FixItHint::CreateRemoval(
9845                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9846                               RHS.get()->getLocEnd()));
9847       }
9848   }
9849 
9850   if (!Context.getLangOpts().CPlusPlus) {
9851     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9852     // not operate on the built-in scalar and vector float types.
9853     if (Context.getLangOpts().OpenCL &&
9854         Context.getLangOpts().OpenCLVersion < 120) {
9855       if (LHS.get()->getType()->isFloatingType() ||
9856           RHS.get()->getType()->isFloatingType())
9857         return InvalidOperands(Loc, LHS, RHS);
9858     }
9859 
9860     LHS = UsualUnaryConversions(LHS.get());
9861     if (LHS.isInvalid())
9862       return QualType();
9863 
9864     RHS = UsualUnaryConversions(RHS.get());
9865     if (RHS.isInvalid())
9866       return QualType();
9867 
9868     if (!LHS.get()->getType()->isScalarType() ||
9869         !RHS.get()->getType()->isScalarType())
9870       return InvalidOperands(Loc, LHS, RHS);
9871 
9872     return Context.IntTy;
9873   }
9874 
9875   // The following is safe because we only use this method for
9876   // non-overloadable operands.
9877 
9878   // C++ [expr.log.and]p1
9879   // C++ [expr.log.or]p1
9880   // The operands are both contextually converted to type bool.
9881   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9882   if (LHSRes.isInvalid())
9883     return InvalidOperands(Loc, LHS, RHS);
9884   LHS = LHSRes;
9885 
9886   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9887   if (RHSRes.isInvalid())
9888     return InvalidOperands(Loc, LHS, RHS);
9889   RHS = RHSRes;
9890 
9891   // C++ [expr.log.and]p2
9892   // C++ [expr.log.or]p2
9893   // The result is a bool.
9894   return Context.BoolTy;
9895 }
9896 
9897 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9898   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9899   if (!ME) return false;
9900   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9901   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9902       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9903   if (!Base) return false;
9904   return Base->getMethodDecl() != nullptr;
9905 }
9906 
9907 /// Is the given expression (which must be 'const') a reference to a
9908 /// variable which was originally non-const, but which has become
9909 /// 'const' due to being captured within a block?
9910 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9911 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9912   assert(E->isLValue() && E->getType().isConstQualified());
9913   E = E->IgnoreParens();
9914 
9915   // Must be a reference to a declaration from an enclosing scope.
9916   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9917   if (!DRE) return NCCK_None;
9918   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9919 
9920   // The declaration must be a variable which is not declared 'const'.
9921   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9922   if (!var) return NCCK_None;
9923   if (var->getType().isConstQualified()) return NCCK_None;
9924   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9925 
9926   // Decide whether the first capture was for a block or a lambda.
9927   DeclContext *DC = S.CurContext, *Prev = nullptr;
9928   // Decide whether the first capture was for a block or a lambda.
9929   while (DC) {
9930     // For init-capture, it is possible that the variable belongs to the
9931     // template pattern of the current context.
9932     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9933       if (var->isInitCapture() &&
9934           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9935         break;
9936     if (DC == var->getDeclContext())
9937       break;
9938     Prev = DC;
9939     DC = DC->getParent();
9940   }
9941   // Unless we have an init-capture, we've gone one step too far.
9942   if (!var->isInitCapture())
9943     DC = Prev;
9944   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9945 }
9946 
9947 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9948   Ty = Ty.getNonReferenceType();
9949   if (IsDereference && Ty->isPointerType())
9950     Ty = Ty->getPointeeType();
9951   return !Ty.isConstQualified();
9952 }
9953 
9954 /// Emit the "read-only variable not assignable" error and print notes to give
9955 /// more information about why the variable is not assignable, such as pointing
9956 /// to the declaration of a const variable, showing that a method is const, or
9957 /// that the function is returning a const reference.
9958 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9959                                     SourceLocation Loc) {
9960   // Update err_typecheck_assign_const and note_typecheck_assign_const
9961   // when this enum is changed.
9962   enum {
9963     ConstFunction,
9964     ConstVariable,
9965     ConstMember,
9966     ConstMethod,
9967     ConstUnknown,  // Keep as last element
9968   };
9969 
9970   SourceRange ExprRange = E->getSourceRange();
9971 
9972   // Only emit one error on the first const found.  All other consts will emit
9973   // a note to the error.
9974   bool DiagnosticEmitted = false;
9975 
9976   // Track if the current expression is the result of a dereference, and if the
9977   // next checked expression is the result of a dereference.
9978   bool IsDereference = false;
9979   bool NextIsDereference = false;
9980 
9981   // Loop to process MemberExpr chains.
9982   while (true) {
9983     IsDereference = NextIsDereference;
9984 
9985     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9986     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9987       NextIsDereference = ME->isArrow();
9988       const ValueDecl *VD = ME->getMemberDecl();
9989       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9990         // Mutable fields can be modified even if the class is const.
9991         if (Field->isMutable()) {
9992           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9993           break;
9994         }
9995 
9996         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9997           if (!DiagnosticEmitted) {
9998             S.Diag(Loc, diag::err_typecheck_assign_const)
9999                 << ExprRange << ConstMember << false /*static*/ << Field
10000                 << Field->getType();
10001             DiagnosticEmitted = true;
10002           }
10003           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10004               << ConstMember << false /*static*/ << Field << Field->getType()
10005               << Field->getSourceRange();
10006         }
10007         E = ME->getBase();
10008         continue;
10009       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10010         if (VDecl->getType().isConstQualified()) {
10011           if (!DiagnosticEmitted) {
10012             S.Diag(Loc, diag::err_typecheck_assign_const)
10013                 << ExprRange << ConstMember << true /*static*/ << VDecl
10014                 << VDecl->getType();
10015             DiagnosticEmitted = true;
10016           }
10017           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10018               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10019               << VDecl->getSourceRange();
10020         }
10021         // Static fields do not inherit constness from parents.
10022         break;
10023       }
10024       break;
10025     } // End MemberExpr
10026     break;
10027   }
10028 
10029   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10030     // Function calls
10031     const FunctionDecl *FD = CE->getDirectCallee();
10032     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10033       if (!DiagnosticEmitted) {
10034         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10035                                                       << ConstFunction << FD;
10036         DiagnosticEmitted = true;
10037       }
10038       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10039              diag::note_typecheck_assign_const)
10040           << ConstFunction << FD << FD->getReturnType()
10041           << FD->getReturnTypeSourceRange();
10042     }
10043   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10044     // Point to variable declaration.
10045     if (const ValueDecl *VD = DRE->getDecl()) {
10046       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10047         if (!DiagnosticEmitted) {
10048           S.Diag(Loc, diag::err_typecheck_assign_const)
10049               << ExprRange << ConstVariable << VD << VD->getType();
10050           DiagnosticEmitted = true;
10051         }
10052         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10053             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10054       }
10055     }
10056   } else if (isa<CXXThisExpr>(E)) {
10057     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10058       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10059         if (MD->isConst()) {
10060           if (!DiagnosticEmitted) {
10061             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10062                                                           << ConstMethod << MD;
10063             DiagnosticEmitted = true;
10064           }
10065           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10066               << ConstMethod << MD << MD->getSourceRange();
10067         }
10068       }
10069     }
10070   }
10071 
10072   if (DiagnosticEmitted)
10073     return;
10074 
10075   // Can't determine a more specific message, so display the generic error.
10076   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10077 }
10078 
10079 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10080 /// emit an error and return true.  If so, return false.
10081 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10082   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10083 
10084   S.CheckShadowingDeclModification(E, Loc);
10085 
10086   SourceLocation OrigLoc = Loc;
10087   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10088                                                               &Loc);
10089   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10090     IsLV = Expr::MLV_InvalidMessageExpression;
10091   if (IsLV == Expr::MLV_Valid)
10092     return false;
10093 
10094   unsigned DiagID = 0;
10095   bool NeedType = false;
10096   switch (IsLV) { // C99 6.5.16p2
10097   case Expr::MLV_ConstQualified:
10098     // Use a specialized diagnostic when we're assigning to an object
10099     // from an enclosing function or block.
10100     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10101       if (NCCK == NCCK_Block)
10102         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10103       else
10104         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10105       break;
10106     }
10107 
10108     // In ARC, use some specialized diagnostics for occasions where we
10109     // infer 'const'.  These are always pseudo-strong variables.
10110     if (S.getLangOpts().ObjCAutoRefCount) {
10111       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10112       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10113         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10114 
10115         // Use the normal diagnostic if it's pseudo-__strong but the
10116         // user actually wrote 'const'.
10117         if (var->isARCPseudoStrong() &&
10118             (!var->getTypeSourceInfo() ||
10119              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10120           // There are two pseudo-strong cases:
10121           //  - self
10122           ObjCMethodDecl *method = S.getCurMethodDecl();
10123           if (method && var == method->getSelfDecl())
10124             DiagID = method->isClassMethod()
10125               ? diag::err_typecheck_arc_assign_self_class_method
10126               : diag::err_typecheck_arc_assign_self;
10127 
10128           //  - fast enumeration variables
10129           else
10130             DiagID = diag::err_typecheck_arr_assign_enumeration;
10131 
10132           SourceRange Assign;
10133           if (Loc != OrigLoc)
10134             Assign = SourceRange(OrigLoc, OrigLoc);
10135           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10136           // We need to preserve the AST regardless, so migration tool
10137           // can do its job.
10138           return false;
10139         }
10140       }
10141     }
10142 
10143     // If none of the special cases above are triggered, then this is a
10144     // simple const assignment.
10145     if (DiagID == 0) {
10146       DiagnoseConstAssignment(S, E, Loc);
10147       return true;
10148     }
10149 
10150     break;
10151   case Expr::MLV_ConstAddrSpace:
10152     DiagnoseConstAssignment(S, E, Loc);
10153     return true;
10154   case Expr::MLV_ArrayType:
10155   case Expr::MLV_ArrayTemporary:
10156     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10157     NeedType = true;
10158     break;
10159   case Expr::MLV_NotObjectType:
10160     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10161     NeedType = true;
10162     break;
10163   case Expr::MLV_LValueCast:
10164     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10165     break;
10166   case Expr::MLV_Valid:
10167     llvm_unreachable("did not take early return for MLV_Valid");
10168   case Expr::MLV_InvalidExpression:
10169   case Expr::MLV_MemberFunction:
10170   case Expr::MLV_ClassTemporary:
10171     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10172     break;
10173   case Expr::MLV_IncompleteType:
10174   case Expr::MLV_IncompleteVoidType:
10175     return S.RequireCompleteType(Loc, E->getType(),
10176              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10177   case Expr::MLV_DuplicateVectorComponents:
10178     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10179     break;
10180   case Expr::MLV_NoSetterProperty:
10181     llvm_unreachable("readonly properties should be processed differently");
10182   case Expr::MLV_InvalidMessageExpression:
10183     DiagID = diag::err_readonly_message_assignment;
10184     break;
10185   case Expr::MLV_SubObjCPropertySetting:
10186     DiagID = diag::err_no_subobject_property_setting;
10187     break;
10188   }
10189 
10190   SourceRange Assign;
10191   if (Loc != OrigLoc)
10192     Assign = SourceRange(OrigLoc, OrigLoc);
10193   if (NeedType)
10194     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10195   else
10196     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10197   return true;
10198 }
10199 
10200 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10201                                          SourceLocation Loc,
10202                                          Sema &Sema) {
10203   // C / C++ fields
10204   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10205   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10206   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10207     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10208       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10209   }
10210 
10211   // Objective-C instance variables
10212   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10213   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10214   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10215     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10216     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10217     if (RL && RR && RL->getDecl() == RR->getDecl())
10218       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10219   }
10220 }
10221 
10222 // C99 6.5.16.1
10223 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10224                                        SourceLocation Loc,
10225                                        QualType CompoundType) {
10226   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10227 
10228   // Verify that LHS is a modifiable lvalue, and emit error if not.
10229   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10230     return QualType();
10231 
10232   QualType LHSType = LHSExpr->getType();
10233   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10234                                              CompoundType;
10235   // OpenCL v1.2 s6.1.1.1 p2:
10236   // The half data type can only be used to declare a pointer to a buffer that
10237   // contains half values
10238   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10239     LHSType->isHalfType()) {
10240     Diag(Loc, diag::err_opencl_half_load_store) << 1
10241         << LHSType.getUnqualifiedType();
10242     return QualType();
10243   }
10244 
10245   AssignConvertType ConvTy;
10246   if (CompoundType.isNull()) {
10247     Expr *RHSCheck = RHS.get();
10248 
10249     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10250 
10251     QualType LHSTy(LHSType);
10252     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10253     if (RHS.isInvalid())
10254       return QualType();
10255     // Special case of NSObject attributes on c-style pointer types.
10256     if (ConvTy == IncompatiblePointer &&
10257         ((Context.isObjCNSObjectType(LHSType) &&
10258           RHSType->isObjCObjectPointerType()) ||
10259          (Context.isObjCNSObjectType(RHSType) &&
10260           LHSType->isObjCObjectPointerType())))
10261       ConvTy = Compatible;
10262 
10263     if (ConvTy == Compatible &&
10264         LHSType->isObjCObjectType())
10265         Diag(Loc, diag::err_objc_object_assignment)
10266           << LHSType;
10267 
10268     // If the RHS is a unary plus or minus, check to see if they = and + are
10269     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10270     // instead of "x += 4".
10271     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10272       RHSCheck = ICE->getSubExpr();
10273     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10274       if ((UO->getOpcode() == UO_Plus ||
10275            UO->getOpcode() == UO_Minus) &&
10276           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10277           // Only if the two operators are exactly adjacent.
10278           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10279           // And there is a space or other character before the subexpr of the
10280           // unary +/-.  We don't want to warn on "x=-1".
10281           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10282           UO->getSubExpr()->getLocStart().isFileID()) {
10283         Diag(Loc, diag::warn_not_compound_assign)
10284           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10285           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10286       }
10287     }
10288 
10289     if (ConvTy == Compatible) {
10290       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10291         // Warn about retain cycles where a block captures the LHS, but
10292         // not if the LHS is a simple variable into which the block is
10293         // being stored...unless that variable can be captured by reference!
10294         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10295         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10296         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10297           checkRetainCycles(LHSExpr, RHS.get());
10298 
10299         // It is safe to assign a weak reference into a strong variable.
10300         // Although this code can still have problems:
10301         //   id x = self.weakProp;
10302         //   id y = self.weakProp;
10303         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10304         // paths through the function. This should be revisited if
10305         // -Wrepeated-use-of-weak is made flow-sensitive.
10306         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10307                              RHS.get()->getLocStart()))
10308           getCurFunction()->markSafeWeakUse(RHS.get());
10309 
10310       } else if (getLangOpts().ObjCAutoRefCount) {
10311         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10312       }
10313     }
10314   } else {
10315     // Compound assignment "x += y"
10316     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10317   }
10318 
10319   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10320                                RHS.get(), AA_Assigning))
10321     return QualType();
10322 
10323   CheckForNullPointerDereference(*this, LHSExpr);
10324 
10325   // C99 6.5.16p3: The type of an assignment expression is the type of the
10326   // left operand unless the left operand has qualified type, in which case
10327   // it is the unqualified version of the type of the left operand.
10328   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10329   // is converted to the type of the assignment expression (above).
10330   // C++ 5.17p1: the type of the assignment expression is that of its left
10331   // operand.
10332   return (getLangOpts().CPlusPlus
10333           ? LHSType : LHSType.getUnqualifiedType());
10334 }
10335 
10336 // Only ignore explicit casts to void.
10337 static bool IgnoreCommaOperand(const Expr *E) {
10338   E = E->IgnoreParens();
10339 
10340   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10341     if (CE->getCastKind() == CK_ToVoid) {
10342       return true;
10343     }
10344   }
10345 
10346   return false;
10347 }
10348 
10349 // Look for instances where it is likely the comma operator is confused with
10350 // another operator.  There is a whitelist of acceptable expressions for the
10351 // left hand side of the comma operator, otherwise emit a warning.
10352 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10353   // No warnings in macros
10354   if (Loc.isMacroID())
10355     return;
10356 
10357   // Don't warn in template instantiations.
10358   if (!ActiveTemplateInstantiations.empty())
10359     return;
10360 
10361   // Scope isn't fine-grained enough to whitelist the specific cases, so
10362   // instead, skip more than needed, then call back into here with the
10363   // CommaVisitor in SemaStmt.cpp.
10364   // The whitelisted locations are the initialization and increment portions
10365   // of a for loop.  The additional checks are on the condition of
10366   // if statements, do/while loops, and for loops.
10367   const unsigned ForIncrementFlags =
10368       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10369   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10370   const unsigned ScopeFlags = getCurScope()->getFlags();
10371   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10372       (ScopeFlags & ForInitFlags) == ForInitFlags)
10373     return;
10374 
10375   // If there are multiple comma operators used together, get the RHS of the
10376   // of the comma operator as the LHS.
10377   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10378     if (BO->getOpcode() != BO_Comma)
10379       break;
10380     LHS = BO->getRHS();
10381   }
10382 
10383   // Only allow some expressions on LHS to not warn.
10384   if (IgnoreCommaOperand(LHS))
10385     return;
10386 
10387   Diag(Loc, diag::warn_comma_operator);
10388   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10389       << LHS->getSourceRange()
10390       << FixItHint::CreateInsertion(LHS->getLocStart(),
10391                                     LangOpts.CPlusPlus ? "static_cast<void>("
10392                                                        : "(void)(")
10393       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10394                                     ")");
10395 }
10396 
10397 // C99 6.5.17
10398 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10399                                    SourceLocation Loc) {
10400   LHS = S.CheckPlaceholderExpr(LHS.get());
10401   RHS = S.CheckPlaceholderExpr(RHS.get());
10402   if (LHS.isInvalid() || RHS.isInvalid())
10403     return QualType();
10404 
10405   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10406   // operands, but not unary promotions.
10407   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10408 
10409   // So we treat the LHS as a ignored value, and in C++ we allow the
10410   // containing site to determine what should be done with the RHS.
10411   LHS = S.IgnoredValueConversions(LHS.get());
10412   if (LHS.isInvalid())
10413     return QualType();
10414 
10415   S.DiagnoseUnusedExprResult(LHS.get());
10416 
10417   if (!S.getLangOpts().CPlusPlus) {
10418     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10419     if (RHS.isInvalid())
10420       return QualType();
10421     if (!RHS.get()->getType()->isVoidType())
10422       S.RequireCompleteType(Loc, RHS.get()->getType(),
10423                             diag::err_incomplete_type);
10424   }
10425 
10426   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10427     S.DiagnoseCommaOperator(LHS.get(), Loc);
10428 
10429   return RHS.get()->getType();
10430 }
10431 
10432 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10433 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10434 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10435                                                ExprValueKind &VK,
10436                                                ExprObjectKind &OK,
10437                                                SourceLocation OpLoc,
10438                                                bool IsInc, bool IsPrefix) {
10439   if (Op->isTypeDependent())
10440     return S.Context.DependentTy;
10441 
10442   QualType ResType = Op->getType();
10443   // Atomic types can be used for increment / decrement where the non-atomic
10444   // versions can, so ignore the _Atomic() specifier for the purpose of
10445   // checking.
10446   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10447     ResType = ResAtomicType->getValueType();
10448 
10449   assert(!ResType.isNull() && "no type for increment/decrement expression");
10450 
10451   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10452     // Decrement of bool is not allowed.
10453     if (!IsInc) {
10454       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10455       return QualType();
10456     }
10457     // Increment of bool sets it to true, but is deprecated.
10458     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10459                                               : diag::warn_increment_bool)
10460       << Op->getSourceRange();
10461   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10462     // Error on enum increments and decrements in C++ mode
10463     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10464     return QualType();
10465   } else if (ResType->isRealType()) {
10466     // OK!
10467   } else if (ResType->isPointerType()) {
10468     // C99 6.5.2.4p2, 6.5.6p2
10469     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10470       return QualType();
10471   } else if (ResType->isObjCObjectPointerType()) {
10472     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10473     // Otherwise, we just need a complete type.
10474     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10475         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10476       return QualType();
10477   } else if (ResType->isAnyComplexType()) {
10478     // C99 does not support ++/-- on complex types, we allow as an extension.
10479     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10480       << ResType << Op->getSourceRange();
10481   } else if (ResType->isPlaceholderType()) {
10482     ExprResult PR = S.CheckPlaceholderExpr(Op);
10483     if (PR.isInvalid()) return QualType();
10484     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10485                                           IsInc, IsPrefix);
10486   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10487     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10488   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10489              (ResType->getAs<VectorType>()->getVectorKind() !=
10490               VectorType::AltiVecBool)) {
10491     // The z vector extensions allow ++ and -- for non-bool vectors.
10492   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10493             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10494     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10495   } else {
10496     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10497       << ResType << int(IsInc) << Op->getSourceRange();
10498     return QualType();
10499   }
10500   // At this point, we know we have a real, complex or pointer type.
10501   // Now make sure the operand is a modifiable lvalue.
10502   if (CheckForModifiableLvalue(Op, OpLoc, S))
10503     return QualType();
10504   // In C++, a prefix increment is the same type as the operand. Otherwise
10505   // (in C or with postfix), the increment is the unqualified type of the
10506   // operand.
10507   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10508     VK = VK_LValue;
10509     OK = Op->getObjectKind();
10510     return ResType;
10511   } else {
10512     VK = VK_RValue;
10513     return ResType.getUnqualifiedType();
10514   }
10515 }
10516 
10517 
10518 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10519 /// This routine allows us to typecheck complex/recursive expressions
10520 /// where the declaration is needed for type checking. We only need to
10521 /// handle cases when the expression references a function designator
10522 /// or is an lvalue. Here are some examples:
10523 ///  - &(x) => x
10524 ///  - &*****f => f for f a function designator.
10525 ///  - &s.xx => s
10526 ///  - &s.zz[1].yy -> s, if zz is an array
10527 ///  - *(x + 1) -> x, if x is an array
10528 ///  - &"123"[2] -> 0
10529 ///  - & __real__ x -> x
10530 static ValueDecl *getPrimaryDecl(Expr *E) {
10531   switch (E->getStmtClass()) {
10532   case Stmt::DeclRefExprClass:
10533     return cast<DeclRefExpr>(E)->getDecl();
10534   case Stmt::MemberExprClass:
10535     // If this is an arrow operator, the address is an offset from
10536     // the base's value, so the object the base refers to is
10537     // irrelevant.
10538     if (cast<MemberExpr>(E)->isArrow())
10539       return nullptr;
10540     // Otherwise, the expression refers to a part of the base
10541     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10542   case Stmt::ArraySubscriptExprClass: {
10543     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10544     // promotion of register arrays earlier.
10545     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10546     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10547       if (ICE->getSubExpr()->getType()->isArrayType())
10548         return getPrimaryDecl(ICE->getSubExpr());
10549     }
10550     return nullptr;
10551   }
10552   case Stmt::UnaryOperatorClass: {
10553     UnaryOperator *UO = cast<UnaryOperator>(E);
10554 
10555     switch(UO->getOpcode()) {
10556     case UO_Real:
10557     case UO_Imag:
10558     case UO_Extension:
10559       return getPrimaryDecl(UO->getSubExpr());
10560     default:
10561       return nullptr;
10562     }
10563   }
10564   case Stmt::ParenExprClass:
10565     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10566   case Stmt::ImplicitCastExprClass:
10567     // If the result of an implicit cast is an l-value, we care about
10568     // the sub-expression; otherwise, the result here doesn't matter.
10569     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10570   default:
10571     return nullptr;
10572   }
10573 }
10574 
10575 namespace {
10576   enum {
10577     AO_Bit_Field = 0,
10578     AO_Vector_Element = 1,
10579     AO_Property_Expansion = 2,
10580     AO_Register_Variable = 3,
10581     AO_No_Error = 4
10582   };
10583 }
10584 /// \brief Diagnose invalid operand for address of operations.
10585 ///
10586 /// \param Type The type of operand which cannot have its address taken.
10587 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10588                                          Expr *E, unsigned Type) {
10589   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10590 }
10591 
10592 /// CheckAddressOfOperand - The operand of & must be either a function
10593 /// designator or an lvalue designating an object. If it is an lvalue, the
10594 /// object cannot be declared with storage class register or be a bit field.
10595 /// Note: The usual conversions are *not* applied to the operand of the &
10596 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10597 /// In C++, the operand might be an overloaded function name, in which case
10598 /// we allow the '&' but retain the overloaded-function type.
10599 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10600   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10601     if (PTy->getKind() == BuiltinType::Overload) {
10602       Expr *E = OrigOp.get()->IgnoreParens();
10603       if (!isa<OverloadExpr>(E)) {
10604         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10605         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10606           << OrigOp.get()->getSourceRange();
10607         return QualType();
10608       }
10609 
10610       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10611       if (isa<UnresolvedMemberExpr>(Ovl))
10612         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10613           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10614             << OrigOp.get()->getSourceRange();
10615           return QualType();
10616         }
10617 
10618       return Context.OverloadTy;
10619     }
10620 
10621     if (PTy->getKind() == BuiltinType::UnknownAny)
10622       return Context.UnknownAnyTy;
10623 
10624     if (PTy->getKind() == BuiltinType::BoundMember) {
10625       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10626         << OrigOp.get()->getSourceRange();
10627       return QualType();
10628     }
10629 
10630     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10631     if (OrigOp.isInvalid()) return QualType();
10632   }
10633 
10634   if (OrigOp.get()->isTypeDependent())
10635     return Context.DependentTy;
10636 
10637   assert(!OrigOp.get()->getType()->isPlaceholderType());
10638 
10639   // Make sure to ignore parentheses in subsequent checks
10640   Expr *op = OrigOp.get()->IgnoreParens();
10641 
10642   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10643   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10644     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10645     return QualType();
10646   }
10647 
10648   if (getLangOpts().C99) {
10649     // Implement C99-only parts of addressof rules.
10650     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10651       if (uOp->getOpcode() == UO_Deref)
10652         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10653         // (assuming the deref expression is valid).
10654         return uOp->getSubExpr()->getType();
10655     }
10656     // Technically, there should be a check for array subscript
10657     // expressions here, but the result of one is always an lvalue anyway.
10658   }
10659   ValueDecl *dcl = getPrimaryDecl(op);
10660 
10661   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10662     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10663                                            op->getLocStart()))
10664       return QualType();
10665 
10666   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10667   unsigned AddressOfError = AO_No_Error;
10668 
10669   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10670     bool sfinae = (bool)isSFINAEContext();
10671     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10672                                   : diag::ext_typecheck_addrof_temporary)
10673       << op->getType() << op->getSourceRange();
10674     if (sfinae)
10675       return QualType();
10676     // Materialize the temporary as an lvalue so that we can take its address.
10677     OrigOp = op =
10678         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10679   } else if (isa<ObjCSelectorExpr>(op)) {
10680     return Context.getPointerType(op->getType());
10681   } else if (lval == Expr::LV_MemberFunction) {
10682     // If it's an instance method, make a member pointer.
10683     // The expression must have exactly the form &A::foo.
10684 
10685     // If the underlying expression isn't a decl ref, give up.
10686     if (!isa<DeclRefExpr>(op)) {
10687       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10688         << OrigOp.get()->getSourceRange();
10689       return QualType();
10690     }
10691     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10692     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10693 
10694     // The id-expression was parenthesized.
10695     if (OrigOp.get() != DRE) {
10696       Diag(OpLoc, diag::err_parens_pointer_member_function)
10697         << OrigOp.get()->getSourceRange();
10698 
10699     // The method was named without a qualifier.
10700     } else if (!DRE->getQualifier()) {
10701       if (MD->getParent()->getName().empty())
10702         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10703           << op->getSourceRange();
10704       else {
10705         SmallString<32> Str;
10706         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10707         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10708           << op->getSourceRange()
10709           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10710       }
10711     }
10712 
10713     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10714     if (isa<CXXDestructorDecl>(MD))
10715       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10716 
10717     QualType MPTy = Context.getMemberPointerType(
10718         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10719     // Under the MS ABI, lock down the inheritance model now.
10720     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10721       (void)isCompleteType(OpLoc, MPTy);
10722     return MPTy;
10723   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10724     // C99 6.5.3.2p1
10725     // The operand must be either an l-value or a function designator
10726     if (!op->getType()->isFunctionType()) {
10727       // Use a special diagnostic for loads from property references.
10728       if (isa<PseudoObjectExpr>(op)) {
10729         AddressOfError = AO_Property_Expansion;
10730       } else {
10731         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10732           << op->getType() << op->getSourceRange();
10733         return QualType();
10734       }
10735     }
10736   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10737     // The operand cannot be a bit-field
10738     AddressOfError = AO_Bit_Field;
10739   } else if (op->getObjectKind() == OK_VectorComponent) {
10740     // The operand cannot be an element of a vector
10741     AddressOfError = AO_Vector_Element;
10742   } else if (dcl) { // C99 6.5.3.2p1
10743     // We have an lvalue with a decl. Make sure the decl is not declared
10744     // with the register storage-class specifier.
10745     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10746       // in C++ it is not error to take address of a register
10747       // variable (c++03 7.1.1P3)
10748       if (vd->getStorageClass() == SC_Register &&
10749           !getLangOpts().CPlusPlus) {
10750         AddressOfError = AO_Register_Variable;
10751       }
10752     } else if (isa<MSPropertyDecl>(dcl)) {
10753       AddressOfError = AO_Property_Expansion;
10754     } else if (isa<FunctionTemplateDecl>(dcl)) {
10755       return Context.OverloadTy;
10756     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10757       // Okay: we can take the address of a field.
10758       // Could be a pointer to member, though, if there is an explicit
10759       // scope qualifier for the class.
10760       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10761         DeclContext *Ctx = dcl->getDeclContext();
10762         if (Ctx && Ctx->isRecord()) {
10763           if (dcl->getType()->isReferenceType()) {
10764             Diag(OpLoc,
10765                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10766               << dcl->getDeclName() << dcl->getType();
10767             return QualType();
10768           }
10769 
10770           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10771             Ctx = Ctx->getParent();
10772 
10773           QualType MPTy = Context.getMemberPointerType(
10774               op->getType(),
10775               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10776           // Under the MS ABI, lock down the inheritance model now.
10777           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10778             (void)isCompleteType(OpLoc, MPTy);
10779           return MPTy;
10780         }
10781       }
10782     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10783                !isa<BindingDecl>(dcl))
10784       llvm_unreachable("Unknown/unexpected decl type");
10785   }
10786 
10787   if (AddressOfError != AO_No_Error) {
10788     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10789     return QualType();
10790   }
10791 
10792   if (lval == Expr::LV_IncompleteVoidType) {
10793     // Taking the address of a void variable is technically illegal, but we
10794     // allow it in cases which are otherwise valid.
10795     // Example: "extern void x; void* y = &x;".
10796     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10797   }
10798 
10799   // If the operand has type "type", the result has type "pointer to type".
10800   if (op->getType()->isObjCObjectType())
10801     return Context.getObjCObjectPointerType(op->getType());
10802 
10803   CheckAddressOfPackedMember(op);
10804 
10805   return Context.getPointerType(op->getType());
10806 }
10807 
10808 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10809   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10810   if (!DRE)
10811     return;
10812   const Decl *D = DRE->getDecl();
10813   if (!D)
10814     return;
10815   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10816   if (!Param)
10817     return;
10818   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10819     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10820       return;
10821   if (FunctionScopeInfo *FD = S.getCurFunction())
10822     if (!FD->ModifiedNonNullParams.count(Param))
10823       FD->ModifiedNonNullParams.insert(Param);
10824 }
10825 
10826 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10827 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10828                                         SourceLocation OpLoc) {
10829   if (Op->isTypeDependent())
10830     return S.Context.DependentTy;
10831 
10832   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10833   if (ConvResult.isInvalid())
10834     return QualType();
10835   Op = ConvResult.get();
10836   QualType OpTy = Op->getType();
10837   QualType Result;
10838 
10839   if (isa<CXXReinterpretCastExpr>(Op)) {
10840     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10841     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10842                                      Op->getSourceRange());
10843   }
10844 
10845   if (const PointerType *PT = OpTy->getAs<PointerType>())
10846   {
10847     Result = PT->getPointeeType();
10848   }
10849   else if (const ObjCObjectPointerType *OPT =
10850              OpTy->getAs<ObjCObjectPointerType>())
10851     Result = OPT->getPointeeType();
10852   else {
10853     ExprResult PR = S.CheckPlaceholderExpr(Op);
10854     if (PR.isInvalid()) return QualType();
10855     if (PR.get() != Op)
10856       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10857   }
10858 
10859   if (Result.isNull()) {
10860     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10861       << OpTy << Op->getSourceRange();
10862     return QualType();
10863   }
10864 
10865   // Note that per both C89 and C99, indirection is always legal, even if Result
10866   // is an incomplete type or void.  It would be possible to warn about
10867   // dereferencing a void pointer, but it's completely well-defined, and such a
10868   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10869   // for pointers to 'void' but is fine for any other pointer type:
10870   //
10871   // C++ [expr.unary.op]p1:
10872   //   [...] the expression to which [the unary * operator] is applied shall
10873   //   be a pointer to an object type, or a pointer to a function type
10874   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10875     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10876       << OpTy << Op->getSourceRange();
10877 
10878   // Dereferences are usually l-values...
10879   VK = VK_LValue;
10880 
10881   // ...except that certain expressions are never l-values in C.
10882   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10883     VK = VK_RValue;
10884 
10885   return Result;
10886 }
10887 
10888 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10889   BinaryOperatorKind Opc;
10890   switch (Kind) {
10891   default: llvm_unreachable("Unknown binop!");
10892   case tok::periodstar:           Opc = BO_PtrMemD; break;
10893   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10894   case tok::star:                 Opc = BO_Mul; break;
10895   case tok::slash:                Opc = BO_Div; break;
10896   case tok::percent:              Opc = BO_Rem; break;
10897   case tok::plus:                 Opc = BO_Add; break;
10898   case tok::minus:                Opc = BO_Sub; break;
10899   case tok::lessless:             Opc = BO_Shl; break;
10900   case tok::greatergreater:       Opc = BO_Shr; break;
10901   case tok::lessequal:            Opc = BO_LE; break;
10902   case tok::less:                 Opc = BO_LT; break;
10903   case tok::greaterequal:         Opc = BO_GE; break;
10904   case tok::greater:              Opc = BO_GT; break;
10905   case tok::exclaimequal:         Opc = BO_NE; break;
10906   case tok::equalequal:           Opc = BO_EQ; break;
10907   case tok::amp:                  Opc = BO_And; break;
10908   case tok::caret:                Opc = BO_Xor; break;
10909   case tok::pipe:                 Opc = BO_Or; break;
10910   case tok::ampamp:               Opc = BO_LAnd; break;
10911   case tok::pipepipe:             Opc = BO_LOr; break;
10912   case tok::equal:                Opc = BO_Assign; break;
10913   case tok::starequal:            Opc = BO_MulAssign; break;
10914   case tok::slashequal:           Opc = BO_DivAssign; break;
10915   case tok::percentequal:         Opc = BO_RemAssign; break;
10916   case tok::plusequal:            Opc = BO_AddAssign; break;
10917   case tok::minusequal:           Opc = BO_SubAssign; break;
10918   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10919   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10920   case tok::ampequal:             Opc = BO_AndAssign; break;
10921   case tok::caretequal:           Opc = BO_XorAssign; break;
10922   case tok::pipeequal:            Opc = BO_OrAssign; break;
10923   case tok::comma:                Opc = BO_Comma; break;
10924   }
10925   return Opc;
10926 }
10927 
10928 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10929   tok::TokenKind Kind) {
10930   UnaryOperatorKind Opc;
10931   switch (Kind) {
10932   default: llvm_unreachable("Unknown unary op!");
10933   case tok::plusplus:     Opc = UO_PreInc; break;
10934   case tok::minusminus:   Opc = UO_PreDec; break;
10935   case tok::amp:          Opc = UO_AddrOf; break;
10936   case tok::star:         Opc = UO_Deref; break;
10937   case tok::plus:         Opc = UO_Plus; break;
10938   case tok::minus:        Opc = UO_Minus; break;
10939   case tok::tilde:        Opc = UO_Not; break;
10940   case tok::exclaim:      Opc = UO_LNot; break;
10941   case tok::kw___real:    Opc = UO_Real; break;
10942   case tok::kw___imag:    Opc = UO_Imag; break;
10943   case tok::kw___extension__: Opc = UO_Extension; break;
10944   }
10945   return Opc;
10946 }
10947 
10948 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10949 /// This warning is only emitted for builtin assignment operations. It is also
10950 /// suppressed in the event of macro expansions.
10951 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10952                                    SourceLocation OpLoc) {
10953   if (!S.ActiveTemplateInstantiations.empty())
10954     return;
10955   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10956     return;
10957   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10958   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10959   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10960   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10961   if (!LHSDeclRef || !RHSDeclRef ||
10962       LHSDeclRef->getLocation().isMacroID() ||
10963       RHSDeclRef->getLocation().isMacroID())
10964     return;
10965   const ValueDecl *LHSDecl =
10966     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10967   const ValueDecl *RHSDecl =
10968     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10969   if (LHSDecl != RHSDecl)
10970     return;
10971   if (LHSDecl->getType().isVolatileQualified())
10972     return;
10973   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10974     if (RefTy->getPointeeType().isVolatileQualified())
10975       return;
10976 
10977   S.Diag(OpLoc, diag::warn_self_assignment)
10978       << LHSDeclRef->getType()
10979       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10980 }
10981 
10982 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10983 /// is usually indicative of introspection within the Objective-C pointer.
10984 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10985                                           SourceLocation OpLoc) {
10986   if (!S.getLangOpts().ObjC1)
10987     return;
10988 
10989   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10990   const Expr *LHS = L.get();
10991   const Expr *RHS = R.get();
10992 
10993   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10994     ObjCPointerExpr = LHS;
10995     OtherExpr = RHS;
10996   }
10997   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10998     ObjCPointerExpr = RHS;
10999     OtherExpr = LHS;
11000   }
11001 
11002   // This warning is deliberately made very specific to reduce false
11003   // positives with logic that uses '&' for hashing.  This logic mainly
11004   // looks for code trying to introspect into tagged pointers, which
11005   // code should generally never do.
11006   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11007     unsigned Diag = diag::warn_objc_pointer_masking;
11008     // Determine if we are introspecting the result of performSelectorXXX.
11009     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11010     // Special case messages to -performSelector and friends, which
11011     // can return non-pointer values boxed in a pointer value.
11012     // Some clients may wish to silence warnings in this subcase.
11013     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11014       Selector S = ME->getSelector();
11015       StringRef SelArg0 = S.getNameForSlot(0);
11016       if (SelArg0.startswith("performSelector"))
11017         Diag = diag::warn_objc_pointer_masking_performSelector;
11018     }
11019 
11020     S.Diag(OpLoc, Diag)
11021       << ObjCPointerExpr->getSourceRange();
11022   }
11023 }
11024 
11025 static NamedDecl *getDeclFromExpr(Expr *E) {
11026   if (!E)
11027     return nullptr;
11028   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11029     return DRE->getDecl();
11030   if (auto *ME = dyn_cast<MemberExpr>(E))
11031     return ME->getMemberDecl();
11032   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11033     return IRE->getDecl();
11034   return nullptr;
11035 }
11036 
11037 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11038 /// operator @p Opc at location @c TokLoc. This routine only supports
11039 /// built-in operations; ActOnBinOp handles overloaded operators.
11040 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11041                                     BinaryOperatorKind Opc,
11042                                     Expr *LHSExpr, Expr *RHSExpr) {
11043   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11044     // The syntax only allows initializer lists on the RHS of assignment,
11045     // so we don't need to worry about accepting invalid code for
11046     // non-assignment operators.
11047     // C++11 5.17p9:
11048     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11049     //   of x = {} is x = T().
11050     InitializationKind Kind =
11051         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11052     InitializedEntity Entity =
11053         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11054     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11055     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11056     if (Init.isInvalid())
11057       return Init;
11058     RHSExpr = Init.get();
11059   }
11060 
11061   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11062   QualType ResultTy;     // Result type of the binary operator.
11063   // The following two variables are used for compound assignment operators
11064   QualType CompLHSTy;    // Type of LHS after promotions for computation
11065   QualType CompResultTy; // Type of computation result
11066   ExprValueKind VK = VK_RValue;
11067   ExprObjectKind OK = OK_Ordinary;
11068 
11069   if (!getLangOpts().CPlusPlus) {
11070     // C cannot handle TypoExpr nodes on either side of a binop because it
11071     // doesn't handle dependent types properly, so make sure any TypoExprs have
11072     // been dealt with before checking the operands.
11073     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11074     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11075       if (Opc != BO_Assign)
11076         return ExprResult(E);
11077       // Avoid correcting the RHS to the same Expr as the LHS.
11078       Decl *D = getDeclFromExpr(E);
11079       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11080     });
11081     if (!LHS.isUsable() || !RHS.isUsable())
11082       return ExprError();
11083   }
11084 
11085   if (getLangOpts().OpenCL) {
11086     QualType LHSTy = LHSExpr->getType();
11087     QualType RHSTy = RHSExpr->getType();
11088     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11089     // the ATOMIC_VAR_INIT macro.
11090     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11091       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11092       if (BO_Assign == Opc)
11093         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11094       else
11095         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11096       return ExprError();
11097     }
11098 
11099     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11100     // only with a builtin functions and therefore should be disallowed here.
11101     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11102         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11103         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11104         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11105       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11106       return ExprError();
11107     }
11108   }
11109 
11110   switch (Opc) {
11111   case BO_Assign:
11112     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11113     if (getLangOpts().CPlusPlus &&
11114         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11115       VK = LHS.get()->getValueKind();
11116       OK = LHS.get()->getObjectKind();
11117     }
11118     if (!ResultTy.isNull()) {
11119       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11120       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11121     }
11122     RecordModifiableNonNullParam(*this, LHS.get());
11123     break;
11124   case BO_PtrMemD:
11125   case BO_PtrMemI:
11126     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11127                                             Opc == BO_PtrMemI);
11128     break;
11129   case BO_Mul:
11130   case BO_Div:
11131     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11132                                            Opc == BO_Div);
11133     break;
11134   case BO_Rem:
11135     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11136     break;
11137   case BO_Add:
11138     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11139     break;
11140   case BO_Sub:
11141     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11142     break;
11143   case BO_Shl:
11144   case BO_Shr:
11145     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11146     break;
11147   case BO_LE:
11148   case BO_LT:
11149   case BO_GE:
11150   case BO_GT:
11151     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11152     break;
11153   case BO_EQ:
11154   case BO_NE:
11155     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11156     break;
11157   case BO_And:
11158     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11159   case BO_Xor:
11160   case BO_Or:
11161     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11162     break;
11163   case BO_LAnd:
11164   case BO_LOr:
11165     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11166     break;
11167   case BO_MulAssign:
11168   case BO_DivAssign:
11169     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11170                                                Opc == BO_DivAssign);
11171     CompLHSTy = CompResultTy;
11172     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11173       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11174     break;
11175   case BO_RemAssign:
11176     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11177     CompLHSTy = CompResultTy;
11178     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11179       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11180     break;
11181   case BO_AddAssign:
11182     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11183     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11184       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11185     break;
11186   case BO_SubAssign:
11187     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11188     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11189       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11190     break;
11191   case BO_ShlAssign:
11192   case BO_ShrAssign:
11193     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11194     CompLHSTy = CompResultTy;
11195     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11196       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11197     break;
11198   case BO_AndAssign:
11199   case BO_OrAssign: // fallthrough
11200     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11201   case BO_XorAssign:
11202     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11203     CompLHSTy = CompResultTy;
11204     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11205       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11206     break;
11207   case BO_Comma:
11208     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11209     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11210       VK = RHS.get()->getValueKind();
11211       OK = RHS.get()->getObjectKind();
11212     }
11213     break;
11214   }
11215   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11216     return ExprError();
11217 
11218   // Check for array bounds violations for both sides of the BinaryOperator
11219   CheckArrayAccess(LHS.get());
11220   CheckArrayAccess(RHS.get());
11221 
11222   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11223     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11224                                                  &Context.Idents.get("object_setClass"),
11225                                                  SourceLocation(), LookupOrdinaryName);
11226     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11227       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11228       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11229       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11230       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11231       FixItHint::CreateInsertion(RHSLocEnd, ")");
11232     }
11233     else
11234       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11235   }
11236   else if (const ObjCIvarRefExpr *OIRE =
11237            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11238     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11239 
11240   if (CompResultTy.isNull())
11241     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11242                                         OK, OpLoc, FPFeatures.fp_contract);
11243   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11244       OK_ObjCProperty) {
11245     VK = VK_LValue;
11246     OK = LHS.get()->getObjectKind();
11247   }
11248   return new (Context) CompoundAssignOperator(
11249       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11250       OpLoc, FPFeatures.fp_contract);
11251 }
11252 
11253 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11254 /// operators are mixed in a way that suggests that the programmer forgot that
11255 /// comparison operators have higher precedence. The most typical example of
11256 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11257 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11258                                       SourceLocation OpLoc, Expr *LHSExpr,
11259                                       Expr *RHSExpr) {
11260   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11261   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11262 
11263   // Check that one of the sides is a comparison operator and the other isn't.
11264   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11265   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11266   if (isLeftComp == isRightComp)
11267     return;
11268 
11269   // Bitwise operations are sometimes used as eager logical ops.
11270   // Don't diagnose this.
11271   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11272   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11273   if (isLeftBitwise || isRightBitwise)
11274     return;
11275 
11276   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11277                                                    OpLoc)
11278                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11279   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11280   SourceRange ParensRange = isLeftComp ?
11281       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11282     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11283 
11284   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11285     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11286   SuggestParentheses(Self, OpLoc,
11287     Self.PDiag(diag::note_precedence_silence) << OpStr,
11288     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11289   SuggestParentheses(Self, OpLoc,
11290     Self.PDiag(diag::note_precedence_bitwise_first)
11291       << BinaryOperator::getOpcodeStr(Opc),
11292     ParensRange);
11293 }
11294 
11295 /// \brief It accepts a '&&' expr that is inside a '||' one.
11296 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11297 /// in parentheses.
11298 static void
11299 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11300                                        BinaryOperator *Bop) {
11301   assert(Bop->getOpcode() == BO_LAnd);
11302   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11303       << Bop->getSourceRange() << OpLoc;
11304   SuggestParentheses(Self, Bop->getOperatorLoc(),
11305     Self.PDiag(diag::note_precedence_silence)
11306       << Bop->getOpcodeStr(),
11307     Bop->getSourceRange());
11308 }
11309 
11310 /// \brief Returns true if the given expression can be evaluated as a constant
11311 /// 'true'.
11312 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11313   bool Res;
11314   return !E->isValueDependent() &&
11315          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11316 }
11317 
11318 /// \brief Returns true if the given expression can be evaluated as a constant
11319 /// 'false'.
11320 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11321   bool Res;
11322   return !E->isValueDependent() &&
11323          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11324 }
11325 
11326 /// \brief Look for '&&' in the left hand of a '||' expr.
11327 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11328                                              Expr *LHSExpr, Expr *RHSExpr) {
11329   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11330     if (Bop->getOpcode() == BO_LAnd) {
11331       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11332       if (EvaluatesAsFalse(S, RHSExpr))
11333         return;
11334       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11335       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11336         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11337     } else if (Bop->getOpcode() == BO_LOr) {
11338       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11339         // If it's "a || b && 1 || c" we didn't warn earlier for
11340         // "a || b && 1", but warn now.
11341         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11342           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11343       }
11344     }
11345   }
11346 }
11347 
11348 /// \brief Look for '&&' in the right hand of a '||' expr.
11349 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11350                                              Expr *LHSExpr, Expr *RHSExpr) {
11351   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11352     if (Bop->getOpcode() == BO_LAnd) {
11353       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11354       if (EvaluatesAsFalse(S, LHSExpr))
11355         return;
11356       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11357       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11358         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11359     }
11360   }
11361 }
11362 
11363 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11364 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11365 /// the '&' expression in parentheses.
11366 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11367                                          SourceLocation OpLoc, Expr *SubExpr) {
11368   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11369     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11370       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11371         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11372         << Bop->getSourceRange() << OpLoc;
11373       SuggestParentheses(S, Bop->getOperatorLoc(),
11374         S.PDiag(diag::note_precedence_silence)
11375           << Bop->getOpcodeStr(),
11376         Bop->getSourceRange());
11377     }
11378   }
11379 }
11380 
11381 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11382                                     Expr *SubExpr, StringRef Shift) {
11383   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11384     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11385       StringRef Op = Bop->getOpcodeStr();
11386       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11387           << Bop->getSourceRange() << OpLoc << Shift << Op;
11388       SuggestParentheses(S, Bop->getOperatorLoc(),
11389           S.PDiag(diag::note_precedence_silence) << Op,
11390           Bop->getSourceRange());
11391     }
11392   }
11393 }
11394 
11395 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11396                                  Expr *LHSExpr, Expr *RHSExpr) {
11397   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11398   if (!OCE)
11399     return;
11400 
11401   FunctionDecl *FD = OCE->getDirectCallee();
11402   if (!FD || !FD->isOverloadedOperator())
11403     return;
11404 
11405   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11406   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11407     return;
11408 
11409   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11410       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11411       << (Kind == OO_LessLess);
11412   SuggestParentheses(S, OCE->getOperatorLoc(),
11413                      S.PDiag(diag::note_precedence_silence)
11414                          << (Kind == OO_LessLess ? "<<" : ">>"),
11415                      OCE->getSourceRange());
11416   SuggestParentheses(S, OpLoc,
11417                      S.PDiag(diag::note_evaluate_comparison_first),
11418                      SourceRange(OCE->getArg(1)->getLocStart(),
11419                                  RHSExpr->getLocEnd()));
11420 }
11421 
11422 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11423 /// precedence.
11424 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11425                                     SourceLocation OpLoc, Expr *LHSExpr,
11426                                     Expr *RHSExpr){
11427   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11428   if (BinaryOperator::isBitwiseOp(Opc))
11429     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11430 
11431   // Diagnose "arg1 & arg2 | arg3"
11432   if ((Opc == BO_Or || Opc == BO_Xor) &&
11433       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11434     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11435     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11436   }
11437 
11438   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11439   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11440   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11441     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11442     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11443   }
11444 
11445   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11446       || Opc == BO_Shr) {
11447     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11448     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11449     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11450   }
11451 
11452   // Warn on overloaded shift operators and comparisons, such as:
11453   // cout << 5 == 4;
11454   if (BinaryOperator::isComparisonOp(Opc))
11455     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11456 }
11457 
11458 // Binary Operators.  'Tok' is the token for the operator.
11459 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11460                             tok::TokenKind Kind,
11461                             Expr *LHSExpr, Expr *RHSExpr) {
11462   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11463   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11464   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11465 
11466   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11467   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11468 
11469   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11470 }
11471 
11472 /// Build an overloaded binary operator expression in the given scope.
11473 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11474                                        BinaryOperatorKind Opc,
11475                                        Expr *LHS, Expr *RHS) {
11476   // Find all of the overloaded operators visible from this
11477   // point. We perform both an operator-name lookup from the local
11478   // scope and an argument-dependent lookup based on the types of
11479   // the arguments.
11480   UnresolvedSet<16> Functions;
11481   OverloadedOperatorKind OverOp
11482     = BinaryOperator::getOverloadedOperator(Opc);
11483   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11484     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11485                                    RHS->getType(), Functions);
11486 
11487   // Build the (potentially-overloaded, potentially-dependent)
11488   // binary operation.
11489   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11490 }
11491 
11492 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11493                             BinaryOperatorKind Opc,
11494                             Expr *LHSExpr, Expr *RHSExpr) {
11495   // We want to end up calling one of checkPseudoObjectAssignment
11496   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11497   // both expressions are overloadable or either is type-dependent),
11498   // or CreateBuiltinBinOp (in any other case).  We also want to get
11499   // any placeholder types out of the way.
11500 
11501   // Handle pseudo-objects in the LHS.
11502   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11503     // Assignments with a pseudo-object l-value need special analysis.
11504     if (pty->getKind() == BuiltinType::PseudoObject &&
11505         BinaryOperator::isAssignmentOp(Opc))
11506       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11507 
11508     // Don't resolve overloads if the other type is overloadable.
11509     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11510       // We can't actually test that if we still have a placeholder,
11511       // though.  Fortunately, none of the exceptions we see in that
11512       // code below are valid when the LHS is an overload set.  Note
11513       // that an overload set can be dependently-typed, but it never
11514       // instantiates to having an overloadable type.
11515       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11516       if (resolvedRHS.isInvalid()) return ExprError();
11517       RHSExpr = resolvedRHS.get();
11518 
11519       if (RHSExpr->isTypeDependent() ||
11520           RHSExpr->getType()->isOverloadableType())
11521         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11522     }
11523 
11524     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11525     if (LHS.isInvalid()) return ExprError();
11526     LHSExpr = LHS.get();
11527   }
11528 
11529   // Handle pseudo-objects in the RHS.
11530   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11531     // An overload in the RHS can potentially be resolved by the type
11532     // being assigned to.
11533     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11534       if (getLangOpts().CPlusPlus &&
11535           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11536            LHSExpr->getType()->isOverloadableType()))
11537         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11538 
11539       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11540     }
11541 
11542     // Don't resolve overloads if the other type is overloadable.
11543     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11544         LHSExpr->getType()->isOverloadableType())
11545       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11546 
11547     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11548     if (!resolvedRHS.isUsable()) return ExprError();
11549     RHSExpr = resolvedRHS.get();
11550   }
11551 
11552   if (getLangOpts().CPlusPlus) {
11553     // If either expression is type-dependent, always build an
11554     // overloaded op.
11555     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11556       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11557 
11558     // Otherwise, build an overloaded op if either expression has an
11559     // overloadable type.
11560     if (LHSExpr->getType()->isOverloadableType() ||
11561         RHSExpr->getType()->isOverloadableType())
11562       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11563   }
11564 
11565   // Build a built-in binary operation.
11566   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11567 }
11568 
11569 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11570                                       UnaryOperatorKind Opc,
11571                                       Expr *InputExpr) {
11572   ExprResult Input = InputExpr;
11573   ExprValueKind VK = VK_RValue;
11574   ExprObjectKind OK = OK_Ordinary;
11575   QualType resultType;
11576   if (getLangOpts().OpenCL) {
11577     QualType Ty = InputExpr->getType();
11578     // The only legal unary operation for atomics is '&'.
11579     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11580     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11581     // only with a builtin functions and therefore should be disallowed here.
11582         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11583         || Ty->isBlockPointerType())) {
11584       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11585                        << InputExpr->getType()
11586                        << Input.get()->getSourceRange());
11587     }
11588   }
11589   switch (Opc) {
11590   case UO_PreInc:
11591   case UO_PreDec:
11592   case UO_PostInc:
11593   case UO_PostDec:
11594     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11595                                                 OpLoc,
11596                                                 Opc == UO_PreInc ||
11597                                                 Opc == UO_PostInc,
11598                                                 Opc == UO_PreInc ||
11599                                                 Opc == UO_PreDec);
11600     break;
11601   case UO_AddrOf:
11602     resultType = CheckAddressOfOperand(Input, OpLoc);
11603     RecordModifiableNonNullParam(*this, InputExpr);
11604     break;
11605   case UO_Deref: {
11606     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11607     if (Input.isInvalid()) return ExprError();
11608     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11609     break;
11610   }
11611   case UO_Plus:
11612   case UO_Minus:
11613     Input = UsualUnaryConversions(Input.get());
11614     if (Input.isInvalid()) return ExprError();
11615     resultType = Input.get()->getType();
11616     if (resultType->isDependentType())
11617       break;
11618     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11619       break;
11620     else if (resultType->isVectorType() &&
11621              // The z vector extensions don't allow + or - with bool vectors.
11622              (!Context.getLangOpts().ZVector ||
11623               resultType->getAs<VectorType>()->getVectorKind() !=
11624               VectorType::AltiVecBool))
11625       break;
11626     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11627              Opc == UO_Plus &&
11628              resultType->isPointerType())
11629       break;
11630 
11631     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11632       << resultType << Input.get()->getSourceRange());
11633 
11634   case UO_Not: // bitwise complement
11635     Input = UsualUnaryConversions(Input.get());
11636     if (Input.isInvalid())
11637       return ExprError();
11638     resultType = Input.get()->getType();
11639     if (resultType->isDependentType())
11640       break;
11641     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11642     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11643       // C99 does not support '~' for complex conjugation.
11644       Diag(OpLoc, diag::ext_integer_complement_complex)
11645           << resultType << Input.get()->getSourceRange();
11646     else if (resultType->hasIntegerRepresentation())
11647       break;
11648     else if (resultType->isExtVectorType()) {
11649       if (Context.getLangOpts().OpenCL) {
11650         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11651         // on vector float types.
11652         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11653         if (!T->isIntegerType())
11654           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11655                            << resultType << Input.get()->getSourceRange());
11656       }
11657       break;
11658     } else {
11659       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11660                        << resultType << Input.get()->getSourceRange());
11661     }
11662     break;
11663 
11664   case UO_LNot: // logical negation
11665     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11666     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11667     if (Input.isInvalid()) return ExprError();
11668     resultType = Input.get()->getType();
11669 
11670     // Though we still have to promote half FP to float...
11671     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11672       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11673       resultType = Context.FloatTy;
11674     }
11675 
11676     if (resultType->isDependentType())
11677       break;
11678     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11679       // C99 6.5.3.3p1: ok, fallthrough;
11680       if (Context.getLangOpts().CPlusPlus) {
11681         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11682         // operand contextually converted to bool.
11683         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11684                                   ScalarTypeToBooleanCastKind(resultType));
11685       } else if (Context.getLangOpts().OpenCL &&
11686                  Context.getLangOpts().OpenCLVersion < 120) {
11687         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11688         // operate on scalar float types.
11689         if (!resultType->isIntegerType() && !resultType->isPointerType())
11690           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11691                            << resultType << Input.get()->getSourceRange());
11692       }
11693     } else if (resultType->isExtVectorType()) {
11694       if (Context.getLangOpts().OpenCL &&
11695           Context.getLangOpts().OpenCLVersion < 120) {
11696         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11697         // operate on vector float types.
11698         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11699         if (!T->isIntegerType())
11700           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11701                            << resultType << Input.get()->getSourceRange());
11702       }
11703       // Vector logical not returns the signed variant of the operand type.
11704       resultType = GetSignedVectorType(resultType);
11705       break;
11706     } else {
11707       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11708         << resultType << Input.get()->getSourceRange());
11709     }
11710 
11711     // LNot always has type int. C99 6.5.3.3p5.
11712     // In C++, it's bool. C++ 5.3.1p8
11713     resultType = Context.getLogicalOperationType();
11714     break;
11715   case UO_Real:
11716   case UO_Imag:
11717     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11718     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11719     // complex l-values to ordinary l-values and all other values to r-values.
11720     if (Input.isInvalid()) return ExprError();
11721     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11722       if (Input.get()->getValueKind() != VK_RValue &&
11723           Input.get()->getObjectKind() == OK_Ordinary)
11724         VK = Input.get()->getValueKind();
11725     } else if (!getLangOpts().CPlusPlus) {
11726       // In C, a volatile scalar is read by __imag. In C++, it is not.
11727       Input = DefaultLvalueConversion(Input.get());
11728     }
11729     break;
11730   case UO_Extension:
11731   case UO_Coawait:
11732     resultType = Input.get()->getType();
11733     VK = Input.get()->getValueKind();
11734     OK = Input.get()->getObjectKind();
11735     break;
11736   }
11737   if (resultType.isNull() || Input.isInvalid())
11738     return ExprError();
11739 
11740   // Check for array bounds violations in the operand of the UnaryOperator,
11741   // except for the '*' and '&' operators that have to be handled specially
11742   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11743   // that are explicitly defined as valid by the standard).
11744   if (Opc != UO_AddrOf && Opc != UO_Deref)
11745     CheckArrayAccess(Input.get());
11746 
11747   return new (Context)
11748       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11749 }
11750 
11751 /// \brief Determine whether the given expression is a qualified member
11752 /// access expression, of a form that could be turned into a pointer to member
11753 /// with the address-of operator.
11754 static bool isQualifiedMemberAccess(Expr *E) {
11755   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11756     if (!DRE->getQualifier())
11757       return false;
11758 
11759     ValueDecl *VD = DRE->getDecl();
11760     if (!VD->isCXXClassMember())
11761       return false;
11762 
11763     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11764       return true;
11765     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11766       return Method->isInstance();
11767 
11768     return false;
11769   }
11770 
11771   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11772     if (!ULE->getQualifier())
11773       return false;
11774 
11775     for (NamedDecl *D : ULE->decls()) {
11776       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11777         if (Method->isInstance())
11778           return true;
11779       } else {
11780         // Overload set does not contain methods.
11781         break;
11782       }
11783     }
11784 
11785     return false;
11786   }
11787 
11788   return false;
11789 }
11790 
11791 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11792                               UnaryOperatorKind Opc, Expr *Input) {
11793   // First things first: handle placeholders so that the
11794   // overloaded-operator check considers the right type.
11795   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11796     // Increment and decrement of pseudo-object references.
11797     if (pty->getKind() == BuiltinType::PseudoObject &&
11798         UnaryOperator::isIncrementDecrementOp(Opc))
11799       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11800 
11801     // extension is always a builtin operator.
11802     if (Opc == UO_Extension)
11803       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11804 
11805     // & gets special logic for several kinds of placeholder.
11806     // The builtin code knows what to do.
11807     if (Opc == UO_AddrOf &&
11808         (pty->getKind() == BuiltinType::Overload ||
11809          pty->getKind() == BuiltinType::UnknownAny ||
11810          pty->getKind() == BuiltinType::BoundMember))
11811       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11812 
11813     // Anything else needs to be handled now.
11814     ExprResult Result = CheckPlaceholderExpr(Input);
11815     if (Result.isInvalid()) return ExprError();
11816     Input = Result.get();
11817   }
11818 
11819   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11820       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11821       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11822     // Find all of the overloaded operators visible from this
11823     // point. We perform both an operator-name lookup from the local
11824     // scope and an argument-dependent lookup based on the types of
11825     // the arguments.
11826     UnresolvedSet<16> Functions;
11827     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11828     if (S && OverOp != OO_None)
11829       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11830                                    Functions);
11831 
11832     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11833   }
11834 
11835   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11836 }
11837 
11838 // Unary Operators.  'Tok' is the token for the operator.
11839 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11840                               tok::TokenKind Op, Expr *Input) {
11841   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11842 }
11843 
11844 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11845 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11846                                 LabelDecl *TheDecl) {
11847   TheDecl->markUsed(Context);
11848   // Create the AST node.  The address of a label always has type 'void*'.
11849   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11850                                      Context.getPointerType(Context.VoidTy));
11851 }
11852 
11853 /// Given the last statement in a statement-expression, check whether
11854 /// the result is a producing expression (like a call to an
11855 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11856 /// release out of the full-expression.  Otherwise, return null.
11857 /// Cannot fail.
11858 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11859   // Should always be wrapped with one of these.
11860   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11861   if (!cleanups) return nullptr;
11862 
11863   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11864   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11865     return nullptr;
11866 
11867   // Splice out the cast.  This shouldn't modify any interesting
11868   // features of the statement.
11869   Expr *producer = cast->getSubExpr();
11870   assert(producer->getType() == cast->getType());
11871   assert(producer->getValueKind() == cast->getValueKind());
11872   cleanups->setSubExpr(producer);
11873   return cleanups;
11874 }
11875 
11876 void Sema::ActOnStartStmtExpr() {
11877   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11878 }
11879 
11880 void Sema::ActOnStmtExprError() {
11881   // Note that function is also called by TreeTransform when leaving a
11882   // StmtExpr scope without rebuilding anything.
11883 
11884   DiscardCleanupsInEvaluationContext();
11885   PopExpressionEvaluationContext();
11886 }
11887 
11888 ExprResult
11889 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11890                     SourceLocation RPLoc) { // "({..})"
11891   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11892   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11893 
11894   if (hasAnyUnrecoverableErrorsInThisFunction())
11895     DiscardCleanupsInEvaluationContext();
11896   assert(!Cleanup.exprNeedsCleanups() &&
11897          "cleanups within StmtExpr not correctly bound!");
11898   PopExpressionEvaluationContext();
11899 
11900   // FIXME: there are a variety of strange constraints to enforce here, for
11901   // example, it is not possible to goto into a stmt expression apparently.
11902   // More semantic analysis is needed.
11903 
11904   // If there are sub-stmts in the compound stmt, take the type of the last one
11905   // as the type of the stmtexpr.
11906   QualType Ty = Context.VoidTy;
11907   bool StmtExprMayBindToTemp = false;
11908   if (!Compound->body_empty()) {
11909     Stmt *LastStmt = Compound->body_back();
11910     LabelStmt *LastLabelStmt = nullptr;
11911     // If LastStmt is a label, skip down through into the body.
11912     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11913       LastLabelStmt = Label;
11914       LastStmt = Label->getSubStmt();
11915     }
11916 
11917     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11918       // Do function/array conversion on the last expression, but not
11919       // lvalue-to-rvalue.  However, initialize an unqualified type.
11920       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11921       if (LastExpr.isInvalid())
11922         return ExprError();
11923       Ty = LastExpr.get()->getType().getUnqualifiedType();
11924 
11925       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11926         // In ARC, if the final expression ends in a consume, splice
11927         // the consume out and bind it later.  In the alternate case
11928         // (when dealing with a retainable type), the result
11929         // initialization will create a produce.  In both cases the
11930         // result will be +1, and we'll need to balance that out with
11931         // a bind.
11932         if (Expr *rebuiltLastStmt
11933               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11934           LastExpr = rebuiltLastStmt;
11935         } else {
11936           LastExpr = PerformCopyInitialization(
11937                             InitializedEntity::InitializeResult(LPLoc,
11938                                                                 Ty,
11939                                                                 false),
11940                                                    SourceLocation(),
11941                                                LastExpr);
11942         }
11943 
11944         if (LastExpr.isInvalid())
11945           return ExprError();
11946         if (LastExpr.get() != nullptr) {
11947           if (!LastLabelStmt)
11948             Compound->setLastStmt(LastExpr.get());
11949           else
11950             LastLabelStmt->setSubStmt(LastExpr.get());
11951           StmtExprMayBindToTemp = true;
11952         }
11953       }
11954     }
11955   }
11956 
11957   // FIXME: Check that expression type is complete/non-abstract; statement
11958   // expressions are not lvalues.
11959   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11960   if (StmtExprMayBindToTemp)
11961     return MaybeBindToTemporary(ResStmtExpr);
11962   return ResStmtExpr;
11963 }
11964 
11965 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11966                                       TypeSourceInfo *TInfo,
11967                                       ArrayRef<OffsetOfComponent> Components,
11968                                       SourceLocation RParenLoc) {
11969   QualType ArgTy = TInfo->getType();
11970   bool Dependent = ArgTy->isDependentType();
11971   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11972 
11973   // We must have at least one component that refers to the type, and the first
11974   // one is known to be a field designator.  Verify that the ArgTy represents
11975   // a struct/union/class.
11976   if (!Dependent && !ArgTy->isRecordType())
11977     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11978                        << ArgTy << TypeRange);
11979 
11980   // Type must be complete per C99 7.17p3 because a declaring a variable
11981   // with an incomplete type would be ill-formed.
11982   if (!Dependent
11983       && RequireCompleteType(BuiltinLoc, ArgTy,
11984                              diag::err_offsetof_incomplete_type, TypeRange))
11985     return ExprError();
11986 
11987   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11988   // GCC extension, diagnose them.
11989   // FIXME: This diagnostic isn't actually visible because the location is in
11990   // a system header!
11991   if (Components.size() != 1)
11992     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11993       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11994 
11995   bool DidWarnAboutNonPOD = false;
11996   QualType CurrentType = ArgTy;
11997   SmallVector<OffsetOfNode, 4> Comps;
11998   SmallVector<Expr*, 4> Exprs;
11999   for (const OffsetOfComponent &OC : Components) {
12000     if (OC.isBrackets) {
12001       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12002       if (!CurrentType->isDependentType()) {
12003         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12004         if(!AT)
12005           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12006                            << CurrentType);
12007         CurrentType = AT->getElementType();
12008       } else
12009         CurrentType = Context.DependentTy;
12010 
12011       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12012       if (IdxRval.isInvalid())
12013         return ExprError();
12014       Expr *Idx = IdxRval.get();
12015 
12016       // The expression must be an integral expression.
12017       // FIXME: An integral constant expression?
12018       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12019           !Idx->getType()->isIntegerType())
12020         return ExprError(Diag(Idx->getLocStart(),
12021                               diag::err_typecheck_subscript_not_integer)
12022                          << Idx->getSourceRange());
12023 
12024       // Record this array index.
12025       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12026       Exprs.push_back(Idx);
12027       continue;
12028     }
12029 
12030     // Offset of a field.
12031     if (CurrentType->isDependentType()) {
12032       // We have the offset of a field, but we can't look into the dependent
12033       // type. Just record the identifier of the field.
12034       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12035       CurrentType = Context.DependentTy;
12036       continue;
12037     }
12038 
12039     // We need to have a complete type to look into.
12040     if (RequireCompleteType(OC.LocStart, CurrentType,
12041                             diag::err_offsetof_incomplete_type))
12042       return ExprError();
12043 
12044     // Look for the designated field.
12045     const RecordType *RC = CurrentType->getAs<RecordType>();
12046     if (!RC)
12047       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12048                        << CurrentType);
12049     RecordDecl *RD = RC->getDecl();
12050 
12051     // C++ [lib.support.types]p5:
12052     //   The macro offsetof accepts a restricted set of type arguments in this
12053     //   International Standard. type shall be a POD structure or a POD union
12054     //   (clause 9).
12055     // C++11 [support.types]p4:
12056     //   If type is not a standard-layout class (Clause 9), the results are
12057     //   undefined.
12058     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12059       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12060       unsigned DiagID =
12061         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12062                             : diag::ext_offsetof_non_pod_type;
12063 
12064       if (!IsSafe && !DidWarnAboutNonPOD &&
12065           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12066                               PDiag(DiagID)
12067                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12068                               << CurrentType))
12069         DidWarnAboutNonPOD = true;
12070     }
12071 
12072     // Look for the field.
12073     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12074     LookupQualifiedName(R, RD);
12075     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12076     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12077     if (!MemberDecl) {
12078       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12079         MemberDecl = IndirectMemberDecl->getAnonField();
12080     }
12081 
12082     if (!MemberDecl)
12083       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12084                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12085                                                               OC.LocEnd));
12086 
12087     // C99 7.17p3:
12088     //   (If the specified member is a bit-field, the behavior is undefined.)
12089     //
12090     // We diagnose this as an error.
12091     if (MemberDecl->isBitField()) {
12092       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12093         << MemberDecl->getDeclName()
12094         << SourceRange(BuiltinLoc, RParenLoc);
12095       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12096       return ExprError();
12097     }
12098 
12099     RecordDecl *Parent = MemberDecl->getParent();
12100     if (IndirectMemberDecl)
12101       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12102 
12103     // If the member was found in a base class, introduce OffsetOfNodes for
12104     // the base class indirections.
12105     CXXBasePaths Paths;
12106     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12107                       Paths)) {
12108       if (Paths.getDetectedVirtual()) {
12109         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12110           << MemberDecl->getDeclName()
12111           << SourceRange(BuiltinLoc, RParenLoc);
12112         return ExprError();
12113       }
12114 
12115       CXXBasePath &Path = Paths.front();
12116       for (const CXXBasePathElement &B : Path)
12117         Comps.push_back(OffsetOfNode(B.Base));
12118     }
12119 
12120     if (IndirectMemberDecl) {
12121       for (auto *FI : IndirectMemberDecl->chain()) {
12122         assert(isa<FieldDecl>(FI));
12123         Comps.push_back(OffsetOfNode(OC.LocStart,
12124                                      cast<FieldDecl>(FI), OC.LocEnd));
12125       }
12126     } else
12127       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12128 
12129     CurrentType = MemberDecl->getType().getNonReferenceType();
12130   }
12131 
12132   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12133                               Comps, Exprs, RParenLoc);
12134 }
12135 
12136 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12137                                       SourceLocation BuiltinLoc,
12138                                       SourceLocation TypeLoc,
12139                                       ParsedType ParsedArgTy,
12140                                       ArrayRef<OffsetOfComponent> Components,
12141                                       SourceLocation RParenLoc) {
12142 
12143   TypeSourceInfo *ArgTInfo;
12144   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12145   if (ArgTy.isNull())
12146     return ExprError();
12147 
12148   if (!ArgTInfo)
12149     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12150 
12151   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12152 }
12153 
12154 
12155 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12156                                  Expr *CondExpr,
12157                                  Expr *LHSExpr, Expr *RHSExpr,
12158                                  SourceLocation RPLoc) {
12159   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12160 
12161   ExprValueKind VK = VK_RValue;
12162   ExprObjectKind OK = OK_Ordinary;
12163   QualType resType;
12164   bool ValueDependent = false;
12165   bool CondIsTrue = false;
12166   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12167     resType = Context.DependentTy;
12168     ValueDependent = true;
12169   } else {
12170     // The conditional expression is required to be a constant expression.
12171     llvm::APSInt condEval(32);
12172     ExprResult CondICE
12173       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12174           diag::err_typecheck_choose_expr_requires_constant, false);
12175     if (CondICE.isInvalid())
12176       return ExprError();
12177     CondExpr = CondICE.get();
12178     CondIsTrue = condEval.getZExtValue();
12179 
12180     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12181     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12182 
12183     resType = ActiveExpr->getType();
12184     ValueDependent = ActiveExpr->isValueDependent();
12185     VK = ActiveExpr->getValueKind();
12186     OK = ActiveExpr->getObjectKind();
12187   }
12188 
12189   return new (Context)
12190       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12191                  CondIsTrue, resType->isDependentType(), ValueDependent);
12192 }
12193 
12194 //===----------------------------------------------------------------------===//
12195 // Clang Extensions.
12196 //===----------------------------------------------------------------------===//
12197 
12198 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12199 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12200   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12201 
12202   if (LangOpts.CPlusPlus) {
12203     Decl *ManglingContextDecl;
12204     if (MangleNumberingContext *MCtx =
12205             getCurrentMangleNumberContext(Block->getDeclContext(),
12206                                           ManglingContextDecl)) {
12207       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12208       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12209     }
12210   }
12211 
12212   PushBlockScope(CurScope, Block);
12213   CurContext->addDecl(Block);
12214   if (CurScope)
12215     PushDeclContext(CurScope, Block);
12216   else
12217     CurContext = Block;
12218 
12219   getCurBlock()->HasImplicitReturnType = true;
12220 
12221   // Enter a new evaluation context to insulate the block from any
12222   // cleanups from the enclosing full-expression.
12223   PushExpressionEvaluationContext(PotentiallyEvaluated);
12224 }
12225 
12226 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12227                                Scope *CurScope) {
12228   assert(ParamInfo.getIdentifier() == nullptr &&
12229          "block-id should have no identifier!");
12230   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12231   BlockScopeInfo *CurBlock = getCurBlock();
12232 
12233   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12234   QualType T = Sig->getType();
12235 
12236   // FIXME: We should allow unexpanded parameter packs here, but that would,
12237   // in turn, make the block expression contain unexpanded parameter packs.
12238   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12239     // Drop the parameters.
12240     FunctionProtoType::ExtProtoInfo EPI;
12241     EPI.HasTrailingReturn = false;
12242     EPI.TypeQuals |= DeclSpec::TQ_const;
12243     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12244     Sig = Context.getTrivialTypeSourceInfo(T);
12245   }
12246 
12247   // GetTypeForDeclarator always produces a function type for a block
12248   // literal signature.  Furthermore, it is always a FunctionProtoType
12249   // unless the function was written with a typedef.
12250   assert(T->isFunctionType() &&
12251          "GetTypeForDeclarator made a non-function block signature");
12252 
12253   // Look for an explicit signature in that function type.
12254   FunctionProtoTypeLoc ExplicitSignature;
12255 
12256   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12257   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12258 
12259     // Check whether that explicit signature was synthesized by
12260     // GetTypeForDeclarator.  If so, don't save that as part of the
12261     // written signature.
12262     if (ExplicitSignature.getLocalRangeBegin() ==
12263         ExplicitSignature.getLocalRangeEnd()) {
12264       // This would be much cheaper if we stored TypeLocs instead of
12265       // TypeSourceInfos.
12266       TypeLoc Result = ExplicitSignature.getReturnLoc();
12267       unsigned Size = Result.getFullDataSize();
12268       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12269       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12270 
12271       ExplicitSignature = FunctionProtoTypeLoc();
12272     }
12273   }
12274 
12275   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12276   CurBlock->FunctionType = T;
12277 
12278   const FunctionType *Fn = T->getAs<FunctionType>();
12279   QualType RetTy = Fn->getReturnType();
12280   bool isVariadic =
12281     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12282 
12283   CurBlock->TheDecl->setIsVariadic(isVariadic);
12284 
12285   // Context.DependentTy is used as a placeholder for a missing block
12286   // return type.  TODO:  what should we do with declarators like:
12287   //   ^ * { ... }
12288   // If the answer is "apply template argument deduction"....
12289   if (RetTy != Context.DependentTy) {
12290     CurBlock->ReturnType = RetTy;
12291     CurBlock->TheDecl->setBlockMissingReturnType(false);
12292     CurBlock->HasImplicitReturnType = false;
12293   }
12294 
12295   // Push block parameters from the declarator if we had them.
12296   SmallVector<ParmVarDecl*, 8> Params;
12297   if (ExplicitSignature) {
12298     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12299       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12300       if (Param->getIdentifier() == nullptr &&
12301           !Param->isImplicit() &&
12302           !Param->isInvalidDecl() &&
12303           !getLangOpts().CPlusPlus)
12304         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12305       Params.push_back(Param);
12306     }
12307 
12308   // Fake up parameter variables if we have a typedef, like
12309   //   ^ fntype { ... }
12310   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12311     for (const auto &I : Fn->param_types()) {
12312       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12313           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12314       Params.push_back(Param);
12315     }
12316   }
12317 
12318   // Set the parameters on the block decl.
12319   if (!Params.empty()) {
12320     CurBlock->TheDecl->setParams(Params);
12321     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12322                              /*CheckParameterNames=*/false);
12323   }
12324 
12325   // Finally we can process decl attributes.
12326   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12327 
12328   // Put the parameter variables in scope.
12329   for (auto AI : CurBlock->TheDecl->parameters()) {
12330     AI->setOwningFunction(CurBlock->TheDecl);
12331 
12332     // If this has an identifier, add it to the scope stack.
12333     if (AI->getIdentifier()) {
12334       CheckShadow(CurBlock->TheScope, AI);
12335 
12336       PushOnScopeChains(AI, CurBlock->TheScope);
12337     }
12338   }
12339 }
12340 
12341 /// ActOnBlockError - If there is an error parsing a block, this callback
12342 /// is invoked to pop the information about the block from the action impl.
12343 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12344   // Leave the expression-evaluation context.
12345   DiscardCleanupsInEvaluationContext();
12346   PopExpressionEvaluationContext();
12347 
12348   // Pop off CurBlock, handle nested blocks.
12349   PopDeclContext();
12350   PopFunctionScopeInfo();
12351 }
12352 
12353 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12354 /// literal was successfully completed.  ^(int x){...}
12355 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12356                                     Stmt *Body, Scope *CurScope) {
12357   // If blocks are disabled, emit an error.
12358   if (!LangOpts.Blocks)
12359     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12360 
12361   // Leave the expression-evaluation context.
12362   if (hasAnyUnrecoverableErrorsInThisFunction())
12363     DiscardCleanupsInEvaluationContext();
12364   assert(!Cleanup.exprNeedsCleanups() &&
12365          "cleanups within block not correctly bound!");
12366   PopExpressionEvaluationContext();
12367 
12368   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12369 
12370   if (BSI->HasImplicitReturnType)
12371     deduceClosureReturnType(*BSI);
12372 
12373   PopDeclContext();
12374 
12375   QualType RetTy = Context.VoidTy;
12376   if (!BSI->ReturnType.isNull())
12377     RetTy = BSI->ReturnType;
12378 
12379   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12380   QualType BlockTy;
12381 
12382   // Set the captured variables on the block.
12383   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12384   SmallVector<BlockDecl::Capture, 4> Captures;
12385   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12386     if (Cap.isThisCapture())
12387       continue;
12388     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12389                               Cap.isNested(), Cap.getInitExpr());
12390     Captures.push_back(NewCap);
12391   }
12392   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12393 
12394   // If the user wrote a function type in some form, try to use that.
12395   if (!BSI->FunctionType.isNull()) {
12396     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12397 
12398     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12399     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12400 
12401     // Turn protoless block types into nullary block types.
12402     if (isa<FunctionNoProtoType>(FTy)) {
12403       FunctionProtoType::ExtProtoInfo EPI;
12404       EPI.ExtInfo = Ext;
12405       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12406 
12407     // Otherwise, if we don't need to change anything about the function type,
12408     // preserve its sugar structure.
12409     } else if (FTy->getReturnType() == RetTy &&
12410                (!NoReturn || FTy->getNoReturnAttr())) {
12411       BlockTy = BSI->FunctionType;
12412 
12413     // Otherwise, make the minimal modifications to the function type.
12414     } else {
12415       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12416       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12417       EPI.TypeQuals = 0; // FIXME: silently?
12418       EPI.ExtInfo = Ext;
12419       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12420     }
12421 
12422   // If we don't have a function type, just build one from nothing.
12423   } else {
12424     FunctionProtoType::ExtProtoInfo EPI;
12425     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12426     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12427   }
12428 
12429   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12430   BlockTy = Context.getBlockPointerType(BlockTy);
12431 
12432   // If needed, diagnose invalid gotos and switches in the block.
12433   if (getCurFunction()->NeedsScopeChecking() &&
12434       !PP.isCodeCompletionEnabled())
12435     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12436 
12437   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12438 
12439   // Try to apply the named return value optimization. We have to check again
12440   // if we can do this, though, because blocks keep return statements around
12441   // to deduce an implicit return type.
12442   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12443       !BSI->TheDecl->isDependentContext())
12444     computeNRVO(Body, BSI);
12445 
12446   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12447   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12448   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12449 
12450   // If the block isn't obviously global, i.e. it captures anything at
12451   // all, then we need to do a few things in the surrounding context:
12452   if (Result->getBlockDecl()->hasCaptures()) {
12453     // First, this expression has a new cleanup object.
12454     ExprCleanupObjects.push_back(Result->getBlockDecl());
12455     Cleanup.setExprNeedsCleanups(true);
12456 
12457     // It also gets a branch-protected scope if any of the captured
12458     // variables needs destruction.
12459     for (const auto &CI : Result->getBlockDecl()->captures()) {
12460       const VarDecl *var = CI.getVariable();
12461       if (var->getType().isDestructedType() != QualType::DK_none) {
12462         getCurFunction()->setHasBranchProtectedScope();
12463         break;
12464       }
12465     }
12466   }
12467 
12468   return Result;
12469 }
12470 
12471 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12472                             SourceLocation RPLoc) {
12473   TypeSourceInfo *TInfo;
12474   GetTypeFromParser(Ty, &TInfo);
12475   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12476 }
12477 
12478 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12479                                 Expr *E, TypeSourceInfo *TInfo,
12480                                 SourceLocation RPLoc) {
12481   Expr *OrigExpr = E;
12482   bool IsMS = false;
12483 
12484   // CUDA device code does not support varargs.
12485   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12486     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12487       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12488       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12489         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12490     }
12491   }
12492 
12493   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12494   // as Microsoft ABI on an actual Microsoft platform, where
12495   // __builtin_ms_va_list and __builtin_va_list are the same.)
12496   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12497       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12498     QualType MSVaListType = Context.getBuiltinMSVaListType();
12499     if (Context.hasSameType(MSVaListType, E->getType())) {
12500       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12501         return ExprError();
12502       IsMS = true;
12503     }
12504   }
12505 
12506   // Get the va_list type
12507   QualType VaListType = Context.getBuiltinVaListType();
12508   if (!IsMS) {
12509     if (VaListType->isArrayType()) {
12510       // Deal with implicit array decay; for example, on x86-64,
12511       // va_list is an array, but it's supposed to decay to
12512       // a pointer for va_arg.
12513       VaListType = Context.getArrayDecayedType(VaListType);
12514       // Make sure the input expression also decays appropriately.
12515       ExprResult Result = UsualUnaryConversions(E);
12516       if (Result.isInvalid())
12517         return ExprError();
12518       E = Result.get();
12519     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12520       // If va_list is a record type and we are compiling in C++ mode,
12521       // check the argument using reference binding.
12522       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12523           Context, Context.getLValueReferenceType(VaListType), false);
12524       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12525       if (Init.isInvalid())
12526         return ExprError();
12527       E = Init.getAs<Expr>();
12528     } else {
12529       // Otherwise, the va_list argument must be an l-value because
12530       // it is modified by va_arg.
12531       if (!E->isTypeDependent() &&
12532           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12533         return ExprError();
12534     }
12535   }
12536 
12537   if (!IsMS && !E->isTypeDependent() &&
12538       !Context.hasSameType(VaListType, E->getType()))
12539     return ExprError(Diag(E->getLocStart(),
12540                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12541       << OrigExpr->getType() << E->getSourceRange());
12542 
12543   if (!TInfo->getType()->isDependentType()) {
12544     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12545                             diag::err_second_parameter_to_va_arg_incomplete,
12546                             TInfo->getTypeLoc()))
12547       return ExprError();
12548 
12549     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12550                                TInfo->getType(),
12551                                diag::err_second_parameter_to_va_arg_abstract,
12552                                TInfo->getTypeLoc()))
12553       return ExprError();
12554 
12555     if (!TInfo->getType().isPODType(Context)) {
12556       Diag(TInfo->getTypeLoc().getBeginLoc(),
12557            TInfo->getType()->isObjCLifetimeType()
12558              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12559              : diag::warn_second_parameter_to_va_arg_not_pod)
12560         << TInfo->getType()
12561         << TInfo->getTypeLoc().getSourceRange();
12562     }
12563 
12564     // Check for va_arg where arguments of the given type will be promoted
12565     // (i.e. this va_arg is guaranteed to have undefined behavior).
12566     QualType PromoteType;
12567     if (TInfo->getType()->isPromotableIntegerType()) {
12568       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12569       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12570         PromoteType = QualType();
12571     }
12572     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12573       PromoteType = Context.DoubleTy;
12574     if (!PromoteType.isNull())
12575       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12576                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12577                           << TInfo->getType()
12578                           << PromoteType
12579                           << TInfo->getTypeLoc().getSourceRange());
12580   }
12581 
12582   QualType T = TInfo->getType().getNonLValueExprType(Context);
12583   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12584 }
12585 
12586 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12587   // The type of __null will be int or long, depending on the size of
12588   // pointers on the target.
12589   QualType Ty;
12590   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12591   if (pw == Context.getTargetInfo().getIntWidth())
12592     Ty = Context.IntTy;
12593   else if (pw == Context.getTargetInfo().getLongWidth())
12594     Ty = Context.LongTy;
12595   else if (pw == Context.getTargetInfo().getLongLongWidth())
12596     Ty = Context.LongLongTy;
12597   else {
12598     llvm_unreachable("I don't know size of pointer!");
12599   }
12600 
12601   return new (Context) GNUNullExpr(Ty, TokenLoc);
12602 }
12603 
12604 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12605                                               bool Diagnose) {
12606   if (!getLangOpts().ObjC1)
12607     return false;
12608 
12609   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12610   if (!PT)
12611     return false;
12612 
12613   if (!PT->isObjCIdType()) {
12614     // Check if the destination is the 'NSString' interface.
12615     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12616     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12617       return false;
12618   }
12619 
12620   // Ignore any parens, implicit casts (should only be
12621   // array-to-pointer decays), and not-so-opaque values.  The last is
12622   // important for making this trigger for property assignments.
12623   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12624   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12625     if (OV->getSourceExpr())
12626       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12627 
12628   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12629   if (!SL || !SL->isAscii())
12630     return false;
12631   if (Diagnose) {
12632     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12633       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12634     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12635   }
12636   return true;
12637 }
12638 
12639 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12640                                               const Expr *SrcExpr) {
12641   if (!DstType->isFunctionPointerType() ||
12642       !SrcExpr->getType()->isFunctionType())
12643     return false;
12644 
12645   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12646   if (!DRE)
12647     return false;
12648 
12649   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12650   if (!FD)
12651     return false;
12652 
12653   return !S.checkAddressOfFunctionIsAvailable(FD,
12654                                               /*Complain=*/true,
12655                                               SrcExpr->getLocStart());
12656 }
12657 
12658 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12659                                     SourceLocation Loc,
12660                                     QualType DstType, QualType SrcType,
12661                                     Expr *SrcExpr, AssignmentAction Action,
12662                                     bool *Complained) {
12663   if (Complained)
12664     *Complained = false;
12665 
12666   // Decode the result (notice that AST's are still created for extensions).
12667   bool CheckInferredResultType = false;
12668   bool isInvalid = false;
12669   unsigned DiagKind = 0;
12670   FixItHint Hint;
12671   ConversionFixItGenerator ConvHints;
12672   bool MayHaveConvFixit = false;
12673   bool MayHaveFunctionDiff = false;
12674   const ObjCInterfaceDecl *IFace = nullptr;
12675   const ObjCProtocolDecl *PDecl = nullptr;
12676 
12677   switch (ConvTy) {
12678   case Compatible:
12679       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12680       return false;
12681 
12682   case PointerToInt:
12683     DiagKind = diag::ext_typecheck_convert_pointer_int;
12684     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12685     MayHaveConvFixit = true;
12686     break;
12687   case IntToPointer:
12688     DiagKind = diag::ext_typecheck_convert_int_pointer;
12689     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12690     MayHaveConvFixit = true;
12691     break;
12692   case IncompatiblePointer:
12693     if (Action == AA_Passing_CFAudited)
12694       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12695     else if (SrcType->isFunctionPointerType() &&
12696              DstType->isFunctionPointerType())
12697       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12698     else
12699       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12700 
12701     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12702       SrcType->isObjCObjectPointerType();
12703     if (Hint.isNull() && !CheckInferredResultType) {
12704       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12705     }
12706     else if (CheckInferredResultType) {
12707       SrcType = SrcType.getUnqualifiedType();
12708       DstType = DstType.getUnqualifiedType();
12709     }
12710     MayHaveConvFixit = true;
12711     break;
12712   case IncompatiblePointerSign:
12713     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12714     break;
12715   case FunctionVoidPointer:
12716     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12717     break;
12718   case IncompatiblePointerDiscardsQualifiers: {
12719     // Perform array-to-pointer decay if necessary.
12720     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12721 
12722     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12723     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12724     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12725       DiagKind = diag::err_typecheck_incompatible_address_space;
12726       break;
12727 
12728 
12729     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12730       DiagKind = diag::err_typecheck_incompatible_ownership;
12731       break;
12732     }
12733 
12734     llvm_unreachable("unknown error case for discarding qualifiers!");
12735     // fallthrough
12736   }
12737   case CompatiblePointerDiscardsQualifiers:
12738     // If the qualifiers lost were because we were applying the
12739     // (deprecated) C++ conversion from a string literal to a char*
12740     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12741     // Ideally, this check would be performed in
12742     // checkPointerTypesForAssignment. However, that would require a
12743     // bit of refactoring (so that the second argument is an
12744     // expression, rather than a type), which should be done as part
12745     // of a larger effort to fix checkPointerTypesForAssignment for
12746     // C++ semantics.
12747     if (getLangOpts().CPlusPlus &&
12748         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12749       return false;
12750     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12751     break;
12752   case IncompatibleNestedPointerQualifiers:
12753     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12754     break;
12755   case IntToBlockPointer:
12756     DiagKind = diag::err_int_to_block_pointer;
12757     break;
12758   case IncompatibleBlockPointer:
12759     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12760     break;
12761   case IncompatibleObjCQualifiedId: {
12762     if (SrcType->isObjCQualifiedIdType()) {
12763       const ObjCObjectPointerType *srcOPT =
12764                 SrcType->getAs<ObjCObjectPointerType>();
12765       for (auto *srcProto : srcOPT->quals()) {
12766         PDecl = srcProto;
12767         break;
12768       }
12769       if (const ObjCInterfaceType *IFaceT =
12770             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12771         IFace = IFaceT->getDecl();
12772     }
12773     else if (DstType->isObjCQualifiedIdType()) {
12774       const ObjCObjectPointerType *dstOPT =
12775         DstType->getAs<ObjCObjectPointerType>();
12776       for (auto *dstProto : dstOPT->quals()) {
12777         PDecl = dstProto;
12778         break;
12779       }
12780       if (const ObjCInterfaceType *IFaceT =
12781             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12782         IFace = IFaceT->getDecl();
12783     }
12784     DiagKind = diag::warn_incompatible_qualified_id;
12785     break;
12786   }
12787   case IncompatibleVectors:
12788     DiagKind = diag::warn_incompatible_vectors;
12789     break;
12790   case IncompatibleObjCWeakRef:
12791     DiagKind = diag::err_arc_weak_unavailable_assign;
12792     break;
12793   case Incompatible:
12794     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12795       if (Complained)
12796         *Complained = true;
12797       return true;
12798     }
12799 
12800     DiagKind = diag::err_typecheck_convert_incompatible;
12801     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12802     MayHaveConvFixit = true;
12803     isInvalid = true;
12804     MayHaveFunctionDiff = true;
12805     break;
12806   }
12807 
12808   QualType FirstType, SecondType;
12809   switch (Action) {
12810   case AA_Assigning:
12811   case AA_Initializing:
12812     // The destination type comes first.
12813     FirstType = DstType;
12814     SecondType = SrcType;
12815     break;
12816 
12817   case AA_Returning:
12818   case AA_Passing:
12819   case AA_Passing_CFAudited:
12820   case AA_Converting:
12821   case AA_Sending:
12822   case AA_Casting:
12823     // The source type comes first.
12824     FirstType = SrcType;
12825     SecondType = DstType;
12826     break;
12827   }
12828 
12829   PartialDiagnostic FDiag = PDiag(DiagKind);
12830   if (Action == AA_Passing_CFAudited)
12831     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12832   else
12833     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12834 
12835   // If we can fix the conversion, suggest the FixIts.
12836   assert(ConvHints.isNull() || Hint.isNull());
12837   if (!ConvHints.isNull()) {
12838     for (FixItHint &H : ConvHints.Hints)
12839       FDiag << H;
12840   } else {
12841     FDiag << Hint;
12842   }
12843   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12844 
12845   if (MayHaveFunctionDiff)
12846     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12847 
12848   Diag(Loc, FDiag);
12849   if (DiagKind == diag::warn_incompatible_qualified_id &&
12850       PDecl && IFace && !IFace->hasDefinition())
12851       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12852         << IFace->getName() << PDecl->getName();
12853 
12854   if (SecondType == Context.OverloadTy)
12855     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12856                               FirstType, /*TakingAddress=*/true);
12857 
12858   if (CheckInferredResultType)
12859     EmitRelatedResultTypeNote(SrcExpr);
12860 
12861   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12862     EmitRelatedResultTypeNoteForReturn(DstType);
12863 
12864   if (Complained)
12865     *Complained = true;
12866   return isInvalid;
12867 }
12868 
12869 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12870                                                  llvm::APSInt *Result) {
12871   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12872   public:
12873     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12874       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12875     }
12876   } Diagnoser;
12877 
12878   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12879 }
12880 
12881 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12882                                                  llvm::APSInt *Result,
12883                                                  unsigned DiagID,
12884                                                  bool AllowFold) {
12885   class IDDiagnoser : public VerifyICEDiagnoser {
12886     unsigned DiagID;
12887 
12888   public:
12889     IDDiagnoser(unsigned DiagID)
12890       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12891 
12892     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12893       S.Diag(Loc, DiagID) << SR;
12894     }
12895   } Diagnoser(DiagID);
12896 
12897   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12898 }
12899 
12900 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12901                                             SourceRange SR) {
12902   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12903 }
12904 
12905 ExprResult
12906 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12907                                       VerifyICEDiagnoser &Diagnoser,
12908                                       bool AllowFold) {
12909   SourceLocation DiagLoc = E->getLocStart();
12910 
12911   if (getLangOpts().CPlusPlus11) {
12912     // C++11 [expr.const]p5:
12913     //   If an expression of literal class type is used in a context where an
12914     //   integral constant expression is required, then that class type shall
12915     //   have a single non-explicit conversion function to an integral or
12916     //   unscoped enumeration type
12917     ExprResult Converted;
12918     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12919     public:
12920       CXX11ConvertDiagnoser(bool Silent)
12921           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12922                                 Silent, true) {}
12923 
12924       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12925                                            QualType T) override {
12926         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12927       }
12928 
12929       SemaDiagnosticBuilder diagnoseIncomplete(
12930           Sema &S, SourceLocation Loc, QualType T) override {
12931         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12932       }
12933 
12934       SemaDiagnosticBuilder diagnoseExplicitConv(
12935           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12936         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12937       }
12938 
12939       SemaDiagnosticBuilder noteExplicitConv(
12940           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12941         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12942                  << ConvTy->isEnumeralType() << ConvTy;
12943       }
12944 
12945       SemaDiagnosticBuilder diagnoseAmbiguous(
12946           Sema &S, SourceLocation Loc, QualType T) override {
12947         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12948       }
12949 
12950       SemaDiagnosticBuilder noteAmbiguous(
12951           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12952         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12953                  << ConvTy->isEnumeralType() << ConvTy;
12954       }
12955 
12956       SemaDiagnosticBuilder diagnoseConversion(
12957           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12958         llvm_unreachable("conversion functions are permitted");
12959       }
12960     } ConvertDiagnoser(Diagnoser.Suppress);
12961 
12962     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12963                                                     ConvertDiagnoser);
12964     if (Converted.isInvalid())
12965       return Converted;
12966     E = Converted.get();
12967     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12968       return ExprError();
12969   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12970     // An ICE must be of integral or unscoped enumeration type.
12971     if (!Diagnoser.Suppress)
12972       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12973     return ExprError();
12974   }
12975 
12976   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12977   // in the non-ICE case.
12978   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12979     if (Result)
12980       *Result = E->EvaluateKnownConstInt(Context);
12981     return E;
12982   }
12983 
12984   Expr::EvalResult EvalResult;
12985   SmallVector<PartialDiagnosticAt, 8> Notes;
12986   EvalResult.Diag = &Notes;
12987 
12988   // Try to evaluate the expression, and produce diagnostics explaining why it's
12989   // not a constant expression as a side-effect.
12990   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12991                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12992 
12993   // In C++11, we can rely on diagnostics being produced for any expression
12994   // which is not a constant expression. If no diagnostics were produced, then
12995   // this is a constant expression.
12996   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12997     if (Result)
12998       *Result = EvalResult.Val.getInt();
12999     return E;
13000   }
13001 
13002   // If our only note is the usual "invalid subexpression" note, just point
13003   // the caret at its location rather than producing an essentially
13004   // redundant note.
13005   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13006         diag::note_invalid_subexpr_in_const_expr) {
13007     DiagLoc = Notes[0].first;
13008     Notes.clear();
13009   }
13010 
13011   if (!Folded || !AllowFold) {
13012     if (!Diagnoser.Suppress) {
13013       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13014       for (const PartialDiagnosticAt &Note : Notes)
13015         Diag(Note.first, Note.second);
13016     }
13017 
13018     return ExprError();
13019   }
13020 
13021   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13022   for (const PartialDiagnosticAt &Note : Notes)
13023     Diag(Note.first, Note.second);
13024 
13025   if (Result)
13026     *Result = EvalResult.Val.getInt();
13027   return E;
13028 }
13029 
13030 namespace {
13031   // Handle the case where we conclude a expression which we speculatively
13032   // considered to be unevaluated is actually evaluated.
13033   class TransformToPE : public TreeTransform<TransformToPE> {
13034     typedef TreeTransform<TransformToPE> BaseTransform;
13035 
13036   public:
13037     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13038 
13039     // Make sure we redo semantic analysis
13040     bool AlwaysRebuild() { return true; }
13041 
13042     // Make sure we handle LabelStmts correctly.
13043     // FIXME: This does the right thing, but maybe we need a more general
13044     // fix to TreeTransform?
13045     StmtResult TransformLabelStmt(LabelStmt *S) {
13046       S->getDecl()->setStmt(nullptr);
13047       return BaseTransform::TransformLabelStmt(S);
13048     }
13049 
13050     // We need to special-case DeclRefExprs referring to FieldDecls which
13051     // are not part of a member pointer formation; normal TreeTransforming
13052     // doesn't catch this case because of the way we represent them in the AST.
13053     // FIXME: This is a bit ugly; is it really the best way to handle this
13054     // case?
13055     //
13056     // Error on DeclRefExprs referring to FieldDecls.
13057     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13058       if (isa<FieldDecl>(E->getDecl()) &&
13059           !SemaRef.isUnevaluatedContext())
13060         return SemaRef.Diag(E->getLocation(),
13061                             diag::err_invalid_non_static_member_use)
13062             << E->getDecl() << E->getSourceRange();
13063 
13064       return BaseTransform::TransformDeclRefExpr(E);
13065     }
13066 
13067     // Exception: filter out member pointer formation
13068     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13069       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13070         return E;
13071 
13072       return BaseTransform::TransformUnaryOperator(E);
13073     }
13074 
13075     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13076       // Lambdas never need to be transformed.
13077       return E;
13078     }
13079   };
13080 }
13081 
13082 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13083   assert(isUnevaluatedContext() &&
13084          "Should only transform unevaluated expressions");
13085   ExprEvalContexts.back().Context =
13086       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13087   if (isUnevaluatedContext())
13088     return E;
13089   return TransformToPE(*this).TransformExpr(E);
13090 }
13091 
13092 void
13093 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13094                                       Decl *LambdaContextDecl,
13095                                       bool IsDecltype) {
13096   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13097                                 LambdaContextDecl, IsDecltype);
13098   Cleanup.reset();
13099   if (!MaybeODRUseExprs.empty())
13100     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13101 }
13102 
13103 void
13104 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13105                                       ReuseLambdaContextDecl_t,
13106                                       bool IsDecltype) {
13107   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13108   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13109 }
13110 
13111 void Sema::PopExpressionEvaluationContext() {
13112   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13113   unsigned NumTypos = Rec.NumTypos;
13114 
13115   if (!Rec.Lambdas.empty()) {
13116     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13117       unsigned D;
13118       if (Rec.isUnevaluated()) {
13119         // C++11 [expr.prim.lambda]p2:
13120         //   A lambda-expression shall not appear in an unevaluated operand
13121         //   (Clause 5).
13122         D = diag::err_lambda_unevaluated_operand;
13123       } else {
13124         // C++1y [expr.const]p2:
13125         //   A conditional-expression e is a core constant expression unless the
13126         //   evaluation of e, following the rules of the abstract machine, would
13127         //   evaluate [...] a lambda-expression.
13128         D = diag::err_lambda_in_constant_expression;
13129       }
13130 
13131       // C++1z allows lambda expressions as core constant expressions.
13132       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13133       // 1607) from appearing within template-arguments and array-bounds that
13134       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13135       // unevaluated contexts) might lift some of these restrictions in a
13136       // future version.
13137       if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13138         for (const auto *L : Rec.Lambdas)
13139           Diag(L->getLocStart(), D);
13140     } else {
13141       // Mark the capture expressions odr-used. This was deferred
13142       // during lambda expression creation.
13143       for (auto *Lambda : Rec.Lambdas) {
13144         for (auto *C : Lambda->capture_inits())
13145           MarkDeclarationsReferencedInExpr(C);
13146       }
13147     }
13148   }
13149 
13150   // When are coming out of an unevaluated context, clear out any
13151   // temporaries that we may have created as part of the evaluation of
13152   // the expression in that context: they aren't relevant because they
13153   // will never be constructed.
13154   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13155     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13156                              ExprCleanupObjects.end());
13157     Cleanup = Rec.ParentCleanup;
13158     CleanupVarDeclMarking();
13159     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13160   // Otherwise, merge the contexts together.
13161   } else {
13162     Cleanup.mergeFrom(Rec.ParentCleanup);
13163     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13164                             Rec.SavedMaybeODRUseExprs.end());
13165   }
13166 
13167   // Pop the current expression evaluation context off the stack.
13168   ExprEvalContexts.pop_back();
13169 
13170   if (!ExprEvalContexts.empty())
13171     ExprEvalContexts.back().NumTypos += NumTypos;
13172   else
13173     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13174                             "last ExpressionEvaluationContextRecord");
13175 }
13176 
13177 void Sema::DiscardCleanupsInEvaluationContext() {
13178   ExprCleanupObjects.erase(
13179          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13180          ExprCleanupObjects.end());
13181   Cleanup.reset();
13182   MaybeODRUseExprs.clear();
13183 }
13184 
13185 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13186   if (!E->getType()->isVariablyModifiedType())
13187     return E;
13188   return TransformToPotentiallyEvaluated(E);
13189 }
13190 
13191 /// Are we within a context in which some evaluation could be performed (be it
13192 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13193 /// captured by C++'s idea of an "unevaluated context".
13194 static bool isEvaluatableContext(Sema &SemaRef) {
13195   switch (SemaRef.ExprEvalContexts.back().Context) {
13196     case Sema::Unevaluated:
13197     case Sema::UnevaluatedAbstract:
13198     case Sema::DiscardedStatement:
13199       // Expressions in this context are never evaluated.
13200       return false;
13201 
13202     case Sema::UnevaluatedList:
13203     case Sema::ConstantEvaluated:
13204     case Sema::PotentiallyEvaluated:
13205       // Expressions in this context could be evaluated.
13206       return true;
13207 
13208     case Sema::PotentiallyEvaluatedIfUsed:
13209       // Referenced declarations will only be used if the construct in the
13210       // containing expression is used, at which point we'll be given another
13211       // turn to mark them.
13212       return false;
13213   }
13214   llvm_unreachable("Invalid context");
13215 }
13216 
13217 /// Are we within a context in which references to resolved functions or to
13218 /// variables result in odr-use?
13219 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13220   // An expression in a template is not really an expression until it's been
13221   // instantiated, so it doesn't trigger odr-use.
13222   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13223     return false;
13224 
13225   switch (SemaRef.ExprEvalContexts.back().Context) {
13226     case Sema::Unevaluated:
13227     case Sema::UnevaluatedList:
13228     case Sema::UnevaluatedAbstract:
13229     case Sema::DiscardedStatement:
13230       return false;
13231 
13232     case Sema::ConstantEvaluated:
13233     case Sema::PotentiallyEvaluated:
13234       return true;
13235 
13236     case Sema::PotentiallyEvaluatedIfUsed:
13237       return false;
13238   }
13239   llvm_unreachable("Invalid context");
13240 }
13241 
13242 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13243   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13244   return Func->isConstexpr() &&
13245          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13246 }
13247 
13248 /// \brief Mark a function referenced, and check whether it is odr-used
13249 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13250 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13251                                   bool MightBeOdrUse) {
13252   assert(Func && "No function?");
13253 
13254   Func->setReferenced();
13255 
13256   // C++11 [basic.def.odr]p3:
13257   //   A function whose name appears as a potentially-evaluated expression is
13258   //   odr-used if it is the unique lookup result or the selected member of a
13259   //   set of overloaded functions [...].
13260   //
13261   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13262   // can just check that here.
13263   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13264 
13265   // Determine whether we require a function definition to exist, per
13266   // C++11 [temp.inst]p3:
13267   //   Unless a function template specialization has been explicitly
13268   //   instantiated or explicitly specialized, the function template
13269   //   specialization is implicitly instantiated when the specialization is
13270   //   referenced in a context that requires a function definition to exist.
13271   //
13272   // That is either when this is an odr-use, or when a usage of a constexpr
13273   // function occurs within an evaluatable context.
13274   bool NeedDefinition =
13275       OdrUse || (isEvaluatableContext(*this) &&
13276                  isImplicitlyDefinableConstexprFunction(Func));
13277 
13278   // C++14 [temp.expl.spec]p6:
13279   //   If a template [...] is explicitly specialized then that specialization
13280   //   shall be declared before the first use of that specialization that would
13281   //   cause an implicit instantiation to take place, in every translation unit
13282   //   in which such a use occurs
13283   if (NeedDefinition &&
13284       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13285        Func->getMemberSpecializationInfo()))
13286     checkSpecializationVisibility(Loc, Func);
13287 
13288   // C++14 [except.spec]p17:
13289   //   An exception-specification is considered to be needed when:
13290   //   - the function is odr-used or, if it appears in an unevaluated operand,
13291   //     would be odr-used if the expression were potentially-evaluated;
13292   //
13293   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13294   // function is a pure virtual function we're calling, and in that case the
13295   // function was selected by overload resolution and we need to resolve its
13296   // exception specification for a different reason.
13297   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13298   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13299     ResolveExceptionSpec(Loc, FPT);
13300 
13301   // If we don't need to mark the function as used, and we don't need to
13302   // try to provide a definition, there's nothing more to do.
13303   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13304       (!NeedDefinition || Func->getBody()))
13305     return;
13306 
13307   // Note that this declaration has been used.
13308   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13309     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13310     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13311       if (Constructor->isDefaultConstructor()) {
13312         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13313           return;
13314         DefineImplicitDefaultConstructor(Loc, Constructor);
13315       } else if (Constructor->isCopyConstructor()) {
13316         DefineImplicitCopyConstructor(Loc, Constructor);
13317       } else if (Constructor->isMoveConstructor()) {
13318         DefineImplicitMoveConstructor(Loc, Constructor);
13319       }
13320     } else if (Constructor->getInheritedConstructor()) {
13321       DefineInheritingConstructor(Loc, Constructor);
13322     }
13323   } else if (CXXDestructorDecl *Destructor =
13324                  dyn_cast<CXXDestructorDecl>(Func)) {
13325     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13326     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13327       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13328         return;
13329       DefineImplicitDestructor(Loc, Destructor);
13330     }
13331     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13332       MarkVTableUsed(Loc, Destructor->getParent());
13333   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13334     if (MethodDecl->isOverloadedOperator() &&
13335         MethodDecl->getOverloadedOperator() == OO_Equal) {
13336       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13337       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13338         if (MethodDecl->isCopyAssignmentOperator())
13339           DefineImplicitCopyAssignment(Loc, MethodDecl);
13340         else if (MethodDecl->isMoveAssignmentOperator())
13341           DefineImplicitMoveAssignment(Loc, MethodDecl);
13342       }
13343     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13344                MethodDecl->getParent()->isLambda()) {
13345       CXXConversionDecl *Conversion =
13346           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13347       if (Conversion->isLambdaToBlockPointerConversion())
13348         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13349       else
13350         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13351     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13352       MarkVTableUsed(Loc, MethodDecl->getParent());
13353   }
13354 
13355   // Recursive functions should be marked when used from another function.
13356   // FIXME: Is this really right?
13357   if (CurContext == Func) return;
13358 
13359   // Implicit instantiation of function templates and member functions of
13360   // class templates.
13361   if (Func->isImplicitlyInstantiable()) {
13362     bool AlreadyInstantiated = false;
13363     SourceLocation PointOfInstantiation = Loc;
13364     if (FunctionTemplateSpecializationInfo *SpecInfo
13365                               = Func->getTemplateSpecializationInfo()) {
13366       if (SpecInfo->getPointOfInstantiation().isInvalid())
13367         SpecInfo->setPointOfInstantiation(Loc);
13368       else if (SpecInfo->getTemplateSpecializationKind()
13369                  == TSK_ImplicitInstantiation) {
13370         AlreadyInstantiated = true;
13371         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13372       }
13373     } else if (MemberSpecializationInfo *MSInfo
13374                                 = Func->getMemberSpecializationInfo()) {
13375       if (MSInfo->getPointOfInstantiation().isInvalid())
13376         MSInfo->setPointOfInstantiation(Loc);
13377       else if (MSInfo->getTemplateSpecializationKind()
13378                  == TSK_ImplicitInstantiation) {
13379         AlreadyInstantiated = true;
13380         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13381       }
13382     }
13383 
13384     if (!AlreadyInstantiated || Func->isConstexpr()) {
13385       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13386           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13387           ActiveTemplateInstantiations.size())
13388         PendingLocalImplicitInstantiations.push_back(
13389             std::make_pair(Func, PointOfInstantiation));
13390       else if (Func->isConstexpr())
13391         // Do not defer instantiations of constexpr functions, to avoid the
13392         // expression evaluator needing to call back into Sema if it sees a
13393         // call to such a function.
13394         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13395       else {
13396         PendingInstantiations.push_back(std::make_pair(Func,
13397                                                        PointOfInstantiation));
13398         // Notify the consumer that a function was implicitly instantiated.
13399         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13400       }
13401     }
13402   } else {
13403     // Walk redefinitions, as some of them may be instantiable.
13404     for (auto i : Func->redecls()) {
13405       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13406         MarkFunctionReferenced(Loc, i, OdrUse);
13407     }
13408   }
13409 
13410   if (!OdrUse) return;
13411 
13412   // Keep track of used but undefined functions.
13413   if (!Func->isDefined()) {
13414     if (mightHaveNonExternalLinkage(Func))
13415       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13416     else if (Func->getMostRecentDecl()->isInlined() &&
13417              !LangOpts.GNUInline &&
13418              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13419       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13420   }
13421 
13422   Func->markUsed(Context);
13423 }
13424 
13425 static void
13426 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13427                                    ValueDecl *var, DeclContext *DC) {
13428   DeclContext *VarDC = var->getDeclContext();
13429 
13430   //  If the parameter still belongs to the translation unit, then
13431   //  we're actually just using one parameter in the declaration of
13432   //  the next.
13433   if (isa<ParmVarDecl>(var) &&
13434       isa<TranslationUnitDecl>(VarDC))
13435     return;
13436 
13437   // For C code, don't diagnose about capture if we're not actually in code
13438   // right now; it's impossible to write a non-constant expression outside of
13439   // function context, so we'll get other (more useful) diagnostics later.
13440   //
13441   // For C++, things get a bit more nasty... it would be nice to suppress this
13442   // diagnostic for certain cases like using a local variable in an array bound
13443   // for a member of a local class, but the correct predicate is not obvious.
13444   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13445     return;
13446 
13447   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13448   unsigned ContextKind = 3; // unknown
13449   if (isa<CXXMethodDecl>(VarDC) &&
13450       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13451     ContextKind = 2;
13452   } else if (isa<FunctionDecl>(VarDC)) {
13453     ContextKind = 0;
13454   } else if (isa<BlockDecl>(VarDC)) {
13455     ContextKind = 1;
13456   }
13457 
13458   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13459     << var << ValueKind << ContextKind << VarDC;
13460   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13461       << var;
13462 
13463   // FIXME: Add additional diagnostic info about class etc. which prevents
13464   // capture.
13465 }
13466 
13467 
13468 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13469                                       bool &SubCapturesAreNested,
13470                                       QualType &CaptureType,
13471                                       QualType &DeclRefType) {
13472    // Check whether we've already captured it.
13473   if (CSI->CaptureMap.count(Var)) {
13474     // If we found a capture, any subcaptures are nested.
13475     SubCapturesAreNested = true;
13476 
13477     // Retrieve the capture type for this variable.
13478     CaptureType = CSI->getCapture(Var).getCaptureType();
13479 
13480     // Compute the type of an expression that refers to this variable.
13481     DeclRefType = CaptureType.getNonReferenceType();
13482 
13483     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13484     // are mutable in the sense that user can change their value - they are
13485     // private instances of the captured declarations.
13486     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13487     if (Cap.isCopyCapture() &&
13488         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13489         !(isa<CapturedRegionScopeInfo>(CSI) &&
13490           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13491       DeclRefType.addConst();
13492     return true;
13493   }
13494   return false;
13495 }
13496 
13497 // Only block literals, captured statements, and lambda expressions can
13498 // capture; other scopes don't work.
13499 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13500                                  SourceLocation Loc,
13501                                  const bool Diagnose, Sema &S) {
13502   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13503     return getLambdaAwareParentOfDeclContext(DC);
13504   else if (Var->hasLocalStorage()) {
13505     if (Diagnose)
13506        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13507   }
13508   return nullptr;
13509 }
13510 
13511 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13512 // certain types of variables (unnamed, variably modified types etc.)
13513 // so check for eligibility.
13514 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13515                                  SourceLocation Loc,
13516                                  const bool Diagnose, Sema &S) {
13517 
13518   bool IsBlock = isa<BlockScopeInfo>(CSI);
13519   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13520 
13521   // Lambdas are not allowed to capture unnamed variables
13522   // (e.g. anonymous unions).
13523   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13524   // assuming that's the intent.
13525   if (IsLambda && !Var->getDeclName()) {
13526     if (Diagnose) {
13527       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13528       S.Diag(Var->getLocation(), diag::note_declared_at);
13529     }
13530     return false;
13531   }
13532 
13533   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13534   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13535     if (Diagnose) {
13536       S.Diag(Loc, diag::err_ref_vm_type);
13537       S.Diag(Var->getLocation(), diag::note_previous_decl)
13538         << Var->getDeclName();
13539     }
13540     return false;
13541   }
13542   // Prohibit structs with flexible array members too.
13543   // We cannot capture what is in the tail end of the struct.
13544   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13545     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13546       if (Diagnose) {
13547         if (IsBlock)
13548           S.Diag(Loc, diag::err_ref_flexarray_type);
13549         else
13550           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13551             << Var->getDeclName();
13552         S.Diag(Var->getLocation(), diag::note_previous_decl)
13553           << Var->getDeclName();
13554       }
13555       return false;
13556     }
13557   }
13558   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13559   // Lambdas and captured statements are not allowed to capture __block
13560   // variables; they don't support the expected semantics.
13561   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13562     if (Diagnose) {
13563       S.Diag(Loc, diag::err_capture_block_variable)
13564         << Var->getDeclName() << !IsLambda;
13565       S.Diag(Var->getLocation(), diag::note_previous_decl)
13566         << Var->getDeclName();
13567     }
13568     return false;
13569   }
13570 
13571   return true;
13572 }
13573 
13574 // Returns true if the capture by block was successful.
13575 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13576                                  SourceLocation Loc,
13577                                  const bool BuildAndDiagnose,
13578                                  QualType &CaptureType,
13579                                  QualType &DeclRefType,
13580                                  const bool Nested,
13581                                  Sema &S) {
13582   Expr *CopyExpr = nullptr;
13583   bool ByRef = false;
13584 
13585   // Blocks are not allowed to capture arrays.
13586   if (CaptureType->isArrayType()) {
13587     if (BuildAndDiagnose) {
13588       S.Diag(Loc, diag::err_ref_array_type);
13589       S.Diag(Var->getLocation(), diag::note_previous_decl)
13590       << Var->getDeclName();
13591     }
13592     return false;
13593   }
13594 
13595   // Forbid the block-capture of autoreleasing variables.
13596   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13597     if (BuildAndDiagnose) {
13598       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13599         << /*block*/ 0;
13600       S.Diag(Var->getLocation(), diag::note_previous_decl)
13601         << Var->getDeclName();
13602     }
13603     return false;
13604   }
13605 
13606   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13607   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13608     // This function finds out whether there is an AttributedType of kind
13609     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13610     // attr_objc_ownership implies __autoreleasing was explicitly specified
13611     // rather than being added implicitly by the compiler.
13612     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13613       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13614         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13615           return true;
13616 
13617         // Peel off AttributedTypes that are not of kind objc_ownership.
13618         Ty = AttrTy->getModifiedType();
13619       }
13620 
13621       return false;
13622     };
13623 
13624     QualType PointeeTy = PT->getPointeeType();
13625 
13626     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13627         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13628         !IsObjCOwnershipAttributedType(PointeeTy)) {
13629       if (BuildAndDiagnose) {
13630         SourceLocation VarLoc = Var->getLocation();
13631         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13632         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13633             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13634         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13635       }
13636     }
13637   }
13638 
13639   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13640   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13641       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13642     // Block capture by reference does not change the capture or
13643     // declaration reference types.
13644     ByRef = true;
13645   } else {
13646     // Block capture by copy introduces 'const'.
13647     CaptureType = CaptureType.getNonReferenceType().withConst();
13648     DeclRefType = CaptureType;
13649 
13650     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13651       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13652         // The capture logic needs the destructor, so make sure we mark it.
13653         // Usually this is unnecessary because most local variables have
13654         // their destructors marked at declaration time, but parameters are
13655         // an exception because it's technically only the call site that
13656         // actually requires the destructor.
13657         if (isa<ParmVarDecl>(Var))
13658           S.FinalizeVarWithDestructor(Var, Record);
13659 
13660         // Enter a new evaluation context to insulate the copy
13661         // full-expression.
13662         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13663 
13664         // According to the blocks spec, the capture of a variable from
13665         // the stack requires a const copy constructor.  This is not true
13666         // of the copy/move done to move a __block variable to the heap.
13667         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13668                                                   DeclRefType.withConst(),
13669                                                   VK_LValue, Loc);
13670 
13671         ExprResult Result
13672           = S.PerformCopyInitialization(
13673               InitializedEntity::InitializeBlock(Var->getLocation(),
13674                                                   CaptureType, false),
13675               Loc, DeclRef);
13676 
13677         // Build a full-expression copy expression if initialization
13678         // succeeded and used a non-trivial constructor.  Recover from
13679         // errors by pretending that the copy isn't necessary.
13680         if (!Result.isInvalid() &&
13681             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13682                 ->isTrivial()) {
13683           Result = S.MaybeCreateExprWithCleanups(Result);
13684           CopyExpr = Result.get();
13685         }
13686       }
13687     }
13688   }
13689 
13690   // Actually capture the variable.
13691   if (BuildAndDiagnose)
13692     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13693                     SourceLocation(), CaptureType, CopyExpr);
13694 
13695   return true;
13696 
13697 }
13698 
13699 
13700 /// \brief Capture the given variable in the captured region.
13701 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13702                                     VarDecl *Var,
13703                                     SourceLocation Loc,
13704                                     const bool BuildAndDiagnose,
13705                                     QualType &CaptureType,
13706                                     QualType &DeclRefType,
13707                                     const bool RefersToCapturedVariable,
13708                                     Sema &S) {
13709   // By default, capture variables by reference.
13710   bool ByRef = true;
13711   // Using an LValue reference type is consistent with Lambdas (see below).
13712   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13713     if (S.IsOpenMPCapturedDecl(Var))
13714       DeclRefType = DeclRefType.getUnqualifiedType();
13715     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13716   }
13717 
13718   if (ByRef)
13719     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13720   else
13721     CaptureType = DeclRefType;
13722 
13723   Expr *CopyExpr = nullptr;
13724   if (BuildAndDiagnose) {
13725     // The current implementation assumes that all variables are captured
13726     // by references. Since there is no capture by copy, no expression
13727     // evaluation will be needed.
13728     RecordDecl *RD = RSI->TheRecordDecl;
13729 
13730     FieldDecl *Field
13731       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13732                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13733                           nullptr, false, ICIS_NoInit);
13734     Field->setImplicit(true);
13735     Field->setAccess(AS_private);
13736     RD->addDecl(Field);
13737 
13738     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13739                                             DeclRefType, VK_LValue, Loc);
13740     Var->setReferenced(true);
13741     Var->markUsed(S.Context);
13742   }
13743 
13744   // Actually capture the variable.
13745   if (BuildAndDiagnose)
13746     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13747                     SourceLocation(), CaptureType, CopyExpr);
13748 
13749 
13750   return true;
13751 }
13752 
13753 /// \brief Create a field within the lambda class for the variable
13754 /// being captured.
13755 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13756                                     QualType FieldType, QualType DeclRefType,
13757                                     SourceLocation Loc,
13758                                     bool RefersToCapturedVariable) {
13759   CXXRecordDecl *Lambda = LSI->Lambda;
13760 
13761   // Build the non-static data member.
13762   FieldDecl *Field
13763     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13764                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13765                         nullptr, false, ICIS_NoInit);
13766   Field->setImplicit(true);
13767   Field->setAccess(AS_private);
13768   Lambda->addDecl(Field);
13769 }
13770 
13771 /// \brief Capture the given variable in the lambda.
13772 static bool captureInLambda(LambdaScopeInfo *LSI,
13773                             VarDecl *Var,
13774                             SourceLocation Loc,
13775                             const bool BuildAndDiagnose,
13776                             QualType &CaptureType,
13777                             QualType &DeclRefType,
13778                             const bool RefersToCapturedVariable,
13779                             const Sema::TryCaptureKind Kind,
13780                             SourceLocation EllipsisLoc,
13781                             const bool IsTopScope,
13782                             Sema &S) {
13783 
13784   // Determine whether we are capturing by reference or by value.
13785   bool ByRef = false;
13786   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13787     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13788   } else {
13789     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13790   }
13791 
13792   // Compute the type of the field that will capture this variable.
13793   if (ByRef) {
13794     // C++11 [expr.prim.lambda]p15:
13795     //   An entity is captured by reference if it is implicitly or
13796     //   explicitly captured but not captured by copy. It is
13797     //   unspecified whether additional unnamed non-static data
13798     //   members are declared in the closure type for entities
13799     //   captured by reference.
13800     //
13801     // FIXME: It is not clear whether we want to build an lvalue reference
13802     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13803     // to do the former, while EDG does the latter. Core issue 1249 will
13804     // clarify, but for now we follow GCC because it's a more permissive and
13805     // easily defensible position.
13806     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13807   } else {
13808     // C++11 [expr.prim.lambda]p14:
13809     //   For each entity captured by copy, an unnamed non-static
13810     //   data member is declared in the closure type. The
13811     //   declaration order of these members is unspecified. The type
13812     //   of such a data member is the type of the corresponding
13813     //   captured entity if the entity is not a reference to an
13814     //   object, or the referenced type otherwise. [Note: If the
13815     //   captured entity is a reference to a function, the
13816     //   corresponding data member is also a reference to a
13817     //   function. - end note ]
13818     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13819       if (!RefType->getPointeeType()->isFunctionType())
13820         CaptureType = RefType->getPointeeType();
13821     }
13822 
13823     // Forbid the lambda copy-capture of autoreleasing variables.
13824     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13825       if (BuildAndDiagnose) {
13826         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13827         S.Diag(Var->getLocation(), diag::note_previous_decl)
13828           << Var->getDeclName();
13829       }
13830       return false;
13831     }
13832 
13833     // Make sure that by-copy captures are of a complete and non-abstract type.
13834     if (BuildAndDiagnose) {
13835       if (!CaptureType->isDependentType() &&
13836           S.RequireCompleteType(Loc, CaptureType,
13837                                 diag::err_capture_of_incomplete_type,
13838                                 Var->getDeclName()))
13839         return false;
13840 
13841       if (S.RequireNonAbstractType(Loc, CaptureType,
13842                                    diag::err_capture_of_abstract_type))
13843         return false;
13844     }
13845   }
13846 
13847   // Capture this variable in the lambda.
13848   if (BuildAndDiagnose)
13849     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13850                             RefersToCapturedVariable);
13851 
13852   // Compute the type of a reference to this captured variable.
13853   if (ByRef)
13854     DeclRefType = CaptureType.getNonReferenceType();
13855   else {
13856     // C++ [expr.prim.lambda]p5:
13857     //   The closure type for a lambda-expression has a public inline
13858     //   function call operator [...]. This function call operator is
13859     //   declared const (9.3.1) if and only if the lambda-expression's
13860     //   parameter-declaration-clause is not followed by mutable.
13861     DeclRefType = CaptureType.getNonReferenceType();
13862     if (!LSI->Mutable && !CaptureType->isReferenceType())
13863       DeclRefType.addConst();
13864   }
13865 
13866   // Add the capture.
13867   if (BuildAndDiagnose)
13868     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13869                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13870 
13871   return true;
13872 }
13873 
13874 bool Sema::tryCaptureVariable(
13875     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13876     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13877     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13878   // An init-capture is notionally from the context surrounding its
13879   // declaration, but its parent DC is the lambda class.
13880   DeclContext *VarDC = Var->getDeclContext();
13881   if (Var->isInitCapture())
13882     VarDC = VarDC->getParent();
13883 
13884   DeclContext *DC = CurContext;
13885   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13886       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13887   // We need to sync up the Declaration Context with the
13888   // FunctionScopeIndexToStopAt
13889   if (FunctionScopeIndexToStopAt) {
13890     unsigned FSIndex = FunctionScopes.size() - 1;
13891     while (FSIndex != MaxFunctionScopesIndex) {
13892       DC = getLambdaAwareParentOfDeclContext(DC);
13893       --FSIndex;
13894     }
13895   }
13896 
13897 
13898   // If the variable is declared in the current context, there is no need to
13899   // capture it.
13900   if (VarDC == DC) return true;
13901 
13902   // Capture global variables if it is required to use private copy of this
13903   // variable.
13904   bool IsGlobal = !Var->hasLocalStorage();
13905   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13906     return true;
13907 
13908   // Walk up the stack to determine whether we can capture the variable,
13909   // performing the "simple" checks that don't depend on type. We stop when
13910   // we've either hit the declared scope of the variable or find an existing
13911   // capture of that variable.  We start from the innermost capturing-entity
13912   // (the DC) and ensure that all intervening capturing-entities
13913   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13914   // declcontext can either capture the variable or have already captured
13915   // the variable.
13916   CaptureType = Var->getType();
13917   DeclRefType = CaptureType.getNonReferenceType();
13918   bool Nested = false;
13919   bool Explicit = (Kind != TryCapture_Implicit);
13920   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13921   do {
13922     // Only block literals, captured statements, and lambda expressions can
13923     // capture; other scopes don't work.
13924     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13925                                                               ExprLoc,
13926                                                               BuildAndDiagnose,
13927                                                               *this);
13928     // We need to check for the parent *first* because, if we *have*
13929     // private-captured a global variable, we need to recursively capture it in
13930     // intermediate blocks, lambdas, etc.
13931     if (!ParentDC) {
13932       if (IsGlobal) {
13933         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13934         break;
13935       }
13936       return true;
13937     }
13938 
13939     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13940     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13941 
13942 
13943     // Check whether we've already captured it.
13944     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13945                                              DeclRefType)) {
13946       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
13947       break;
13948     }
13949     // If we are instantiating a generic lambda call operator body,
13950     // we do not want to capture new variables.  What was captured
13951     // during either a lambdas transformation or initial parsing
13952     // should be used.
13953     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13954       if (BuildAndDiagnose) {
13955         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13956         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13957           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13958           Diag(Var->getLocation(), diag::note_previous_decl)
13959              << Var->getDeclName();
13960           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13961         } else
13962           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13963       }
13964       return true;
13965     }
13966     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13967     // certain types of variables (unnamed, variably modified types etc.)
13968     // so check for eligibility.
13969     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13970        return true;
13971 
13972     // Try to capture variable-length arrays types.
13973     if (Var->getType()->isVariablyModifiedType()) {
13974       // We're going to walk down into the type and look for VLA
13975       // expressions.
13976       QualType QTy = Var->getType();
13977       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13978         QTy = PVD->getOriginalType();
13979       captureVariablyModifiedType(Context, QTy, CSI);
13980     }
13981 
13982     if (getLangOpts().OpenMP) {
13983       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13984         // OpenMP private variables should not be captured in outer scope, so
13985         // just break here. Similarly, global variables that are captured in a
13986         // target region should not be captured outside the scope of the region.
13987         if (RSI->CapRegionKind == CR_OpenMP) {
13988           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13989           // When we detect target captures we are looking from inside the
13990           // target region, therefore we need to propagate the capture from the
13991           // enclosing region. Therefore, the capture is not initially nested.
13992           if (IsTargetCap)
13993             FunctionScopesIndex--;
13994 
13995           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13996             Nested = !IsTargetCap;
13997             DeclRefType = DeclRefType.getUnqualifiedType();
13998             CaptureType = Context.getLValueReferenceType(DeclRefType);
13999             break;
14000           }
14001         }
14002       }
14003     }
14004     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14005       // No capture-default, and this is not an explicit capture
14006       // so cannot capture this variable.
14007       if (BuildAndDiagnose) {
14008         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14009         Diag(Var->getLocation(), diag::note_previous_decl)
14010           << Var->getDeclName();
14011         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14012           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14013                diag::note_lambda_decl);
14014         // FIXME: If we error out because an outer lambda can not implicitly
14015         // capture a variable that an inner lambda explicitly captures, we
14016         // should have the inner lambda do the explicit capture - because
14017         // it makes for cleaner diagnostics later.  This would purely be done
14018         // so that the diagnostic does not misleadingly claim that a variable
14019         // can not be captured by a lambda implicitly even though it is captured
14020         // explicitly.  Suggestion:
14021         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14022         //    at the function head
14023         //  - cache the StartingDeclContext - this must be a lambda
14024         //  - captureInLambda in the innermost lambda the variable.
14025       }
14026       return true;
14027     }
14028 
14029     FunctionScopesIndex--;
14030     DC = ParentDC;
14031     Explicit = false;
14032   } while (!VarDC->Equals(DC));
14033 
14034   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14035   // computing the type of the capture at each step, checking type-specific
14036   // requirements, and adding captures if requested.
14037   // If the variable had already been captured previously, we start capturing
14038   // at the lambda nested within that one.
14039   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14040        ++I) {
14041     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14042 
14043     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14044       if (!captureInBlock(BSI, Var, ExprLoc,
14045                           BuildAndDiagnose, CaptureType,
14046                           DeclRefType, Nested, *this))
14047         return true;
14048       Nested = true;
14049     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14050       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14051                                    BuildAndDiagnose, CaptureType,
14052                                    DeclRefType, Nested, *this))
14053         return true;
14054       Nested = true;
14055     } else {
14056       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14057       if (!captureInLambda(LSI, Var, ExprLoc,
14058                            BuildAndDiagnose, CaptureType,
14059                            DeclRefType, Nested, Kind, EllipsisLoc,
14060                             /*IsTopScope*/I == N - 1, *this))
14061         return true;
14062       Nested = true;
14063     }
14064   }
14065   return false;
14066 }
14067 
14068 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14069                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14070   QualType CaptureType;
14071   QualType DeclRefType;
14072   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14073                             /*BuildAndDiagnose=*/true, CaptureType,
14074                             DeclRefType, nullptr);
14075 }
14076 
14077 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14078   QualType CaptureType;
14079   QualType DeclRefType;
14080   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14081                              /*BuildAndDiagnose=*/false, CaptureType,
14082                              DeclRefType, nullptr);
14083 }
14084 
14085 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14086   QualType CaptureType;
14087   QualType DeclRefType;
14088 
14089   // Determine whether we can capture this variable.
14090   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14091                          /*BuildAndDiagnose=*/false, CaptureType,
14092                          DeclRefType, nullptr))
14093     return QualType();
14094 
14095   return DeclRefType;
14096 }
14097 
14098 
14099 
14100 // If either the type of the variable or the initializer is dependent,
14101 // return false. Otherwise, determine whether the variable is a constant
14102 // expression. Use this if you need to know if a variable that might or
14103 // might not be dependent is truly a constant expression.
14104 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14105     ASTContext &Context) {
14106 
14107   if (Var->getType()->isDependentType())
14108     return false;
14109   const VarDecl *DefVD = nullptr;
14110   Var->getAnyInitializer(DefVD);
14111   if (!DefVD)
14112     return false;
14113   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14114   Expr *Init = cast<Expr>(Eval->Value);
14115   if (Init->isValueDependent())
14116     return false;
14117   return IsVariableAConstantExpression(Var, Context);
14118 }
14119 
14120 
14121 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14122   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14123   // an object that satisfies the requirements for appearing in a
14124   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14125   // is immediately applied."  This function handles the lvalue-to-rvalue
14126   // conversion part.
14127   MaybeODRUseExprs.erase(E->IgnoreParens());
14128 
14129   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14130   // to a variable that is a constant expression, and if so, identify it as
14131   // a reference to a variable that does not involve an odr-use of that
14132   // variable.
14133   if (LambdaScopeInfo *LSI = getCurLambda()) {
14134     Expr *SansParensExpr = E->IgnoreParens();
14135     VarDecl *Var = nullptr;
14136     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14137       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14138     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14139       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14140 
14141     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14142       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14143   }
14144 }
14145 
14146 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14147   Res = CorrectDelayedTyposInExpr(Res);
14148 
14149   if (!Res.isUsable())
14150     return Res;
14151 
14152   // If a constant-expression is a reference to a variable where we delay
14153   // deciding whether it is an odr-use, just assume we will apply the
14154   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14155   // (a non-type template argument), we have special handling anyway.
14156   UpdateMarkingForLValueToRValue(Res.get());
14157   return Res;
14158 }
14159 
14160 void Sema::CleanupVarDeclMarking() {
14161   for (Expr *E : MaybeODRUseExprs) {
14162     VarDecl *Var;
14163     SourceLocation Loc;
14164     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14165       Var = cast<VarDecl>(DRE->getDecl());
14166       Loc = DRE->getLocation();
14167     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14168       Var = cast<VarDecl>(ME->getMemberDecl());
14169       Loc = ME->getMemberLoc();
14170     } else {
14171       llvm_unreachable("Unexpected expression");
14172     }
14173 
14174     MarkVarDeclODRUsed(Var, Loc, *this,
14175                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14176   }
14177 
14178   MaybeODRUseExprs.clear();
14179 }
14180 
14181 
14182 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14183                                     VarDecl *Var, Expr *E) {
14184   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14185          "Invalid Expr argument to DoMarkVarDeclReferenced");
14186   Var->setReferenced();
14187 
14188   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14189 
14190   bool OdrUseContext = isOdrUseContext(SemaRef);
14191   bool NeedDefinition =
14192       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14193                         Var->isUsableInConstantExpressions(SemaRef.Context));
14194 
14195   VarTemplateSpecializationDecl *VarSpec =
14196       dyn_cast<VarTemplateSpecializationDecl>(Var);
14197   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14198          "Can't instantiate a partial template specialization.");
14199 
14200   // If this might be a member specialization of a static data member, check
14201   // the specialization is visible. We already did the checks for variable
14202   // template specializations when we created them.
14203   if (NeedDefinition && TSK != TSK_Undeclared &&
14204       !isa<VarTemplateSpecializationDecl>(Var))
14205     SemaRef.checkSpecializationVisibility(Loc, Var);
14206 
14207   // Perform implicit instantiation of static data members, static data member
14208   // templates of class templates, and variable template specializations. Delay
14209   // instantiations of variable templates, except for those that could be used
14210   // in a constant expression.
14211   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14212     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14213 
14214     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14215       if (Var->getPointOfInstantiation().isInvalid()) {
14216         // This is a modification of an existing AST node. Notify listeners.
14217         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14218           L->StaticDataMemberInstantiated(Var);
14219       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14220         // Don't bother trying to instantiate it again, unless we might need
14221         // its initializer before we get to the end of the TU.
14222         TryInstantiating = false;
14223     }
14224 
14225     if (Var->getPointOfInstantiation().isInvalid())
14226       Var->setTemplateSpecializationKind(TSK, Loc);
14227 
14228     if (TryInstantiating) {
14229       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14230       bool InstantiationDependent = false;
14231       bool IsNonDependent =
14232           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14233                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14234                   : true;
14235 
14236       // Do not instantiate specializations that are still type-dependent.
14237       if (IsNonDependent) {
14238         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14239           // Do not defer instantiations of variables which could be used in a
14240           // constant expression.
14241           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14242         } else {
14243           SemaRef.PendingInstantiations
14244               .push_back(std::make_pair(Var, PointOfInstantiation));
14245         }
14246       }
14247     }
14248   }
14249 
14250   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14251   // the requirements for appearing in a constant expression (5.19) and, if
14252   // it is an object, the lvalue-to-rvalue conversion (4.1)
14253   // is immediately applied."  We check the first part here, and
14254   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14255   // Note that we use the C++11 definition everywhere because nothing in
14256   // C++03 depends on whether we get the C++03 version correct. The second
14257   // part does not apply to references, since they are not objects.
14258   if (OdrUseContext && E &&
14259       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14260     // A reference initialized by a constant expression can never be
14261     // odr-used, so simply ignore it.
14262     if (!Var->getType()->isReferenceType())
14263       SemaRef.MaybeODRUseExprs.insert(E);
14264   } else if (OdrUseContext) {
14265     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14266                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14267   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14268     // If this is a dependent context, we don't need to mark variables as
14269     // odr-used, but we may still need to track them for lambda capture.
14270     // FIXME: Do we also need to do this inside dependent typeid expressions
14271     // (which are modeled as unevaluated at this point)?
14272     const bool RefersToEnclosingScope =
14273         (SemaRef.CurContext != Var->getDeclContext() &&
14274          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14275     if (RefersToEnclosingScope) {
14276       if (LambdaScopeInfo *const LSI =
14277               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14278         // If a variable could potentially be odr-used, defer marking it so
14279         // until we finish analyzing the full expression for any
14280         // lvalue-to-rvalue
14281         // or discarded value conversions that would obviate odr-use.
14282         // Add it to the list of potential captures that will be analyzed
14283         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14284         // unless the variable is a reference that was initialized by a constant
14285         // expression (this will never need to be captured or odr-used).
14286         assert(E && "Capture variable should be used in an expression.");
14287         if (!Var->getType()->isReferenceType() ||
14288             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14289           LSI->addPotentialCapture(E->IgnoreParens());
14290       }
14291     }
14292   }
14293 }
14294 
14295 /// \brief Mark a variable referenced, and check whether it is odr-used
14296 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14297 /// used directly for normal expressions referring to VarDecl.
14298 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14299   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14300 }
14301 
14302 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14303                                Decl *D, Expr *E, bool MightBeOdrUse) {
14304   if (SemaRef.isInOpenMPDeclareTargetContext())
14305     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14306 
14307   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14308     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14309     return;
14310   }
14311 
14312   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14313 
14314   // If this is a call to a method via a cast, also mark the method in the
14315   // derived class used in case codegen can devirtualize the call.
14316   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14317   if (!ME)
14318     return;
14319   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14320   if (!MD)
14321     return;
14322   // Only attempt to devirtualize if this is truly a virtual call.
14323   bool IsVirtualCall = MD->isVirtual() &&
14324                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14325   if (!IsVirtualCall)
14326     return;
14327   const Expr *Base = ME->getBase();
14328   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14329   if (!MostDerivedClassDecl)
14330     return;
14331   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14332   if (!DM || DM->isPure())
14333     return;
14334   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14335 }
14336 
14337 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14338 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14339   // TODO: update this with DR# once a defect report is filed.
14340   // C++11 defect. The address of a pure member should not be an ODR use, even
14341   // if it's a qualified reference.
14342   bool OdrUse = true;
14343   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14344     if (Method->isVirtual())
14345       OdrUse = false;
14346   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14347 }
14348 
14349 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14350 void Sema::MarkMemberReferenced(MemberExpr *E) {
14351   // C++11 [basic.def.odr]p2:
14352   //   A non-overloaded function whose name appears as a potentially-evaluated
14353   //   expression or a member of a set of candidate functions, if selected by
14354   //   overload resolution when referred to from a potentially-evaluated
14355   //   expression, is odr-used, unless it is a pure virtual function and its
14356   //   name is not explicitly qualified.
14357   bool MightBeOdrUse = true;
14358   if (E->performsVirtualDispatch(getLangOpts())) {
14359     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14360       if (Method->isPure())
14361         MightBeOdrUse = false;
14362   }
14363   SourceLocation Loc = E->getMemberLoc().isValid() ?
14364                             E->getMemberLoc() : E->getLocStart();
14365   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14366 }
14367 
14368 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14369 /// marks the declaration referenced, and performs odr-use checking for
14370 /// functions and variables. This method should not be used when building a
14371 /// normal expression which refers to a variable.
14372 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14373                                  bool MightBeOdrUse) {
14374   if (MightBeOdrUse) {
14375     if (auto *VD = dyn_cast<VarDecl>(D)) {
14376       MarkVariableReferenced(Loc, VD);
14377       return;
14378     }
14379   }
14380   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14381     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14382     return;
14383   }
14384   D->setReferenced();
14385 }
14386 
14387 namespace {
14388   // Mark all of the declarations used by a type as referenced.
14389   // FIXME: Not fully implemented yet! We need to have a better understanding
14390   // of when we're entering a context we should not recurse into.
14391   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14392   // TreeTransforms rebuilding the type in a new context. Rather than
14393   // duplicating the TreeTransform logic, we should consider reusing it here.
14394   // Currently that causes problems when rebuilding LambdaExprs.
14395   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14396     Sema &S;
14397     SourceLocation Loc;
14398 
14399   public:
14400     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14401 
14402     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14403 
14404     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14405   };
14406 }
14407 
14408 bool MarkReferencedDecls::TraverseTemplateArgument(
14409     const TemplateArgument &Arg) {
14410   {
14411     // A non-type template argument is a constant-evaluated context.
14412     EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14413     if (Arg.getKind() == TemplateArgument::Declaration) {
14414       if (Decl *D = Arg.getAsDecl())
14415         S.MarkAnyDeclReferenced(Loc, D, true);
14416     } else if (Arg.getKind() == TemplateArgument::Expression) {
14417       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14418     }
14419   }
14420 
14421   return Inherited::TraverseTemplateArgument(Arg);
14422 }
14423 
14424 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14425   MarkReferencedDecls Marker(*this, Loc);
14426   Marker.TraverseType(T);
14427 }
14428 
14429 namespace {
14430   /// \brief Helper class that marks all of the declarations referenced by
14431   /// potentially-evaluated subexpressions as "referenced".
14432   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14433     Sema &S;
14434     bool SkipLocalVariables;
14435 
14436   public:
14437     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14438 
14439     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14440       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14441 
14442     void VisitDeclRefExpr(DeclRefExpr *E) {
14443       // If we were asked not to visit local variables, don't.
14444       if (SkipLocalVariables) {
14445         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14446           if (VD->hasLocalStorage())
14447             return;
14448       }
14449 
14450       S.MarkDeclRefReferenced(E);
14451     }
14452 
14453     void VisitMemberExpr(MemberExpr *E) {
14454       S.MarkMemberReferenced(E);
14455       Inherited::VisitMemberExpr(E);
14456     }
14457 
14458     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14459       S.MarkFunctionReferenced(E->getLocStart(),
14460             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14461       Visit(E->getSubExpr());
14462     }
14463 
14464     void VisitCXXNewExpr(CXXNewExpr *E) {
14465       if (E->getOperatorNew())
14466         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14467       if (E->getOperatorDelete())
14468         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14469       Inherited::VisitCXXNewExpr(E);
14470     }
14471 
14472     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14473       if (E->getOperatorDelete())
14474         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14475       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14476       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14477         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14478         S.MarkFunctionReferenced(E->getLocStart(),
14479                                     S.LookupDestructor(Record));
14480       }
14481 
14482       Inherited::VisitCXXDeleteExpr(E);
14483     }
14484 
14485     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14486       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14487       Inherited::VisitCXXConstructExpr(E);
14488     }
14489 
14490     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14491       Visit(E->getExpr());
14492     }
14493 
14494     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14495       Inherited::VisitImplicitCastExpr(E);
14496 
14497       if (E->getCastKind() == CK_LValueToRValue)
14498         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14499     }
14500   };
14501 }
14502 
14503 /// \brief Mark any declarations that appear within this expression or any
14504 /// potentially-evaluated subexpressions as "referenced".
14505 ///
14506 /// \param SkipLocalVariables If true, don't mark local variables as
14507 /// 'referenced'.
14508 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14509                                             bool SkipLocalVariables) {
14510   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14511 }
14512 
14513 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14514 /// of the program being compiled.
14515 ///
14516 /// This routine emits the given diagnostic when the code currently being
14517 /// type-checked is "potentially evaluated", meaning that there is a
14518 /// possibility that the code will actually be executable. Code in sizeof()
14519 /// expressions, code used only during overload resolution, etc., are not
14520 /// potentially evaluated. This routine will suppress such diagnostics or,
14521 /// in the absolutely nutty case of potentially potentially evaluated
14522 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14523 /// later.
14524 ///
14525 /// This routine should be used for all diagnostics that describe the run-time
14526 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14527 /// Failure to do so will likely result in spurious diagnostics or failures
14528 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14529 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14530                                const PartialDiagnostic &PD) {
14531   switch (ExprEvalContexts.back().Context) {
14532   case Unevaluated:
14533   case UnevaluatedList:
14534   case UnevaluatedAbstract:
14535   case DiscardedStatement:
14536     // The argument will never be evaluated, so don't complain.
14537     break;
14538 
14539   case ConstantEvaluated:
14540     // Relevant diagnostics should be produced by constant evaluation.
14541     break;
14542 
14543   case PotentiallyEvaluated:
14544   case PotentiallyEvaluatedIfUsed:
14545     if (Statement && getCurFunctionOrMethodDecl()) {
14546       FunctionScopes.back()->PossiblyUnreachableDiags.
14547         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14548     }
14549     else
14550       Diag(Loc, PD);
14551 
14552     return true;
14553   }
14554 
14555   return false;
14556 }
14557 
14558 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14559                                CallExpr *CE, FunctionDecl *FD) {
14560   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14561     return false;
14562 
14563   // If we're inside a decltype's expression, don't check for a valid return
14564   // type or construct temporaries until we know whether this is the last call.
14565   if (ExprEvalContexts.back().IsDecltype) {
14566     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14567     return false;
14568   }
14569 
14570   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14571     FunctionDecl *FD;
14572     CallExpr *CE;
14573 
14574   public:
14575     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14576       : FD(FD), CE(CE) { }
14577 
14578     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14579       if (!FD) {
14580         S.Diag(Loc, diag::err_call_incomplete_return)
14581           << T << CE->getSourceRange();
14582         return;
14583       }
14584 
14585       S.Diag(Loc, diag::err_call_function_incomplete_return)
14586         << CE->getSourceRange() << FD->getDeclName() << T;
14587       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14588           << FD->getDeclName();
14589     }
14590   } Diagnoser(FD, CE);
14591 
14592   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14593     return true;
14594 
14595   return false;
14596 }
14597 
14598 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14599 // will prevent this condition from triggering, which is what we want.
14600 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14601   SourceLocation Loc;
14602 
14603   unsigned diagnostic = diag::warn_condition_is_assignment;
14604   bool IsOrAssign = false;
14605 
14606   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14607     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14608       return;
14609 
14610     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14611 
14612     // Greylist some idioms by putting them into a warning subcategory.
14613     if (ObjCMessageExpr *ME
14614           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14615       Selector Sel = ME->getSelector();
14616 
14617       // self = [<foo> init...]
14618       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14619         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14620 
14621       // <foo> = [<bar> nextObject]
14622       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14623         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14624     }
14625 
14626     Loc = Op->getOperatorLoc();
14627   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14628     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14629       return;
14630 
14631     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14632     Loc = Op->getOperatorLoc();
14633   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14634     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14635   else {
14636     // Not an assignment.
14637     return;
14638   }
14639 
14640   Diag(Loc, diagnostic) << E->getSourceRange();
14641 
14642   SourceLocation Open = E->getLocStart();
14643   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14644   Diag(Loc, diag::note_condition_assign_silence)
14645         << FixItHint::CreateInsertion(Open, "(")
14646         << FixItHint::CreateInsertion(Close, ")");
14647 
14648   if (IsOrAssign)
14649     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14650       << FixItHint::CreateReplacement(Loc, "!=");
14651   else
14652     Diag(Loc, diag::note_condition_assign_to_comparison)
14653       << FixItHint::CreateReplacement(Loc, "==");
14654 }
14655 
14656 /// \brief Redundant parentheses over an equality comparison can indicate
14657 /// that the user intended an assignment used as condition.
14658 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14659   // Don't warn if the parens came from a macro.
14660   SourceLocation parenLoc = ParenE->getLocStart();
14661   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14662     return;
14663   // Don't warn for dependent expressions.
14664   if (ParenE->isTypeDependent())
14665     return;
14666 
14667   Expr *E = ParenE->IgnoreParens();
14668 
14669   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14670     if (opE->getOpcode() == BO_EQ &&
14671         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14672                                                            == Expr::MLV_Valid) {
14673       SourceLocation Loc = opE->getOperatorLoc();
14674 
14675       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14676       SourceRange ParenERange = ParenE->getSourceRange();
14677       Diag(Loc, diag::note_equality_comparison_silence)
14678         << FixItHint::CreateRemoval(ParenERange.getBegin())
14679         << FixItHint::CreateRemoval(ParenERange.getEnd());
14680       Diag(Loc, diag::note_equality_comparison_to_assign)
14681         << FixItHint::CreateReplacement(Loc, "=");
14682     }
14683 }
14684 
14685 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14686                                        bool IsConstexpr) {
14687   DiagnoseAssignmentAsCondition(E);
14688   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14689     DiagnoseEqualityWithExtraParens(parenE);
14690 
14691   ExprResult result = CheckPlaceholderExpr(E);
14692   if (result.isInvalid()) return ExprError();
14693   E = result.get();
14694 
14695   if (!E->isTypeDependent()) {
14696     if (getLangOpts().CPlusPlus)
14697       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14698 
14699     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14700     if (ERes.isInvalid())
14701       return ExprError();
14702     E = ERes.get();
14703 
14704     QualType T = E->getType();
14705     if (!T->isScalarType()) { // C99 6.8.4.1p1
14706       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14707         << T << E->getSourceRange();
14708       return ExprError();
14709     }
14710     CheckBoolLikeConversion(E, Loc);
14711   }
14712 
14713   return E;
14714 }
14715 
14716 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14717                                            Expr *SubExpr, ConditionKind CK) {
14718   // Empty conditions are valid in for-statements.
14719   if (!SubExpr)
14720     return ConditionResult();
14721 
14722   ExprResult Cond;
14723   switch (CK) {
14724   case ConditionKind::Boolean:
14725     Cond = CheckBooleanCondition(Loc, SubExpr);
14726     break;
14727 
14728   case ConditionKind::ConstexprIf:
14729     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14730     break;
14731 
14732   case ConditionKind::Switch:
14733     Cond = CheckSwitchCondition(Loc, SubExpr);
14734     break;
14735   }
14736   if (Cond.isInvalid())
14737     return ConditionError();
14738 
14739   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14740   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14741   if (!FullExpr.get())
14742     return ConditionError();
14743 
14744   return ConditionResult(*this, nullptr, FullExpr,
14745                          CK == ConditionKind::ConstexprIf);
14746 }
14747 
14748 namespace {
14749   /// A visitor for rebuilding a call to an __unknown_any expression
14750   /// to have an appropriate type.
14751   struct RebuildUnknownAnyFunction
14752     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14753 
14754     Sema &S;
14755 
14756     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14757 
14758     ExprResult VisitStmt(Stmt *S) {
14759       llvm_unreachable("unexpected statement!");
14760     }
14761 
14762     ExprResult VisitExpr(Expr *E) {
14763       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14764         << E->getSourceRange();
14765       return ExprError();
14766     }
14767 
14768     /// Rebuild an expression which simply semantically wraps another
14769     /// expression which it shares the type and value kind of.
14770     template <class T> ExprResult rebuildSugarExpr(T *E) {
14771       ExprResult SubResult = Visit(E->getSubExpr());
14772       if (SubResult.isInvalid()) return ExprError();
14773 
14774       Expr *SubExpr = SubResult.get();
14775       E->setSubExpr(SubExpr);
14776       E->setType(SubExpr->getType());
14777       E->setValueKind(SubExpr->getValueKind());
14778       assert(E->getObjectKind() == OK_Ordinary);
14779       return E;
14780     }
14781 
14782     ExprResult VisitParenExpr(ParenExpr *E) {
14783       return rebuildSugarExpr(E);
14784     }
14785 
14786     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14787       return rebuildSugarExpr(E);
14788     }
14789 
14790     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14791       ExprResult SubResult = Visit(E->getSubExpr());
14792       if (SubResult.isInvalid()) return ExprError();
14793 
14794       Expr *SubExpr = SubResult.get();
14795       E->setSubExpr(SubExpr);
14796       E->setType(S.Context.getPointerType(SubExpr->getType()));
14797       assert(E->getValueKind() == VK_RValue);
14798       assert(E->getObjectKind() == OK_Ordinary);
14799       return E;
14800     }
14801 
14802     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14803       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14804 
14805       E->setType(VD->getType());
14806 
14807       assert(E->getValueKind() == VK_RValue);
14808       if (S.getLangOpts().CPlusPlus &&
14809           !(isa<CXXMethodDecl>(VD) &&
14810             cast<CXXMethodDecl>(VD)->isInstance()))
14811         E->setValueKind(VK_LValue);
14812 
14813       return E;
14814     }
14815 
14816     ExprResult VisitMemberExpr(MemberExpr *E) {
14817       return resolveDecl(E, E->getMemberDecl());
14818     }
14819 
14820     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14821       return resolveDecl(E, E->getDecl());
14822     }
14823   };
14824 }
14825 
14826 /// Given a function expression of unknown-any type, try to rebuild it
14827 /// to have a function type.
14828 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14829   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14830   if (Result.isInvalid()) return ExprError();
14831   return S.DefaultFunctionArrayConversion(Result.get());
14832 }
14833 
14834 namespace {
14835   /// A visitor for rebuilding an expression of type __unknown_anytype
14836   /// into one which resolves the type directly on the referring
14837   /// expression.  Strict preservation of the original source
14838   /// structure is not a goal.
14839   struct RebuildUnknownAnyExpr
14840     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14841 
14842     Sema &S;
14843 
14844     /// The current destination type.
14845     QualType DestType;
14846 
14847     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14848       : S(S), DestType(CastType) {}
14849 
14850     ExprResult VisitStmt(Stmt *S) {
14851       llvm_unreachable("unexpected statement!");
14852     }
14853 
14854     ExprResult VisitExpr(Expr *E) {
14855       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14856         << E->getSourceRange();
14857       return ExprError();
14858     }
14859 
14860     ExprResult VisitCallExpr(CallExpr *E);
14861     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14862 
14863     /// Rebuild an expression which simply semantically wraps another
14864     /// expression which it shares the type and value kind of.
14865     template <class T> ExprResult rebuildSugarExpr(T *E) {
14866       ExprResult SubResult = Visit(E->getSubExpr());
14867       if (SubResult.isInvalid()) return ExprError();
14868       Expr *SubExpr = SubResult.get();
14869       E->setSubExpr(SubExpr);
14870       E->setType(SubExpr->getType());
14871       E->setValueKind(SubExpr->getValueKind());
14872       assert(E->getObjectKind() == OK_Ordinary);
14873       return E;
14874     }
14875 
14876     ExprResult VisitParenExpr(ParenExpr *E) {
14877       return rebuildSugarExpr(E);
14878     }
14879 
14880     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14881       return rebuildSugarExpr(E);
14882     }
14883 
14884     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14885       const PointerType *Ptr = DestType->getAs<PointerType>();
14886       if (!Ptr) {
14887         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14888           << E->getSourceRange();
14889         return ExprError();
14890       }
14891 
14892       if (isa<CallExpr>(E->getSubExpr())) {
14893         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14894           << E->getSourceRange();
14895         return ExprError();
14896       }
14897 
14898       assert(E->getValueKind() == VK_RValue);
14899       assert(E->getObjectKind() == OK_Ordinary);
14900       E->setType(DestType);
14901 
14902       // Build the sub-expression as if it were an object of the pointee type.
14903       DestType = Ptr->getPointeeType();
14904       ExprResult SubResult = Visit(E->getSubExpr());
14905       if (SubResult.isInvalid()) return ExprError();
14906       E->setSubExpr(SubResult.get());
14907       return E;
14908     }
14909 
14910     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14911 
14912     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14913 
14914     ExprResult VisitMemberExpr(MemberExpr *E) {
14915       return resolveDecl(E, E->getMemberDecl());
14916     }
14917 
14918     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14919       return resolveDecl(E, E->getDecl());
14920     }
14921   };
14922 }
14923 
14924 /// Rebuilds a call expression which yielded __unknown_anytype.
14925 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14926   Expr *CalleeExpr = E->getCallee();
14927 
14928   enum FnKind {
14929     FK_MemberFunction,
14930     FK_FunctionPointer,
14931     FK_BlockPointer
14932   };
14933 
14934   FnKind Kind;
14935   QualType CalleeType = CalleeExpr->getType();
14936   if (CalleeType == S.Context.BoundMemberTy) {
14937     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14938     Kind = FK_MemberFunction;
14939     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14940   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14941     CalleeType = Ptr->getPointeeType();
14942     Kind = FK_FunctionPointer;
14943   } else {
14944     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14945     Kind = FK_BlockPointer;
14946   }
14947   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14948 
14949   // Verify that this is a legal result type of a function.
14950   if (DestType->isArrayType() || DestType->isFunctionType()) {
14951     unsigned diagID = diag::err_func_returning_array_function;
14952     if (Kind == FK_BlockPointer)
14953       diagID = diag::err_block_returning_array_function;
14954 
14955     S.Diag(E->getExprLoc(), diagID)
14956       << DestType->isFunctionType() << DestType;
14957     return ExprError();
14958   }
14959 
14960   // Otherwise, go ahead and set DestType as the call's result.
14961   E->setType(DestType.getNonLValueExprType(S.Context));
14962   E->setValueKind(Expr::getValueKindForType(DestType));
14963   assert(E->getObjectKind() == OK_Ordinary);
14964 
14965   // Rebuild the function type, replacing the result type with DestType.
14966   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14967   if (Proto) {
14968     // __unknown_anytype(...) is a special case used by the debugger when
14969     // it has no idea what a function's signature is.
14970     //
14971     // We want to build this call essentially under the K&R
14972     // unprototyped rules, but making a FunctionNoProtoType in C++
14973     // would foul up all sorts of assumptions.  However, we cannot
14974     // simply pass all arguments as variadic arguments, nor can we
14975     // portably just call the function under a non-variadic type; see
14976     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14977     // However, it turns out that in practice it is generally safe to
14978     // call a function declared as "A foo(B,C,D);" under the prototype
14979     // "A foo(B,C,D,...);".  The only known exception is with the
14980     // Windows ABI, where any variadic function is implicitly cdecl
14981     // regardless of its normal CC.  Therefore we change the parameter
14982     // types to match the types of the arguments.
14983     //
14984     // This is a hack, but it is far superior to moving the
14985     // corresponding target-specific code from IR-gen to Sema/AST.
14986 
14987     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14988     SmallVector<QualType, 8> ArgTypes;
14989     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14990       ArgTypes.reserve(E->getNumArgs());
14991       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14992         Expr *Arg = E->getArg(i);
14993         QualType ArgType = Arg->getType();
14994         if (E->isLValue()) {
14995           ArgType = S.Context.getLValueReferenceType(ArgType);
14996         } else if (E->isXValue()) {
14997           ArgType = S.Context.getRValueReferenceType(ArgType);
14998         }
14999         ArgTypes.push_back(ArgType);
15000       }
15001       ParamTypes = ArgTypes;
15002     }
15003     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15004                                          Proto->getExtProtoInfo());
15005   } else {
15006     DestType = S.Context.getFunctionNoProtoType(DestType,
15007                                                 FnType->getExtInfo());
15008   }
15009 
15010   // Rebuild the appropriate pointer-to-function type.
15011   switch (Kind) {
15012   case FK_MemberFunction:
15013     // Nothing to do.
15014     break;
15015 
15016   case FK_FunctionPointer:
15017     DestType = S.Context.getPointerType(DestType);
15018     break;
15019 
15020   case FK_BlockPointer:
15021     DestType = S.Context.getBlockPointerType(DestType);
15022     break;
15023   }
15024 
15025   // Finally, we can recurse.
15026   ExprResult CalleeResult = Visit(CalleeExpr);
15027   if (!CalleeResult.isUsable()) return ExprError();
15028   E->setCallee(CalleeResult.get());
15029 
15030   // Bind a temporary if necessary.
15031   return S.MaybeBindToTemporary(E);
15032 }
15033 
15034 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15035   // Verify that this is a legal result type of a call.
15036   if (DestType->isArrayType() || DestType->isFunctionType()) {
15037     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15038       << DestType->isFunctionType() << DestType;
15039     return ExprError();
15040   }
15041 
15042   // Rewrite the method result type if available.
15043   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15044     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15045     Method->setReturnType(DestType);
15046   }
15047 
15048   // Change the type of the message.
15049   E->setType(DestType.getNonReferenceType());
15050   E->setValueKind(Expr::getValueKindForType(DestType));
15051 
15052   return S.MaybeBindToTemporary(E);
15053 }
15054 
15055 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15056   // The only case we should ever see here is a function-to-pointer decay.
15057   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15058     assert(E->getValueKind() == VK_RValue);
15059     assert(E->getObjectKind() == OK_Ordinary);
15060 
15061     E->setType(DestType);
15062 
15063     // Rebuild the sub-expression as the pointee (function) type.
15064     DestType = DestType->castAs<PointerType>()->getPointeeType();
15065 
15066     ExprResult Result = Visit(E->getSubExpr());
15067     if (!Result.isUsable()) return ExprError();
15068 
15069     E->setSubExpr(Result.get());
15070     return E;
15071   } else if (E->getCastKind() == CK_LValueToRValue) {
15072     assert(E->getValueKind() == VK_RValue);
15073     assert(E->getObjectKind() == OK_Ordinary);
15074 
15075     assert(isa<BlockPointerType>(E->getType()));
15076 
15077     E->setType(DestType);
15078 
15079     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15080     DestType = S.Context.getLValueReferenceType(DestType);
15081 
15082     ExprResult Result = Visit(E->getSubExpr());
15083     if (!Result.isUsable()) return ExprError();
15084 
15085     E->setSubExpr(Result.get());
15086     return E;
15087   } else {
15088     llvm_unreachable("Unhandled cast type!");
15089   }
15090 }
15091 
15092 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15093   ExprValueKind ValueKind = VK_LValue;
15094   QualType Type = DestType;
15095 
15096   // We know how to make this work for certain kinds of decls:
15097 
15098   //  - functions
15099   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15100     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15101       DestType = Ptr->getPointeeType();
15102       ExprResult Result = resolveDecl(E, VD);
15103       if (Result.isInvalid()) return ExprError();
15104       return S.ImpCastExprToType(Result.get(), Type,
15105                                  CK_FunctionToPointerDecay, VK_RValue);
15106     }
15107 
15108     if (!Type->isFunctionType()) {
15109       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15110         << VD << E->getSourceRange();
15111       return ExprError();
15112     }
15113     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15114       // We must match the FunctionDecl's type to the hack introduced in
15115       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15116       // type. See the lengthy commentary in that routine.
15117       QualType FDT = FD->getType();
15118       const FunctionType *FnType = FDT->castAs<FunctionType>();
15119       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15120       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15121       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15122         SourceLocation Loc = FD->getLocation();
15123         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15124                                       FD->getDeclContext(),
15125                                       Loc, Loc, FD->getNameInfo().getName(),
15126                                       DestType, FD->getTypeSourceInfo(),
15127                                       SC_None, false/*isInlineSpecified*/,
15128                                       FD->hasPrototype(),
15129                                       false/*isConstexprSpecified*/);
15130 
15131         if (FD->getQualifier())
15132           NewFD->setQualifierInfo(FD->getQualifierLoc());
15133 
15134         SmallVector<ParmVarDecl*, 16> Params;
15135         for (const auto &AI : FT->param_types()) {
15136           ParmVarDecl *Param =
15137             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15138           Param->setScopeInfo(0, Params.size());
15139           Params.push_back(Param);
15140         }
15141         NewFD->setParams(Params);
15142         DRE->setDecl(NewFD);
15143         VD = DRE->getDecl();
15144       }
15145     }
15146 
15147     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15148       if (MD->isInstance()) {
15149         ValueKind = VK_RValue;
15150         Type = S.Context.BoundMemberTy;
15151       }
15152 
15153     // Function references aren't l-values in C.
15154     if (!S.getLangOpts().CPlusPlus)
15155       ValueKind = VK_RValue;
15156 
15157   //  - variables
15158   } else if (isa<VarDecl>(VD)) {
15159     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15160       Type = RefTy->getPointeeType();
15161     } else if (Type->isFunctionType()) {
15162       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15163         << VD << E->getSourceRange();
15164       return ExprError();
15165     }
15166 
15167   //  - nothing else
15168   } else {
15169     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15170       << VD << E->getSourceRange();
15171     return ExprError();
15172   }
15173 
15174   // Modifying the declaration like this is friendly to IR-gen but
15175   // also really dangerous.
15176   VD->setType(DestType);
15177   E->setType(Type);
15178   E->setValueKind(ValueKind);
15179   return E;
15180 }
15181 
15182 /// Check a cast of an unknown-any type.  We intentionally only
15183 /// trigger this for C-style casts.
15184 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15185                                      Expr *CastExpr, CastKind &CastKind,
15186                                      ExprValueKind &VK, CXXCastPath &Path) {
15187   // The type we're casting to must be either void or complete.
15188   if (!CastType->isVoidType() &&
15189       RequireCompleteType(TypeRange.getBegin(), CastType,
15190                           diag::err_typecheck_cast_to_incomplete))
15191     return ExprError();
15192 
15193   // Rewrite the casted expression from scratch.
15194   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15195   if (!result.isUsable()) return ExprError();
15196 
15197   CastExpr = result.get();
15198   VK = CastExpr->getValueKind();
15199   CastKind = CK_NoOp;
15200 
15201   return CastExpr;
15202 }
15203 
15204 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15205   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15206 }
15207 
15208 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15209                                     Expr *arg, QualType &paramType) {
15210   // If the syntactic form of the argument is not an explicit cast of
15211   // any sort, just do default argument promotion.
15212   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15213   if (!castArg) {
15214     ExprResult result = DefaultArgumentPromotion(arg);
15215     if (result.isInvalid()) return ExprError();
15216     paramType = result.get()->getType();
15217     return result;
15218   }
15219 
15220   // Otherwise, use the type that was written in the explicit cast.
15221   assert(!arg->hasPlaceholderType());
15222   paramType = castArg->getTypeAsWritten();
15223 
15224   // Copy-initialize a parameter of that type.
15225   InitializedEntity entity =
15226     InitializedEntity::InitializeParameter(Context, paramType,
15227                                            /*consumed*/ false);
15228   return PerformCopyInitialization(entity, callLoc, arg);
15229 }
15230 
15231 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15232   Expr *orig = E;
15233   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15234   while (true) {
15235     E = E->IgnoreParenImpCasts();
15236     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15237       E = call->getCallee();
15238       diagID = diag::err_uncasted_call_of_unknown_any;
15239     } else {
15240       break;
15241     }
15242   }
15243 
15244   SourceLocation loc;
15245   NamedDecl *d;
15246   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15247     loc = ref->getLocation();
15248     d = ref->getDecl();
15249   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15250     loc = mem->getMemberLoc();
15251     d = mem->getMemberDecl();
15252   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15253     diagID = diag::err_uncasted_call_of_unknown_any;
15254     loc = msg->getSelectorStartLoc();
15255     d = msg->getMethodDecl();
15256     if (!d) {
15257       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15258         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15259         << orig->getSourceRange();
15260       return ExprError();
15261     }
15262   } else {
15263     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15264       << E->getSourceRange();
15265     return ExprError();
15266   }
15267 
15268   S.Diag(loc, diagID) << d << orig->getSourceRange();
15269 
15270   // Never recoverable.
15271   return ExprError();
15272 }
15273 
15274 /// Check for operands with placeholder types and complain if found.
15275 /// Returns true if there was an error and no recovery was possible.
15276 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15277   if (!getLangOpts().CPlusPlus) {
15278     // C cannot handle TypoExpr nodes on either side of a binop because it
15279     // doesn't handle dependent types properly, so make sure any TypoExprs have
15280     // been dealt with before checking the operands.
15281     ExprResult Result = CorrectDelayedTyposInExpr(E);
15282     if (!Result.isUsable()) return ExprError();
15283     E = Result.get();
15284   }
15285 
15286   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15287   if (!placeholderType) return E;
15288 
15289   switch (placeholderType->getKind()) {
15290 
15291   // Overloaded expressions.
15292   case BuiltinType::Overload: {
15293     // Try to resolve a single function template specialization.
15294     // This is obligatory.
15295     ExprResult Result = E;
15296     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15297       return Result;
15298 
15299     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15300     // leaves Result unchanged on failure.
15301     Result = E;
15302     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15303       return Result;
15304 
15305     // If that failed, try to recover with a call.
15306     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15307                          /*complain*/ true);
15308     return Result;
15309   }
15310 
15311   // Bound member functions.
15312   case BuiltinType::BoundMember: {
15313     ExprResult result = E;
15314     const Expr *BME = E->IgnoreParens();
15315     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15316     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15317     if (isa<CXXPseudoDestructorExpr>(BME)) {
15318       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15319     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15320       if (ME->getMemberNameInfo().getName().getNameKind() ==
15321           DeclarationName::CXXDestructorName)
15322         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15323     }
15324     tryToRecoverWithCall(result, PD,
15325                          /*complain*/ true);
15326     return result;
15327   }
15328 
15329   // ARC unbridged casts.
15330   case BuiltinType::ARCUnbridgedCast: {
15331     Expr *realCast = stripARCUnbridgedCast(E);
15332     diagnoseARCUnbridgedCast(realCast);
15333     return realCast;
15334   }
15335 
15336   // Expressions of unknown type.
15337   case BuiltinType::UnknownAny:
15338     return diagnoseUnknownAnyExpr(*this, E);
15339 
15340   // Pseudo-objects.
15341   case BuiltinType::PseudoObject:
15342     return checkPseudoObjectRValue(E);
15343 
15344   case BuiltinType::BuiltinFn: {
15345     // Accept __noop without parens by implicitly converting it to a call expr.
15346     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15347     if (DRE) {
15348       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15349       if (FD->getBuiltinID() == Builtin::BI__noop) {
15350         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15351                               CK_BuiltinFnToFnPtr).get();
15352         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15353                                       VK_RValue, SourceLocation());
15354       }
15355     }
15356 
15357     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15358     return ExprError();
15359   }
15360 
15361   // Expressions of unknown type.
15362   case BuiltinType::OMPArraySection:
15363     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15364     return ExprError();
15365 
15366   // Everything else should be impossible.
15367 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15368   case BuiltinType::Id:
15369 #include "clang/Basic/OpenCLImageTypes.def"
15370 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15371 #define PLACEHOLDER_TYPE(Id, SingletonId)
15372 #include "clang/AST/BuiltinTypes.def"
15373     break;
15374   }
15375 
15376   llvm_unreachable("invalid placeholder type!");
15377 }
15378 
15379 bool Sema::CheckCaseExpression(Expr *E) {
15380   if (E->isTypeDependent())
15381     return true;
15382   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15383     return E->getType()->isIntegralOrEnumerationType();
15384   return false;
15385 }
15386 
15387 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15388 ExprResult
15389 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15390   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15391          "Unknown Objective-C Boolean value!");
15392   QualType BoolT = Context.ObjCBuiltinBoolTy;
15393   if (!Context.getBOOLDecl()) {
15394     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15395                         Sema::LookupOrdinaryName);
15396     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15397       NamedDecl *ND = Result.getFoundDecl();
15398       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15399         Context.setBOOLDecl(TD);
15400     }
15401   }
15402   if (Context.getBOOLDecl())
15403     BoolT = Context.getBOOLType();
15404   return new (Context)
15405       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15406 }
15407 
15408 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15409     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15410     SourceLocation RParen) {
15411 
15412   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15413 
15414   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15415                            [&](const AvailabilitySpec &Spec) {
15416                              return Spec.getPlatform() == Platform;
15417                            });
15418 
15419   VersionTuple Version;
15420   if (Spec != AvailSpecs.end())
15421     Version = Spec->getVersion();
15422 
15423   return new (Context)
15424       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15425 }
15426