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 
368   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
369   // Only the variables omp_in and omp_out are allowed in the combiner.
370   // Only the variables omp_priv and omp_orig are allowed in the
371   // initializer-clause.
372   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
373   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
374       isa<VarDecl>(D)) {
375     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
376         << getCurFunction()->HasOMPDeclareReductionCombiner;
377     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
378     return true;
379   }
380   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
381                              ObjCPropertyAccess);
382 
383   DiagnoseUnusedOfDecl(*this, D, Loc);
384 
385   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
386 
387   return false;
388 }
389 
390 /// \brief Retrieve the message suffix that should be added to a
391 /// diagnostic complaining about the given function being deleted or
392 /// unavailable.
393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
394   std::string Message;
395   if (FD->getAvailability(&Message))
396     return ": " + Message;
397 
398   return std::string();
399 }
400 
401 /// DiagnoseSentinelCalls - This routine checks whether a call or
402 /// message-send is to a declaration with the sentinel attribute, and
403 /// if so, it checks that the requirements of the sentinel are
404 /// satisfied.
405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406                                  ArrayRef<Expr *> Args) {
407   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408   if (!attr)
409     return;
410 
411   // The number of formal parameters of the declaration.
412   unsigned numFormalParams;
413 
414   // The kind of declaration.  This is also an index into a %select in
415   // the diagnostic.
416   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417 
418   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419     numFormalParams = MD->param_size();
420     calleeType = CT_Method;
421   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422     numFormalParams = FD->param_size();
423     calleeType = CT_Function;
424   } else if (isa<VarDecl>(D)) {
425     QualType type = cast<ValueDecl>(D)->getType();
426     const FunctionType *fn = nullptr;
427     if (const PointerType *ptr = type->getAs<PointerType>()) {
428       fn = ptr->getPointeeType()->getAs<FunctionType>();
429       if (!fn) return;
430       calleeType = CT_Function;
431     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432       fn = ptr->getPointeeType()->castAs<FunctionType>();
433       calleeType = CT_Block;
434     } else {
435       return;
436     }
437 
438     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439       numFormalParams = proto->getNumParams();
440     } else {
441       numFormalParams = 0;
442     }
443   } else {
444     return;
445   }
446 
447   // "nullPos" is the number of formal parameters at the end which
448   // effectively count as part of the variadic arguments.  This is
449   // useful if you would prefer to not have *any* formal parameters,
450   // but the language forces you to have at least one.
451   unsigned nullPos = attr->getNullPos();
452   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454 
455   // The number of arguments which should follow the sentinel.
456   unsigned numArgsAfterSentinel = attr->getSentinel();
457 
458   // If there aren't enough arguments for all the formal parameters,
459   // the sentinel, and the args after the sentinel, complain.
460   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463     return;
464   }
465 
466   // Otherwise, find the sentinel expression.
467   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468   if (!sentinelExpr) return;
469   if (sentinelExpr->isValueDependent()) return;
470   if (Context.isSentinelNullExpr(sentinelExpr)) return;
471 
472   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
473   // or 'NULL' if those are actually defined in the context.  Only use
474   // 'nil' for ObjC methods, where it's much more likely that the
475   // variadic arguments form a list of object pointers.
476   SourceLocation MissingNilLoc
477     = getLocForEndOfToken(sentinelExpr->getLocEnd());
478   std::string NullValue;
479   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480     NullValue = "nil";
481   else if (getLangOpts().CPlusPlus11)
482     NullValue = "nullptr";
483   else if (PP.isMacroDefined("NULL"))
484     NullValue = "NULL";
485   else
486     NullValue = "(void*) 0";
487 
488   if (MissingNilLoc.isInvalid())
489     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490   else
491     Diag(MissingNilLoc, diag::warn_missing_sentinel)
492       << int(calleeType)
493       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496 
497 SourceRange Sema::getExprRange(Expr *E) const {
498   return E ? E->getSourceRange() : SourceRange();
499 }
500 
501 //===----------------------------------------------------------------------===//
502 //  Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504 
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
507   // Handle any placeholder expressions which made it here.
508   if (E->getType()->isPlaceholderType()) {
509     ExprResult result = CheckPlaceholderExpr(E);
510     if (result.isInvalid()) return ExprError();
511     E = result.get();
512   }
513 
514   QualType Ty = E->getType();
515   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516 
517   if (Ty->isFunctionType()) {
518     // If we are here, we are not calling a function but taking
519     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
520     if (getLangOpts().OpenCL) {
521       if (Diagnose)
522         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
523       return ExprError();
524     }
525 
526     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
527       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
528         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
529           return ExprError();
530 
531     E = ImpCastExprToType(E, Context.getPointerType(Ty),
532                           CK_FunctionToPointerDecay).get();
533   } else if (Ty->isArrayType()) {
534     // In C90 mode, arrays only promote to pointers if the array expression is
535     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
536     // type 'array of type' is converted to an expression that has type 'pointer
537     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
538     // that has type 'array of type' ...".  The relevant change is "an lvalue"
539     // (C90) to "an expression" (C99).
540     //
541     // C++ 4.2p1:
542     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
543     // T" can be converted to an rvalue of type "pointer to T".
544     //
545     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
546       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
547                             CK_ArrayToPointerDecay).get();
548   }
549   return E;
550 }
551 
552 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
553   // Check to see if we are dereferencing a null pointer.  If so,
554   // and if not volatile-qualified, this is undefined behavior that the
555   // optimizer will delete, so warn about it.  People sometimes try to use this
556   // to get a deterministic trap and are surprised by clang's behavior.  This
557   // only handles the pattern "*null", which is a very syntactic check.
558   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
559     if (UO->getOpcode() == UO_Deref &&
560         UO->getSubExpr()->IgnoreParenCasts()->
561           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562         !UO->getType().isVolatileQualified()) {
563     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                           S.PDiag(diag::warn_indirection_through_null)
565                             << UO->getSubExpr()->getSourceRange());
566     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567                         S.PDiag(diag::note_indirection_through_null));
568   }
569 }
570 
571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
572                                     SourceLocation AssignLoc,
573                                     const Expr* RHS) {
574   const ObjCIvarDecl *IV = OIRE->getDecl();
575   if (!IV)
576     return;
577 
578   DeclarationName MemberName = IV->getDeclName();
579   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
580   if (!Member || !Member->isStr("isa"))
581     return;
582 
583   const Expr *Base = OIRE->getBase();
584   QualType BaseType = Base->getType();
585   if (OIRE->isArrow())
586     BaseType = BaseType->getPointeeType();
587   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
588     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
589       ObjCInterfaceDecl *ClassDeclared = nullptr;
590       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
591       if (!ClassDeclared->getSuperClass()
592           && (*ClassDeclared->ivar_begin()) == IV) {
593         if (RHS) {
594           NamedDecl *ObjectSetClass =
595             S.LookupSingleName(S.TUScope,
596                                &S.Context.Idents.get("object_setClass"),
597                                SourceLocation(), S.LookupOrdinaryName);
598           if (ObjectSetClass) {
599             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
600             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
601             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
602             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
603                                                      AssignLoc), ",") <<
604             FixItHint::CreateInsertion(RHSLocEnd, ")");
605           }
606           else
607             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
608         } else {
609           NamedDecl *ObjectGetClass =
610             S.LookupSingleName(S.TUScope,
611                                &S.Context.Idents.get("object_getClass"),
612                                SourceLocation(), S.LookupOrdinaryName);
613           if (ObjectGetClass)
614             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
615             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
616             FixItHint::CreateReplacement(
617                                          SourceRange(OIRE->getOpLoc(),
618                                                      OIRE->getLocEnd()), ")");
619           else
620             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621         }
622         S.Diag(IV->getLocation(), diag::note_ivar_decl);
623       }
624     }
625 }
626 
627 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
628   // Handle any placeholder expressions which made it here.
629   if (E->getType()->isPlaceholderType()) {
630     ExprResult result = CheckPlaceholderExpr(E);
631     if (result.isInvalid()) return ExprError();
632     E = result.get();
633   }
634 
635   // C++ [conv.lval]p1:
636   //   A glvalue of a non-function, non-array type T can be
637   //   converted to a prvalue.
638   if (!E->isGLValue()) return E;
639 
640   QualType T = E->getType();
641   assert(!T.isNull() && "r-value conversion on typeless expression?");
642 
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650 
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658 
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666 
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
674         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
675         FixItHint::CreateReplacement(
676                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683 
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695 
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700 
701   UpdateMarkingForLValueToRValue(E);
702 
703   // Loading a __weak object implicitly retains the value, so we need a cleanup to
704   // balance that.
705   if (getLangOpts().ObjCAutoRefCount &&
706       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
707     Cleanup.setExprNeedsCleanups(true);
708 
709   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
710                                             nullptr, VK_RValue);
711 
712   // C11 6.3.2.1p2:
713   //   ... if the lvalue has atomic type, the value has the non-atomic version
714   //   of the type of the lvalue ...
715   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
716     T = Atomic->getValueType().getUnqualifiedType();
717     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
718                                    nullptr, VK_RValue);
719   }
720 
721   return Res;
722 }
723 
724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
725   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
726   if (Res.isInvalid())
727     return ExprError();
728   Res = DefaultLvalueConversion(Res.get());
729   if (Res.isInvalid())
730     return ExprError();
731   return Res;
732 }
733 
734 /// CallExprUnaryConversions - a special case of an unary conversion
735 /// performed on a function designator of a call expression.
736 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
737   QualType Ty = E->getType();
738   ExprResult Res = E;
739   // Only do implicit cast for a function type, but not for a pointer
740   // to function type.
741   if (Ty->isFunctionType()) {
742     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
743                             CK_FunctionToPointerDecay).get();
744     if (Res.isInvalid())
745       return ExprError();
746   }
747   Res = DefaultLvalueConversion(Res.get());
748   if (Res.isInvalid())
749     return ExprError();
750   return Res.get();
751 }
752 
753 /// UsualUnaryConversions - Performs various conversions that are common to most
754 /// operators (C99 6.3). The conversions of array and function types are
755 /// sometimes suppressed. For example, the array->pointer conversion doesn't
756 /// apply if the array is an argument to the sizeof or address (&) operators.
757 /// In these instances, this routine should *not* be called.
758 ExprResult Sema::UsualUnaryConversions(Expr *E) {
759   // First, convert to an r-value.
760   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
761   if (Res.isInvalid())
762     return ExprError();
763   E = Res.get();
764 
765   QualType Ty = E->getType();
766   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
767 
768   // Half FP have to be promoted to float unless it is natively supported
769   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
770     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
771 
772   // Try to perform integral promotions if the object has a theoretically
773   // promotable type.
774   if (Ty->isIntegralOrUnscopedEnumerationType()) {
775     // C99 6.3.1.1p2:
776     //
777     //   The following may be used in an expression wherever an int or
778     //   unsigned int may be used:
779     //     - an object or expression with an integer type whose integer
780     //       conversion rank is less than or equal to the rank of int
781     //       and unsigned int.
782     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
783     //
784     //   If an int can represent all values of the original type, the
785     //   value is converted to an int; otherwise, it is converted to an
786     //   unsigned int. These are called the integer promotions. All
787     //   other types are unchanged by the integer promotions.
788 
789     QualType PTy = Context.isPromotableBitField(E);
790     if (!PTy.isNull()) {
791       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
792       return E;
793     }
794     if (Ty->isPromotableIntegerType()) {
795       QualType PT = Context.getPromotedIntegerType(Ty);
796       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
797       return E;
798     }
799   }
800   return E;
801 }
802 
803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
804 /// do not have a prototype. Arguments that have type float or __fp16
805 /// are promoted to double. All other argument types are converted by
806 /// UsualUnaryConversions().
807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
808   QualType Ty = E->getType();
809   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
810 
811   ExprResult Res = UsualUnaryConversions(E);
812   if (Res.isInvalid())
813     return ExprError();
814   E = Res.get();
815 
816   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
817   // double.
818   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
819   if (BTy && (BTy->getKind() == BuiltinType::Half ||
820               BTy->getKind() == BuiltinType::Float)) {
821     if (getLangOpts().OpenCL &&
822         !(getOpenCLOptions().cl_khr_fp64)) {
823         if (BTy->getKind() == BuiltinType::Half) {
824             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
825         }
826     } else {
827       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
828     }
829   }
830 
831   // C++ performs lvalue-to-rvalue conversion as a default argument
832   // promotion, even on class types, but note:
833   //   C++11 [conv.lval]p2:
834   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
835   //     operand or a subexpression thereof the value contained in the
836   //     referenced object is not accessed. Otherwise, if the glvalue
837   //     has a class type, the conversion copy-initializes a temporary
838   //     of type T from the glvalue and the result of the conversion
839   //     is a prvalue for the temporary.
840   // FIXME: add some way to gate this entire thing for correctness in
841   // potentially potentially evaluated contexts.
842   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
843     ExprResult Temp = PerformCopyInitialization(
844                        InitializedEntity::InitializeTemporary(E->getType()),
845                                                 E->getExprLoc(), E);
846     if (Temp.isInvalid())
847       return ExprError();
848     E = Temp.get();
849   }
850 
851   return E;
852 }
853 
854 /// Determine the degree of POD-ness for an expression.
855 /// Incomplete types are considered POD, since this check can be performed
856 /// when we're in an unevaluated context.
857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
858   if (Ty->isIncompleteType()) {
859     // C++11 [expr.call]p7:
860     //   After these conversions, if the argument does not have arithmetic,
861     //   enumeration, pointer, pointer to member, or class type, the program
862     //   is ill-formed.
863     //
864     // Since we've already performed array-to-pointer and function-to-pointer
865     // decay, the only such type in C++ is cv void. This also handles
866     // initializer lists as variadic arguments.
867     if (Ty->isVoidType())
868       return VAK_Invalid;
869 
870     if (Ty->isObjCObjectType())
871       return VAK_Invalid;
872     return VAK_Valid;
873   }
874 
875   if (Ty.isCXX98PODType(Context))
876     return VAK_Valid;
877 
878   // C++11 [expr.call]p7:
879   //   Passing a potentially-evaluated argument of class type (Clause 9)
880   //   having a non-trivial copy constructor, a non-trivial move constructor,
881   //   or a non-trivial destructor, with no corresponding parameter,
882   //   is conditionally-supported with implementation-defined semantics.
883   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
884     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
885       if (!Record->hasNonTrivialCopyConstructor() &&
886           !Record->hasNonTrivialMoveConstructor() &&
887           !Record->hasNonTrivialDestructor())
888         return VAK_ValidInCXX11;
889 
890   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891     return VAK_Valid;
892 
893   if (Ty->isObjCObjectType())
894     return VAK_Invalid;
895 
896   if (getLangOpts().MSVCCompat)
897     return VAK_MSVCUndefined;
898 
899   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900   // permitted to reject them. We should consider doing so.
901   return VAK_Undefined;
902 }
903 
904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
905   // Don't allow one to pass an Objective-C interface to a vararg.
906   const QualType &Ty = E->getType();
907   VarArgKind VAK = isValidVarArgType(Ty);
908 
909   // Complain about passing non-POD types through varargs.
910   switch (VAK) {
911   case VAK_ValidInCXX11:
912     DiagRuntimeBehavior(
913         E->getLocStart(), nullptr,
914         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
915           << Ty << CT);
916     // Fall through.
917   case VAK_Valid:
918     if (Ty->isRecordType()) {
919       // This is unlikely to be what the user intended. If the class has a
920       // 'c_str' member function, the user probably meant to call that.
921       DiagRuntimeBehavior(E->getLocStart(), nullptr,
922                           PDiag(diag::warn_pass_class_arg_to_vararg)
923                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
924     }
925     break;
926 
927   case VAK_Undefined:
928   case VAK_MSVCUndefined:
929     DiagRuntimeBehavior(
930         E->getLocStart(), nullptr,
931         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
932           << getLangOpts().CPlusPlus11 << Ty << CT);
933     break;
934 
935   case VAK_Invalid:
936     if (Ty->isObjCObjectType())
937       DiagRuntimeBehavior(
938           E->getLocStart(), nullptr,
939           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
940             << Ty << CT);
941     else
942       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
943         << isa<InitListExpr>(E) << Ty << CT;
944     break;
945   }
946 }
947 
948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
949 /// will create a trap if the resulting type is not a POD type.
950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
951                                                   FunctionDecl *FDecl) {
952   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
953     // Strip the unbridged-cast placeholder expression off, if applicable.
954     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
955         (CT == VariadicMethod ||
956          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
957       E = stripARCUnbridgedCast(E);
958 
959     // Otherwise, do normal placeholder checking.
960     } else {
961       ExprResult ExprRes = CheckPlaceholderExpr(E);
962       if (ExprRes.isInvalid())
963         return ExprError();
964       E = ExprRes.get();
965     }
966   }
967 
968   ExprResult ExprRes = DefaultArgumentPromotion(E);
969   if (ExprRes.isInvalid())
970     return ExprError();
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getLocStart());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
983                                           Name, true, false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
988                                     E->getLocStart(), None,
989                                     E->getLocEnd());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
994                                   Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// \brief Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// \brief Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // If we have two real floating types, convert the smaller operand
1129   // to the bigger result.
1130   if (LHSFloat && RHSFloat) {
1131     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1132     if (order > 0) {
1133       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1134       return LHSType;
1135     }
1136 
1137     assert(order < 0 && "illegal float comparison");
1138     if (!IsCompAssign)
1139       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1140     return RHSType;
1141   }
1142 
1143   if (LHSFloat) {
1144     // Half FP has to be promoted to float unless it is natively supported
1145     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1146       LHSType = S.Context.FloatTy;
1147 
1148     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1149                                       /*convertFloat=*/!IsCompAssign,
1150                                       /*convertInt=*/ true);
1151   }
1152   assert(RHSFloat);
1153   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1154                                     /*convertInt=*/ true,
1155                                     /*convertFloat=*/!IsCompAssign);
1156 }
1157 
1158 /// \brief Diagnose attempts to convert between __float128 and long double if
1159 /// there is no support for such conversion. Helper function of
1160 /// UsualArithmeticConversions().
1161 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1162                                       QualType RHSType) {
1163   /*  No issue converting if at least one of the types is not a floating point
1164       type or the two types have the same rank.
1165   */
1166   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1167       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1168     return false;
1169 
1170   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1171          "The remaining types must be floating point types.");
1172 
1173   auto *LHSComplex = LHSType->getAs<ComplexType>();
1174   auto *RHSComplex = RHSType->getAs<ComplexType>();
1175 
1176   QualType LHSElemType = LHSComplex ?
1177     LHSComplex->getElementType() : LHSType;
1178   QualType RHSElemType = RHSComplex ?
1179     RHSComplex->getElementType() : RHSType;
1180 
1181   // No issue if the two types have the same representation
1182   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1183       &S.Context.getFloatTypeSemantics(RHSElemType))
1184     return false;
1185 
1186   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1187                                 RHSElemType == S.Context.LongDoubleTy);
1188   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1189                             RHSElemType == S.Context.Float128Ty);
1190 
1191   /* We've handled the situation where __float128 and long double have the same
1192      representation. The only other allowable conversion is if long double is
1193      really just double.
1194   */
1195   return Float128AndLongDouble &&
1196     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1197      &llvm::APFloat::IEEEdouble());
1198 }
1199 
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201 
1202 namespace {
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207 }
1208 
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211                              CK_IntegralComplexCast);
1212 }
1213 }
1214 
1215 /// \brief Handle integer arithmetic conversions.  Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219                                         ExprResult &RHS, QualType LHSType,
1220                                         QualType RHSType, bool IsCompAssign) {
1221   // The rules for this case are in C99 6.3.1.8
1222   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225   if (LHSSigned == RHSSigned) {
1226     // Same signedness; use the higher-ranked type
1227     if (order >= 0) {
1228       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229       return LHSType;
1230     } else if (!IsCompAssign)
1231       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232     return RHSType;
1233   } else if (order != (LHSSigned ? 1 : -1)) {
1234     // The unsigned type has greater than or equal rank to the
1235     // signed type, so use the unsigned type
1236     if (RHSSigned) {
1237       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238       return LHSType;
1239     } else if (!IsCompAssign)
1240       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241     return RHSType;
1242   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243     // The two types are different widths; if we are here, that
1244     // means the signed type is larger than the unsigned type, so
1245     // use the signed type.
1246     if (LHSSigned) {
1247       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248       return LHSType;
1249     } else if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251     return RHSType;
1252   } else {
1253     // The signed type is higher-ranked than the unsigned type,
1254     // but isn't actually any bigger (like unsigned int and long
1255     // on most 32-bit systems).  Use the unsigned type corresponding
1256     // to the signed type.
1257     QualType result =
1258       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259     RHS = (*doRHSCast)(S, RHS.get(), result);
1260     if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), result);
1262     return result;
1263   }
1264 }
1265 
1266 /// \brief Handle conversions with GCC complex int extension.  Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269                                            ExprResult &RHS, QualType LHSType,
1270                                            QualType RHSType,
1271                                            bool IsCompAssign) {
1272   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274 
1275   if (LHSComplexInt && RHSComplexInt) {
1276     QualType LHSEltType = LHSComplexInt->getElementType();
1277     QualType RHSEltType = RHSComplexInt->getElementType();
1278     QualType ScalarType =
1279       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281 
1282     return S.Context.getComplexType(ScalarType);
1283   }
1284 
1285   if (LHSComplexInt) {
1286     QualType LHSEltType = LHSComplexInt->getElementType();
1287     QualType ScalarType =
1288       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290     QualType ComplexType = S.Context.getComplexType(ScalarType);
1291     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292                               CK_IntegralRealToComplex);
1293 
1294     return ComplexType;
1295   }
1296 
1297   assert(RHSComplexInt);
1298 
1299   QualType RHSEltType = RHSComplexInt->getElementType();
1300   QualType ScalarType =
1301     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303   QualType ComplexType = S.Context.getComplexType(ScalarType);
1304 
1305   if (!IsCompAssign)
1306     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307                               CK_IntegralRealToComplex);
1308   return ComplexType;
1309 }
1310 
1311 /// UsualArithmeticConversions - Performs various conversions that are common to
1312 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1313 /// routine returns the first non-arithmetic type found. The client is
1314 /// responsible for emitting appropriate error diagnostics.
1315 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1316                                           bool IsCompAssign) {
1317   if (!IsCompAssign) {
1318     LHS = UsualUnaryConversions(LHS.get());
1319     if (LHS.isInvalid())
1320       return QualType();
1321   }
1322 
1323   RHS = UsualUnaryConversions(RHS.get());
1324   if (RHS.isInvalid())
1325     return QualType();
1326 
1327   // For conversion purposes, we ignore any qualifiers.
1328   // For example, "const float" and "float" are equivalent.
1329   QualType LHSType =
1330     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1331   QualType RHSType =
1332     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1333 
1334   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1335   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1336     LHSType = AtomicLHS->getValueType();
1337 
1338   // If both types are identical, no conversion is needed.
1339   if (LHSType == RHSType)
1340     return LHSType;
1341 
1342   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1343   // The caller can deal with this (e.g. pointer + int).
1344   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1345     return QualType();
1346 
1347   // Apply unary and bitfield promotions to the LHS's type.
1348   QualType LHSUnpromotedType = LHSType;
1349   if (LHSType->isPromotableIntegerType())
1350     LHSType = Context.getPromotedIntegerType(LHSType);
1351   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1352   if (!LHSBitfieldPromoteTy.isNull())
1353     LHSType = LHSBitfieldPromoteTy;
1354   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1355     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1356 
1357   // If both types are identical, no conversion is needed.
1358   if (LHSType == RHSType)
1359     return LHSType;
1360 
1361   // At this point, we have two different arithmetic types.
1362 
1363   // Diagnose attempts to convert between __float128 and long double where
1364   // such conversions currently can't be handled.
1365   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1366     return QualType();
1367 
1368   // Handle complex types first (C99 6.3.1.8p1).
1369   if (LHSType->isComplexType() || RHSType->isComplexType())
1370     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1371                                         IsCompAssign);
1372 
1373   // Now handle "real" floating types (i.e. float, double, long double).
1374   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1375     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1376                                  IsCompAssign);
1377 
1378   // Handle GCC complex int extension.
1379   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1380     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1381                                       IsCompAssign);
1382 
1383   // Finally, we have two differing integer types.
1384   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1385            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1386 }
1387 
1388 
1389 //===----------------------------------------------------------------------===//
1390 //  Semantic Analysis for various Expression Types
1391 //===----------------------------------------------------------------------===//
1392 
1393 
1394 ExprResult
1395 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1396                                 SourceLocation DefaultLoc,
1397                                 SourceLocation RParenLoc,
1398                                 Expr *ControllingExpr,
1399                                 ArrayRef<ParsedType> ArgTypes,
1400                                 ArrayRef<Expr *> ArgExprs) {
1401   unsigned NumAssocs = ArgTypes.size();
1402   assert(NumAssocs == ArgExprs.size());
1403 
1404   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1405   for (unsigned i = 0; i < NumAssocs; ++i) {
1406     if (ArgTypes[i])
1407       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1408     else
1409       Types[i] = nullptr;
1410   }
1411 
1412   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1413                                              ControllingExpr,
1414                                              llvm::makeArrayRef(Types, NumAssocs),
1415                                              ArgExprs);
1416   delete [] Types;
1417   return ER;
1418 }
1419 
1420 ExprResult
1421 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1422                                  SourceLocation DefaultLoc,
1423                                  SourceLocation RParenLoc,
1424                                  Expr *ControllingExpr,
1425                                  ArrayRef<TypeSourceInfo *> Types,
1426                                  ArrayRef<Expr *> Exprs) {
1427   unsigned NumAssocs = Types.size();
1428   assert(NumAssocs == Exprs.size());
1429 
1430   // Decay and strip qualifiers for the controlling expression type, and handle
1431   // placeholder type replacement. See committee discussion from WG14 DR423.
1432   {
1433     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1434     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1435     if (R.isInvalid())
1436       return ExprError();
1437     ControllingExpr = R.get();
1438   }
1439 
1440   // The controlling expression is an unevaluated operand, so side effects are
1441   // likely unintended.
1442   if (ActiveTemplateInstantiations.empty() &&
1443       ControllingExpr->HasSideEffects(Context, false))
1444     Diag(ControllingExpr->getExprLoc(),
1445          diag::warn_side_effects_unevaluated_context);
1446 
1447   bool TypeErrorFound = false,
1448        IsResultDependent = ControllingExpr->isTypeDependent(),
1449        ContainsUnexpandedParameterPack
1450          = ControllingExpr->containsUnexpandedParameterPack();
1451 
1452   for (unsigned i = 0; i < NumAssocs; ++i) {
1453     if (Exprs[i]->containsUnexpandedParameterPack())
1454       ContainsUnexpandedParameterPack = true;
1455 
1456     if (Types[i]) {
1457       if (Types[i]->getType()->containsUnexpandedParameterPack())
1458         ContainsUnexpandedParameterPack = true;
1459 
1460       if (Types[i]->getType()->isDependentType()) {
1461         IsResultDependent = true;
1462       } else {
1463         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1464         // complete object type other than a variably modified type."
1465         unsigned D = 0;
1466         if (Types[i]->getType()->isIncompleteType())
1467           D = diag::err_assoc_type_incomplete;
1468         else if (!Types[i]->getType()->isObjectType())
1469           D = diag::err_assoc_type_nonobject;
1470         else if (Types[i]->getType()->isVariablyModifiedType())
1471           D = diag::err_assoc_type_variably_modified;
1472 
1473         if (D != 0) {
1474           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1475             << Types[i]->getTypeLoc().getSourceRange()
1476             << Types[i]->getType();
1477           TypeErrorFound = true;
1478         }
1479 
1480         // C11 6.5.1.1p2 "No two generic associations in the same generic
1481         // selection shall specify compatible types."
1482         for (unsigned j = i+1; j < NumAssocs; ++j)
1483           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1484               Context.typesAreCompatible(Types[i]->getType(),
1485                                          Types[j]->getType())) {
1486             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1487                  diag::err_assoc_compatible_types)
1488               << Types[j]->getTypeLoc().getSourceRange()
1489               << Types[j]->getType()
1490               << Types[i]->getType();
1491             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1492                  diag::note_compat_assoc)
1493               << Types[i]->getTypeLoc().getSourceRange()
1494               << Types[i]->getType();
1495             TypeErrorFound = true;
1496           }
1497       }
1498     }
1499   }
1500   if (TypeErrorFound)
1501     return ExprError();
1502 
1503   // If we determined that the generic selection is result-dependent, don't
1504   // try to compute the result expression.
1505   if (IsResultDependent)
1506     return new (Context) GenericSelectionExpr(
1507         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1508         ContainsUnexpandedParameterPack);
1509 
1510   SmallVector<unsigned, 1> CompatIndices;
1511   unsigned DefaultIndex = -1U;
1512   for (unsigned i = 0; i < NumAssocs; ++i) {
1513     if (!Types[i])
1514       DefaultIndex = i;
1515     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1516                                         Types[i]->getType()))
1517       CompatIndices.push_back(i);
1518   }
1519 
1520   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1521   // type compatible with at most one of the types named in its generic
1522   // association list."
1523   if (CompatIndices.size() > 1) {
1524     // We strip parens here because the controlling expression is typically
1525     // parenthesized in macro definitions.
1526     ControllingExpr = ControllingExpr->IgnoreParens();
1527     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1528       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1529       << (unsigned) CompatIndices.size();
1530     for (unsigned I : CompatIndices) {
1531       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1532            diag::note_compat_assoc)
1533         << Types[I]->getTypeLoc().getSourceRange()
1534         << Types[I]->getType();
1535     }
1536     return ExprError();
1537   }
1538 
1539   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1540   // its controlling expression shall have type compatible with exactly one of
1541   // the types named in its generic association list."
1542   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1543     // We strip parens here because the controlling expression is typically
1544     // parenthesized in macro definitions.
1545     ControllingExpr = ControllingExpr->IgnoreParens();
1546     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1547       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1548     return ExprError();
1549   }
1550 
1551   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1552   // type name that is compatible with the type of the controlling expression,
1553   // then the result expression of the generic selection is the expression
1554   // in that generic association. Otherwise, the result expression of the
1555   // generic selection is the expression in the default generic association."
1556   unsigned ResultIndex =
1557     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1558 
1559   return new (Context) GenericSelectionExpr(
1560       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1561       ContainsUnexpandedParameterPack, ResultIndex);
1562 }
1563 
1564 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1565 /// location of the token and the offset of the ud-suffix within it.
1566 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1567                                      unsigned Offset) {
1568   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1569                                         S.getLangOpts());
1570 }
1571 
1572 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1573 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1574 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1575                                                  IdentifierInfo *UDSuffix,
1576                                                  SourceLocation UDSuffixLoc,
1577                                                  ArrayRef<Expr*> Args,
1578                                                  SourceLocation LitEndLoc) {
1579   assert(Args.size() <= 2 && "too many arguments for literal operator");
1580 
1581   QualType ArgTy[2];
1582   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1583     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1584     if (ArgTy[ArgIdx]->isArrayType())
1585       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1586   }
1587 
1588   DeclarationName OpName =
1589     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1594   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1595                               /*AllowRaw*/false, /*AllowTemplate*/false,
1596                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1597     return ExprError();
1598 
1599   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1600 }
1601 
1602 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1603 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1604 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1605 /// multiple tokens.  However, the common case is that StringToks points to one
1606 /// string.
1607 ///
1608 ExprResult
1609 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1610   assert(!StringToks.empty() && "Must have at least one string!");
1611 
1612   StringLiteralParser Literal(StringToks, PP);
1613   if (Literal.hadError)
1614     return ExprError();
1615 
1616   SmallVector<SourceLocation, 4> StringTokLocs;
1617   for (const Token &Tok : StringToks)
1618     StringTokLocs.push_back(Tok.getLocation());
1619 
1620   QualType CharTy = Context.CharTy;
1621   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1622   if (Literal.isWide()) {
1623     CharTy = Context.getWideCharType();
1624     Kind = StringLiteral::Wide;
1625   } else if (Literal.isUTF8()) {
1626     Kind = StringLiteral::UTF8;
1627   } else if (Literal.isUTF16()) {
1628     CharTy = Context.Char16Ty;
1629     Kind = StringLiteral::UTF16;
1630   } else if (Literal.isUTF32()) {
1631     CharTy = Context.Char32Ty;
1632     Kind = StringLiteral::UTF32;
1633   } else if (Literal.isPascal()) {
1634     CharTy = Context.UnsignedCharTy;
1635   }
1636 
1637   QualType CharTyConst = CharTy;
1638   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1639   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1640     CharTyConst.addConst();
1641 
1642   // Get an array type for the string, according to C99 6.4.5.  This includes
1643   // the nul terminator character as well as the string length for pascal
1644   // strings.
1645   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1646                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1647                                  ArrayType::Normal, 0);
1648 
1649   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1650   if (getLangOpts().OpenCL) {
1651     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1652   }
1653 
1654   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1655   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1656                                              Kind, Literal.Pascal, StrTy,
1657                                              &StringTokLocs[0],
1658                                              StringTokLocs.size());
1659   if (Literal.getUDSuffix().empty())
1660     return Lit;
1661 
1662   // We're building a user-defined literal.
1663   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1664   SourceLocation UDSuffixLoc =
1665     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1666                    Literal.getUDSuffixOffset());
1667 
1668   // Make sure we're allowed user-defined literals here.
1669   if (!UDLScope)
1670     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1671 
1672   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1673   //   operator "" X (str, len)
1674   QualType SizeType = Context.getSizeType();
1675 
1676   DeclarationName OpName =
1677     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1678   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1679   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1680 
1681   QualType ArgTy[] = {
1682     Context.getArrayDecayedType(StrTy), SizeType
1683   };
1684 
1685   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1686   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1687                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1688                                 /*AllowStringTemplate*/true)) {
1689 
1690   case LOLR_Cooked: {
1691     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1692     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1693                                                     StringTokLocs[0]);
1694     Expr *Args[] = { Lit, LenArg };
1695 
1696     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1697   }
1698 
1699   case LOLR_StringTemplate: {
1700     TemplateArgumentListInfo ExplicitArgs;
1701 
1702     unsigned CharBits = Context.getIntWidth(CharTy);
1703     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1704     llvm::APSInt Value(CharBits, CharIsUnsigned);
1705 
1706     TemplateArgument TypeArg(CharTy);
1707     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1708     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1709 
1710     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1711       Value = Lit->getCodeUnit(I);
1712       TemplateArgument Arg(Context, Value, CharTy);
1713       TemplateArgumentLocInfo ArgInfo;
1714       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1715     }
1716     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1717                                     &ExplicitArgs);
1718   }
1719   case LOLR_Raw:
1720   case LOLR_Template:
1721     llvm_unreachable("unexpected literal operator lookup result");
1722   case LOLR_Error:
1723     return ExprError();
1724   }
1725   llvm_unreachable("unexpected literal operator lookup result");
1726 }
1727 
1728 ExprResult
1729 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1730                        SourceLocation Loc,
1731                        const CXXScopeSpec *SS) {
1732   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1733   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1734 }
1735 
1736 /// BuildDeclRefExpr - Build an expression that references a
1737 /// declaration that does not require a closure capture.
1738 ExprResult
1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1740                        const DeclarationNameInfo &NameInfo,
1741                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1742                        const TemplateArgumentListInfo *TemplateArgs) {
1743   bool RefersToCapturedVariable =
1744       isa<VarDecl>(D) &&
1745       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1746 
1747   DeclRefExpr *E;
1748   if (isa<VarTemplateSpecializationDecl>(D)) {
1749     VarTemplateSpecializationDecl *VarSpec =
1750         cast<VarTemplateSpecializationDecl>(D);
1751 
1752     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1753                                         : NestedNameSpecifierLoc(),
1754                             VarSpec->getTemplateKeywordLoc(), D,
1755                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1756                             FoundD, TemplateArgs);
1757   } else {
1758     assert(!TemplateArgs && "No template arguments for non-variable"
1759                             " template specialization references");
1760     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761                                         : NestedNameSpecifierLoc(),
1762                             SourceLocation(), D, RefersToCapturedVariable,
1763                             NameInfo, Ty, VK, FoundD);
1764   }
1765 
1766   MarkDeclRefReferenced(E);
1767 
1768   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1769       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1770       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1771       recordUseOfEvaluatedWeak(E);
1772 
1773   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1774     UnusedPrivateFields.remove(FD);
1775     // Just in case we're building an illegal pointer-to-member.
1776     if (FD->isBitField())
1777       E->setObjectKind(OK_BitField);
1778   }
1779 
1780   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1781   // designates a bit-field.
1782   if (auto *BD = dyn_cast<BindingDecl>(D))
1783     if (auto *BE = BD->getBinding())
1784       E->setObjectKind(BE->getObjectKind());
1785 
1786   return E;
1787 }
1788 
1789 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1790 /// possibly a list of template arguments.
1791 ///
1792 /// If this produces template arguments, it is permitted to call
1793 /// DecomposeTemplateName.
1794 ///
1795 /// This actually loses a lot of source location information for
1796 /// non-standard name kinds; we should consider preserving that in
1797 /// some way.
1798 void
1799 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1800                              TemplateArgumentListInfo &Buffer,
1801                              DeclarationNameInfo &NameInfo,
1802                              const TemplateArgumentListInfo *&TemplateArgs) {
1803   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1804     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1805     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1806 
1807     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1808                                        Id.TemplateId->NumArgs);
1809     translateTemplateArguments(TemplateArgsPtr, Buffer);
1810 
1811     TemplateName TName = Id.TemplateId->Template.get();
1812     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1813     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1814     TemplateArgs = &Buffer;
1815   } else {
1816     NameInfo = GetNameFromUnqualifiedId(Id);
1817     TemplateArgs = nullptr;
1818   }
1819 }
1820 
1821 static void emitEmptyLookupTypoDiagnostic(
1822     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1823     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1824     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1825   DeclContext *Ctx =
1826       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1827   if (!TC) {
1828     // Emit a special diagnostic for failed member lookups.
1829     // FIXME: computing the declaration context might fail here (?)
1830     if (Ctx)
1831       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1832                                                  << SS.getRange();
1833     else
1834       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1835     return;
1836   }
1837 
1838   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1839   bool DroppedSpecifier =
1840       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1841   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1842                         ? diag::note_implicit_param_decl
1843                         : diag::note_previous_decl;
1844   if (!Ctx)
1845     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1846                          SemaRef.PDiag(NoteID));
1847   else
1848     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1849                                  << Typo << Ctx << DroppedSpecifier
1850                                  << SS.getRange(),
1851                          SemaRef.PDiag(NoteID));
1852 }
1853 
1854 /// Diagnose an empty lookup.
1855 ///
1856 /// \return false if new lookup candidates were found
1857 bool
1858 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1859                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1860                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1861                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1862   DeclarationName Name = R.getLookupName();
1863 
1864   unsigned diagnostic = diag::err_undeclared_var_use;
1865   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1866   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1867       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1868       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1869     diagnostic = diag::err_undeclared_use;
1870     diagnostic_suggest = diag::err_undeclared_use_suggest;
1871   }
1872 
1873   // If the original lookup was an unqualified lookup, fake an
1874   // unqualified lookup.  This is useful when (for example) the
1875   // original lookup would not have found something because it was a
1876   // dependent name.
1877   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1878   while (DC) {
1879     if (isa<CXXRecordDecl>(DC)) {
1880       LookupQualifiedName(R, DC);
1881 
1882       if (!R.empty()) {
1883         // Don't give errors about ambiguities in this lookup.
1884         R.suppressDiagnostics();
1885 
1886         // During a default argument instantiation the CurContext points
1887         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1888         // function parameter list, hence add an explicit check.
1889         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1890                               ActiveTemplateInstantiations.back().Kind ==
1891             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1892         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1893         bool isInstance = CurMethod &&
1894                           CurMethod->isInstance() &&
1895                           DC == CurMethod->getParent() && !isDefaultArgument;
1896 
1897         // Give a code modification hint to insert 'this->'.
1898         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1899         // Actually quite difficult!
1900         if (getLangOpts().MSVCCompat)
1901           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1902         if (isInstance) {
1903           Diag(R.getNameLoc(), diagnostic) << Name
1904             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1905           CheckCXXThisCapture(R.getNameLoc());
1906         } else {
1907           Diag(R.getNameLoc(), diagnostic) << Name;
1908         }
1909 
1910         // Do we really want to note all of these?
1911         for (NamedDecl *D : R)
1912           Diag(D->getLocation(), diag::note_dependent_var_use);
1913 
1914         // Return true if we are inside a default argument instantiation
1915         // and the found name refers to an instance member function, otherwise
1916         // the function calling DiagnoseEmptyLookup will try to create an
1917         // implicit member call and this is wrong for default argument.
1918         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1919           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1920           return true;
1921         }
1922 
1923         // Tell the callee to try to recover.
1924         return false;
1925       }
1926 
1927       R.clear();
1928     }
1929 
1930     // In Microsoft mode, if we are performing lookup from within a friend
1931     // function definition declared at class scope then we must set
1932     // DC to the lexical parent to be able to search into the parent
1933     // class.
1934     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1935         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1936         DC->getLexicalParent()->isRecord())
1937       DC = DC->getLexicalParent();
1938     else
1939       DC = DC->getParent();
1940   }
1941 
1942   // We didn't find anything, so try to correct for a typo.
1943   TypoCorrection Corrected;
1944   if (S && Out) {
1945     SourceLocation TypoLoc = R.getNameLoc();
1946     assert(!ExplicitTemplateArgs &&
1947            "Diagnosing an empty lookup with explicit template args!");
1948     *Out = CorrectTypoDelayed(
1949         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1950         [=](const TypoCorrection &TC) {
1951           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1952                                         diagnostic, diagnostic_suggest);
1953         },
1954         nullptr, CTK_ErrorRecovery);
1955     if (*Out)
1956       return true;
1957   } else if (S && (Corrected =
1958                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1959                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1960     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1961     bool DroppedSpecifier =
1962         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1963     R.setLookupName(Corrected.getCorrection());
1964 
1965     bool AcceptableWithRecovery = false;
1966     bool AcceptableWithoutRecovery = false;
1967     NamedDecl *ND = Corrected.getFoundDecl();
1968     if (ND) {
1969       if (Corrected.isOverloaded()) {
1970         OverloadCandidateSet OCS(R.getNameLoc(),
1971                                  OverloadCandidateSet::CSK_Normal);
1972         OverloadCandidateSet::iterator Best;
1973         for (NamedDecl *CD : Corrected) {
1974           if (FunctionTemplateDecl *FTD =
1975                    dyn_cast<FunctionTemplateDecl>(CD))
1976             AddTemplateOverloadCandidate(
1977                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1978                 Args, OCS);
1979           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1980             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1981               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1982                                    Args, OCS);
1983         }
1984         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1985         case OR_Success:
1986           ND = Best->FoundDecl;
1987           Corrected.setCorrectionDecl(ND);
1988           break;
1989         default:
1990           // FIXME: Arbitrarily pick the first declaration for the note.
1991           Corrected.setCorrectionDecl(ND);
1992           break;
1993         }
1994       }
1995       R.addDecl(ND);
1996       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1997         CXXRecordDecl *Record = nullptr;
1998         if (Corrected.getCorrectionSpecifier()) {
1999           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2000           Record = Ty->getAsCXXRecordDecl();
2001         }
2002         if (!Record)
2003           Record = cast<CXXRecordDecl>(
2004               ND->getDeclContext()->getRedeclContext());
2005         R.setNamingClass(Record);
2006       }
2007 
2008       auto *UnderlyingND = ND->getUnderlyingDecl();
2009       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2010                                isa<FunctionTemplateDecl>(UnderlyingND);
2011       // FIXME: If we ended up with a typo for a type name or
2012       // Objective-C class name, we're in trouble because the parser
2013       // is in the wrong place to recover. Suggest the typo
2014       // correction, but don't make it a fix-it since we're not going
2015       // to recover well anyway.
2016       AcceptableWithoutRecovery =
2017           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2018     } else {
2019       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2020       // because we aren't able to recover.
2021       AcceptableWithoutRecovery = true;
2022     }
2023 
2024     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2025       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2026                             ? diag::note_implicit_param_decl
2027                             : diag::note_previous_decl;
2028       if (SS.isEmpty())
2029         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2030                      PDiag(NoteID), AcceptableWithRecovery);
2031       else
2032         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2033                                   << Name << computeDeclContext(SS, false)
2034                                   << DroppedSpecifier << SS.getRange(),
2035                      PDiag(NoteID), AcceptableWithRecovery);
2036 
2037       // Tell the callee whether to try to recover.
2038       return !AcceptableWithRecovery;
2039     }
2040   }
2041   R.clear();
2042 
2043   // Emit a special diagnostic for failed member lookups.
2044   // FIXME: computing the declaration context might fail here (?)
2045   if (!SS.isEmpty()) {
2046     Diag(R.getNameLoc(), diag::err_no_member)
2047       << Name << computeDeclContext(SS, false)
2048       << SS.getRange();
2049     return true;
2050   }
2051 
2052   // Give up, we can't recover.
2053   Diag(R.getNameLoc(), diagnostic) << Name;
2054   return true;
2055 }
2056 
2057 /// In Microsoft mode, if we are inside a template class whose parent class has
2058 /// dependent base classes, and we can't resolve an unqualified identifier, then
2059 /// assume the identifier is a member of a dependent base class.  We can only
2060 /// recover successfully in static methods, instance methods, and other contexts
2061 /// where 'this' is available.  This doesn't precisely match MSVC's
2062 /// instantiation model, but it's close enough.
2063 static Expr *
2064 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2065                                DeclarationNameInfo &NameInfo,
2066                                SourceLocation TemplateKWLoc,
2067                                const TemplateArgumentListInfo *TemplateArgs) {
2068   // Only try to recover from lookup into dependent bases in static methods or
2069   // contexts where 'this' is available.
2070   QualType ThisType = S.getCurrentThisType();
2071   const CXXRecordDecl *RD = nullptr;
2072   if (!ThisType.isNull())
2073     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2074   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2075     RD = MD->getParent();
2076   if (!RD || !RD->hasAnyDependentBases())
2077     return nullptr;
2078 
2079   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2080   // is available, suggest inserting 'this->' as a fixit.
2081   SourceLocation Loc = NameInfo.getLoc();
2082   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2083   DB << NameInfo.getName() << RD;
2084 
2085   if (!ThisType.isNull()) {
2086     DB << FixItHint::CreateInsertion(Loc, "this->");
2087     return CXXDependentScopeMemberExpr::Create(
2088         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2089         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2090         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2091   }
2092 
2093   // Synthesize a fake NNS that points to the derived class.  This will
2094   // perform name lookup during template instantiation.
2095   CXXScopeSpec SS;
2096   auto *NNS =
2097       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2098   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2099   return DependentScopeDeclRefExpr::Create(
2100       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2101       TemplateArgs);
2102 }
2103 
2104 ExprResult
2105 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2106                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2107                         bool HasTrailingLParen, bool IsAddressOfOperand,
2108                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2109                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2110   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2111          "cannot be direct & operand and have a trailing lparen");
2112   if (SS.isInvalid())
2113     return ExprError();
2114 
2115   TemplateArgumentListInfo TemplateArgsBuffer;
2116 
2117   // Decompose the UnqualifiedId into the following data.
2118   DeclarationNameInfo NameInfo;
2119   const TemplateArgumentListInfo *TemplateArgs;
2120   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2121 
2122   DeclarationName Name = NameInfo.getName();
2123   IdentifierInfo *II = Name.getAsIdentifierInfo();
2124   SourceLocation NameLoc = NameInfo.getLoc();
2125 
2126   // C++ [temp.dep.expr]p3:
2127   //   An id-expression is type-dependent if it contains:
2128   //     -- an identifier that was declared with a dependent type,
2129   //        (note: handled after lookup)
2130   //     -- a template-id that is dependent,
2131   //        (note: handled in BuildTemplateIdExpr)
2132   //     -- a conversion-function-id that specifies a dependent type,
2133   //     -- a nested-name-specifier that contains a class-name that
2134   //        names a dependent type.
2135   // Determine whether this is a member of an unknown specialization;
2136   // we need to handle these differently.
2137   bool DependentID = false;
2138   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2139       Name.getCXXNameType()->isDependentType()) {
2140     DependentID = true;
2141   } else if (SS.isSet()) {
2142     if (DeclContext *DC = computeDeclContext(SS, false)) {
2143       if (RequireCompleteDeclContext(SS, DC))
2144         return ExprError();
2145     } else {
2146       DependentID = true;
2147     }
2148   }
2149 
2150   if (DependentID)
2151     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2152                                       IsAddressOfOperand, TemplateArgs);
2153 
2154   // Perform the required lookup.
2155   LookupResult R(*this, NameInfo,
2156                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2157                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2158   if (TemplateArgs) {
2159     // Lookup the template name again to correctly establish the context in
2160     // which it was found. This is really unfortunate as we already did the
2161     // lookup to determine that it was a template name in the first place. If
2162     // this becomes a performance hit, we can work harder to preserve those
2163     // results until we get here but it's likely not worth it.
2164     bool MemberOfUnknownSpecialization;
2165     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2166                        MemberOfUnknownSpecialization);
2167 
2168     if (MemberOfUnknownSpecialization ||
2169         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2170       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2171                                         IsAddressOfOperand, TemplateArgs);
2172   } else {
2173     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2174     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2175 
2176     // If the result might be in a dependent base class, this is a dependent
2177     // id-expression.
2178     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2179       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2180                                         IsAddressOfOperand, TemplateArgs);
2181 
2182     // If this reference is in an Objective-C method, then we need to do
2183     // some special Objective-C lookup, too.
2184     if (IvarLookupFollowUp) {
2185       ExprResult E(LookupInObjCMethod(R, S, II, true));
2186       if (E.isInvalid())
2187         return ExprError();
2188 
2189       if (Expr *Ex = E.getAs<Expr>())
2190         return Ex;
2191     }
2192   }
2193 
2194   if (R.isAmbiguous())
2195     return ExprError();
2196 
2197   // This could be an implicitly declared function reference (legal in C90,
2198   // extension in C99, forbidden in C++).
2199   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2200     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2201     if (D) R.addDecl(D);
2202   }
2203 
2204   // Determine whether this name might be a candidate for
2205   // argument-dependent lookup.
2206   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2207 
2208   if (R.empty() && !ADL) {
2209     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2210       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2211                                                    TemplateKWLoc, TemplateArgs))
2212         return E;
2213     }
2214 
2215     // Don't diagnose an empty lookup for inline assembly.
2216     if (IsInlineAsmIdentifier)
2217       return ExprError();
2218 
2219     // If this name wasn't predeclared and if this is not a function
2220     // call, diagnose the problem.
2221     TypoExpr *TE = nullptr;
2222     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2223         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2224     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2225     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2226            "Typo correction callback misconfigured");
2227     if (CCC) {
2228       // Make sure the callback knows what the typo being diagnosed is.
2229       CCC->setTypoName(II);
2230       if (SS.isValid())
2231         CCC->setTypoNNS(SS.getScopeRep());
2232     }
2233     if (DiagnoseEmptyLookup(S, SS, R,
2234                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2235                             nullptr, None, &TE)) {
2236       if (TE && KeywordReplacement) {
2237         auto &State = getTypoExprState(TE);
2238         auto BestTC = State.Consumer->getNextCorrection();
2239         if (BestTC.isKeyword()) {
2240           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2241           if (State.DiagHandler)
2242             State.DiagHandler(BestTC);
2243           KeywordReplacement->startToken();
2244           KeywordReplacement->setKind(II->getTokenID());
2245           KeywordReplacement->setIdentifierInfo(II);
2246           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2247           // Clean up the state associated with the TypoExpr, since it has
2248           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2249           clearDelayedTypo(TE);
2250           // Signal that a correction to a keyword was performed by returning a
2251           // valid-but-null ExprResult.
2252           return (Expr*)nullptr;
2253         }
2254         State.Consumer->resetCorrectionStream();
2255       }
2256       return TE ? TE : ExprError();
2257     }
2258 
2259     assert(!R.empty() &&
2260            "DiagnoseEmptyLookup returned false but added no results");
2261 
2262     // If we found an Objective-C instance variable, let
2263     // LookupInObjCMethod build the appropriate expression to
2264     // reference the ivar.
2265     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2266       R.clear();
2267       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2268       // In a hopelessly buggy code, Objective-C instance variable
2269       // lookup fails and no expression will be built to reference it.
2270       if (!E.isInvalid() && !E.get())
2271         return ExprError();
2272       return E;
2273     }
2274   }
2275 
2276   // This is guaranteed from this point on.
2277   assert(!R.empty() || ADL);
2278 
2279   // Check whether this might be a C++ implicit instance member access.
2280   // C++ [class.mfct.non-static]p3:
2281   //   When an id-expression that is not part of a class member access
2282   //   syntax and not used to form a pointer to member is used in the
2283   //   body of a non-static member function of class X, if name lookup
2284   //   resolves the name in the id-expression to a non-static non-type
2285   //   member of some class C, the id-expression is transformed into a
2286   //   class member access expression using (*this) as the
2287   //   postfix-expression to the left of the . operator.
2288   //
2289   // But we don't actually need to do this for '&' operands if R
2290   // resolved to a function or overloaded function set, because the
2291   // expression is ill-formed if it actually works out to be a
2292   // non-static member function:
2293   //
2294   // C++ [expr.ref]p4:
2295   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2296   //   [t]he expression can be used only as the left-hand operand of a
2297   //   member function call.
2298   //
2299   // There are other safeguards against such uses, but it's important
2300   // to get this right here so that we don't end up making a
2301   // spuriously dependent expression if we're inside a dependent
2302   // instance method.
2303   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2304     bool MightBeImplicitMember;
2305     if (!IsAddressOfOperand)
2306       MightBeImplicitMember = true;
2307     else if (!SS.isEmpty())
2308       MightBeImplicitMember = false;
2309     else if (R.isOverloadedResult())
2310       MightBeImplicitMember = false;
2311     else if (R.isUnresolvableResult())
2312       MightBeImplicitMember = true;
2313     else
2314       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2315                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2316                               isa<MSPropertyDecl>(R.getFoundDecl());
2317 
2318     if (MightBeImplicitMember)
2319       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2320                                              R, TemplateArgs, S);
2321   }
2322 
2323   if (TemplateArgs || TemplateKWLoc.isValid()) {
2324 
2325     // In C++1y, if this is a variable template id, then check it
2326     // in BuildTemplateIdExpr().
2327     // The single lookup result must be a variable template declaration.
2328     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2329         Id.TemplateId->Kind == TNK_Var_template) {
2330       assert(R.getAsSingle<VarTemplateDecl>() &&
2331              "There should only be one declaration found.");
2332     }
2333 
2334     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2335   }
2336 
2337   return BuildDeclarationNameExpr(SS, R, ADL);
2338 }
2339 
2340 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2341 /// declaration name, generally during template instantiation.
2342 /// There's a large number of things which don't need to be done along
2343 /// this path.
2344 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2345     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2346     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2347   DeclContext *DC = computeDeclContext(SS, false);
2348   if (!DC)
2349     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2350                                      NameInfo, /*TemplateArgs=*/nullptr);
2351 
2352   if (RequireCompleteDeclContext(SS, DC))
2353     return ExprError();
2354 
2355   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2356   LookupQualifiedName(R, DC);
2357 
2358   if (R.isAmbiguous())
2359     return ExprError();
2360 
2361   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2362     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2363                                      NameInfo, /*TemplateArgs=*/nullptr);
2364 
2365   if (R.empty()) {
2366     Diag(NameInfo.getLoc(), diag::err_no_member)
2367       << NameInfo.getName() << DC << SS.getRange();
2368     return ExprError();
2369   }
2370 
2371   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2372     // Diagnose a missing typename if this resolved unambiguously to a type in
2373     // a dependent context.  If we can recover with a type, downgrade this to
2374     // a warning in Microsoft compatibility mode.
2375     unsigned DiagID = diag::err_typename_missing;
2376     if (RecoveryTSI && getLangOpts().MSVCCompat)
2377       DiagID = diag::ext_typename_missing;
2378     SourceLocation Loc = SS.getBeginLoc();
2379     auto D = Diag(Loc, DiagID);
2380     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2381       << SourceRange(Loc, NameInfo.getEndLoc());
2382 
2383     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2384     // context.
2385     if (!RecoveryTSI)
2386       return ExprError();
2387 
2388     // Only issue the fixit if we're prepared to recover.
2389     D << FixItHint::CreateInsertion(Loc, "typename ");
2390 
2391     // Recover by pretending this was an elaborated type.
2392     QualType Ty = Context.getTypeDeclType(TD);
2393     TypeLocBuilder TLB;
2394     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2395 
2396     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2397     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2398     QTL.setElaboratedKeywordLoc(SourceLocation());
2399     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2400 
2401     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2402 
2403     return ExprEmpty();
2404   }
2405 
2406   // Defend against this resolving to an implicit member access. We usually
2407   // won't get here if this might be a legitimate a class member (we end up in
2408   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2409   // a pointer-to-member or in an unevaluated context in C++11.
2410   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2411     return BuildPossibleImplicitMemberExpr(SS,
2412                                            /*TemplateKWLoc=*/SourceLocation(),
2413                                            R, /*TemplateArgs=*/nullptr, S);
2414 
2415   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2416 }
2417 
2418 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2419 /// detected that we're currently inside an ObjC method.  Perform some
2420 /// additional lookup.
2421 ///
2422 /// Ideally, most of this would be done by lookup, but there's
2423 /// actually quite a lot of extra work involved.
2424 ///
2425 /// Returns a null sentinel to indicate trivial success.
2426 ExprResult
2427 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2428                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2429   SourceLocation Loc = Lookup.getNameLoc();
2430   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2431 
2432   // Check for error condition which is already reported.
2433   if (!CurMethod)
2434     return ExprError();
2435 
2436   // There are two cases to handle here.  1) scoped lookup could have failed,
2437   // in which case we should look for an ivar.  2) scoped lookup could have
2438   // found a decl, but that decl is outside the current instance method (i.e.
2439   // a global variable).  In these two cases, we do a lookup for an ivar with
2440   // this name, if the lookup sucedes, we replace it our current decl.
2441 
2442   // If we're in a class method, we don't normally want to look for
2443   // ivars.  But if we don't find anything else, and there's an
2444   // ivar, that's an error.
2445   bool IsClassMethod = CurMethod->isClassMethod();
2446 
2447   bool LookForIvars;
2448   if (Lookup.empty())
2449     LookForIvars = true;
2450   else if (IsClassMethod)
2451     LookForIvars = false;
2452   else
2453     LookForIvars = (Lookup.isSingleResult() &&
2454                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2455   ObjCInterfaceDecl *IFace = nullptr;
2456   if (LookForIvars) {
2457     IFace = CurMethod->getClassInterface();
2458     ObjCInterfaceDecl *ClassDeclared;
2459     ObjCIvarDecl *IV = nullptr;
2460     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2461       // Diagnose using an ivar in a class method.
2462       if (IsClassMethod)
2463         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2464                          << IV->getDeclName());
2465 
2466       // If we're referencing an invalid decl, just return this as a silent
2467       // error node.  The error diagnostic was already emitted on the decl.
2468       if (IV->isInvalidDecl())
2469         return ExprError();
2470 
2471       // Check if referencing a field with __attribute__((deprecated)).
2472       if (DiagnoseUseOfDecl(IV, Loc))
2473         return ExprError();
2474 
2475       // Diagnose the use of an ivar outside of the declaring class.
2476       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2477           !declaresSameEntity(ClassDeclared, IFace) &&
2478           !getLangOpts().DebuggerSupport)
2479         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2480 
2481       // FIXME: This should use a new expr for a direct reference, don't
2482       // turn this into Self->ivar, just return a BareIVarExpr or something.
2483       IdentifierInfo &II = Context.Idents.get("self");
2484       UnqualifiedId SelfName;
2485       SelfName.setIdentifier(&II, SourceLocation());
2486       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2487       CXXScopeSpec SelfScopeSpec;
2488       SourceLocation TemplateKWLoc;
2489       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2490                                               SelfName, false, false);
2491       if (SelfExpr.isInvalid())
2492         return ExprError();
2493 
2494       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2495       if (SelfExpr.isInvalid())
2496         return ExprError();
2497 
2498       MarkAnyDeclReferenced(Loc, IV, true);
2499 
2500       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2501       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2502           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2503         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2504 
2505       ObjCIvarRefExpr *Result = new (Context)
2506           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2507                           IV->getLocation(), SelfExpr.get(), true, true);
2508 
2509       if (getLangOpts().ObjCAutoRefCount) {
2510         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2511           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2512             recordUseOfEvaluatedWeak(Result);
2513         }
2514         if (CurContext->isClosure())
2515           Diag(Loc, diag::warn_implicitly_retains_self)
2516             << FixItHint::CreateInsertion(Loc, "self->");
2517       }
2518 
2519       return Result;
2520     }
2521   } else if (CurMethod->isInstanceMethod()) {
2522     // We should warn if a local variable hides an ivar.
2523     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2524       ObjCInterfaceDecl *ClassDeclared;
2525       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2526         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2527             declaresSameEntity(IFace, ClassDeclared))
2528           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2529       }
2530     }
2531   } else if (Lookup.isSingleResult() &&
2532              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2533     // If accessing a stand-alone ivar in a class method, this is an error.
2534     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2535       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2536                        << IV->getDeclName());
2537   }
2538 
2539   if (Lookup.empty() && II && AllowBuiltinCreation) {
2540     // FIXME. Consolidate this with similar code in LookupName.
2541     if (unsigned BuiltinID = II->getBuiltinID()) {
2542       if (!(getLangOpts().CPlusPlus &&
2543             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2544         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2545                                            S, Lookup.isForRedeclaration(),
2546                                            Lookup.getNameLoc());
2547         if (D) Lookup.addDecl(D);
2548       }
2549     }
2550   }
2551   // Sentinel value saying that we didn't do anything special.
2552   return ExprResult((Expr *)nullptr);
2553 }
2554 
2555 /// \brief Cast a base object to a member's actual type.
2556 ///
2557 /// Logically this happens in three phases:
2558 ///
2559 /// * First we cast from the base type to the naming class.
2560 ///   The naming class is the class into which we were looking
2561 ///   when we found the member;  it's the qualifier type if a
2562 ///   qualifier was provided, and otherwise it's the base type.
2563 ///
2564 /// * Next we cast from the naming class to the declaring class.
2565 ///   If the member we found was brought into a class's scope by
2566 ///   a using declaration, this is that class;  otherwise it's
2567 ///   the class declaring the member.
2568 ///
2569 /// * Finally we cast from the declaring class to the "true"
2570 ///   declaring class of the member.  This conversion does not
2571 ///   obey access control.
2572 ExprResult
2573 Sema::PerformObjectMemberConversion(Expr *From,
2574                                     NestedNameSpecifier *Qualifier,
2575                                     NamedDecl *FoundDecl,
2576                                     NamedDecl *Member) {
2577   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2578   if (!RD)
2579     return From;
2580 
2581   QualType DestRecordType;
2582   QualType DestType;
2583   QualType FromRecordType;
2584   QualType FromType = From->getType();
2585   bool PointerConversions = false;
2586   if (isa<FieldDecl>(Member)) {
2587     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2588 
2589     if (FromType->getAs<PointerType>()) {
2590       DestType = Context.getPointerType(DestRecordType);
2591       FromRecordType = FromType->getPointeeType();
2592       PointerConversions = true;
2593     } else {
2594       DestType = DestRecordType;
2595       FromRecordType = FromType;
2596     }
2597   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2598     if (Method->isStatic())
2599       return From;
2600 
2601     DestType = Method->getThisType(Context);
2602     DestRecordType = DestType->getPointeeType();
2603 
2604     if (FromType->getAs<PointerType>()) {
2605       FromRecordType = FromType->getPointeeType();
2606       PointerConversions = true;
2607     } else {
2608       FromRecordType = FromType;
2609       DestType = DestRecordType;
2610     }
2611   } else {
2612     // No conversion necessary.
2613     return From;
2614   }
2615 
2616   if (DestType->isDependentType() || FromType->isDependentType())
2617     return From;
2618 
2619   // If the unqualified types are the same, no conversion is necessary.
2620   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2621     return From;
2622 
2623   SourceRange FromRange = From->getSourceRange();
2624   SourceLocation FromLoc = FromRange.getBegin();
2625 
2626   ExprValueKind VK = From->getValueKind();
2627 
2628   // C++ [class.member.lookup]p8:
2629   //   [...] Ambiguities can often be resolved by qualifying a name with its
2630   //   class name.
2631   //
2632   // If the member was a qualified name and the qualified referred to a
2633   // specific base subobject type, we'll cast to that intermediate type
2634   // first and then to the object in which the member is declared. That allows
2635   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2636   //
2637   //   class Base { public: int x; };
2638   //   class Derived1 : public Base { };
2639   //   class Derived2 : public Base { };
2640   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2641   //
2642   //   void VeryDerived::f() {
2643   //     x = 17; // error: ambiguous base subobjects
2644   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2645   //   }
2646   if (Qualifier && Qualifier->getAsType()) {
2647     QualType QType = QualType(Qualifier->getAsType(), 0);
2648     assert(QType->isRecordType() && "lookup done with non-record type");
2649 
2650     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2651 
2652     // In C++98, the qualifier type doesn't actually have to be a base
2653     // type of the object type, in which case we just ignore it.
2654     // Otherwise build the appropriate casts.
2655     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2656       CXXCastPath BasePath;
2657       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2658                                        FromLoc, FromRange, &BasePath))
2659         return ExprError();
2660 
2661       if (PointerConversions)
2662         QType = Context.getPointerType(QType);
2663       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2664                                VK, &BasePath).get();
2665 
2666       FromType = QType;
2667       FromRecordType = QRecordType;
2668 
2669       // If the qualifier type was the same as the destination type,
2670       // we're done.
2671       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2672         return From;
2673     }
2674   }
2675 
2676   bool IgnoreAccess = false;
2677 
2678   // If we actually found the member through a using declaration, cast
2679   // down to the using declaration's type.
2680   //
2681   // Pointer equality is fine here because only one declaration of a
2682   // class ever has member declarations.
2683   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2684     assert(isa<UsingShadowDecl>(FoundDecl));
2685     QualType URecordType = Context.getTypeDeclType(
2686                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2687 
2688     // We only need to do this if the naming-class to declaring-class
2689     // conversion is non-trivial.
2690     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2691       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2692       CXXCastPath BasePath;
2693       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2694                                        FromLoc, FromRange, &BasePath))
2695         return ExprError();
2696 
2697       QualType UType = URecordType;
2698       if (PointerConversions)
2699         UType = Context.getPointerType(UType);
2700       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2701                                VK, &BasePath).get();
2702       FromType = UType;
2703       FromRecordType = URecordType;
2704     }
2705 
2706     // We don't do access control for the conversion from the
2707     // declaring class to the true declaring class.
2708     IgnoreAccess = true;
2709   }
2710 
2711   CXXCastPath BasePath;
2712   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2713                                    FromLoc, FromRange, &BasePath,
2714                                    IgnoreAccess))
2715     return ExprError();
2716 
2717   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2718                            VK, &BasePath);
2719 }
2720 
2721 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2722                                       const LookupResult &R,
2723                                       bool HasTrailingLParen) {
2724   // Only when used directly as the postfix-expression of a call.
2725   if (!HasTrailingLParen)
2726     return false;
2727 
2728   // Never if a scope specifier was provided.
2729   if (SS.isSet())
2730     return false;
2731 
2732   // Only in C++ or ObjC++.
2733   if (!getLangOpts().CPlusPlus)
2734     return false;
2735 
2736   // Turn off ADL when we find certain kinds of declarations during
2737   // normal lookup:
2738   for (NamedDecl *D : R) {
2739     // C++0x [basic.lookup.argdep]p3:
2740     //     -- a declaration of a class member
2741     // Since using decls preserve this property, we check this on the
2742     // original decl.
2743     if (D->isCXXClassMember())
2744       return false;
2745 
2746     // C++0x [basic.lookup.argdep]p3:
2747     //     -- a block-scope function declaration that is not a
2748     //        using-declaration
2749     // NOTE: we also trigger this for function templates (in fact, we
2750     // don't check the decl type at all, since all other decl types
2751     // turn off ADL anyway).
2752     if (isa<UsingShadowDecl>(D))
2753       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2754     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2755       return false;
2756 
2757     // C++0x [basic.lookup.argdep]p3:
2758     //     -- a declaration that is neither a function or a function
2759     //        template
2760     // And also for builtin functions.
2761     if (isa<FunctionDecl>(D)) {
2762       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2763 
2764       // But also builtin functions.
2765       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2766         return false;
2767     } else if (!isa<FunctionTemplateDecl>(D))
2768       return false;
2769   }
2770 
2771   return true;
2772 }
2773 
2774 
2775 /// Diagnoses obvious problems with the use of the given declaration
2776 /// as an expression.  This is only actually called for lookups that
2777 /// were not overloaded, and it doesn't promise that the declaration
2778 /// will in fact be used.
2779 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2780   if (isa<TypedefNameDecl>(D)) {
2781     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2782     return true;
2783   }
2784 
2785   if (isa<ObjCInterfaceDecl>(D)) {
2786     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2787     return true;
2788   }
2789 
2790   if (isa<NamespaceDecl>(D)) {
2791     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2792     return true;
2793   }
2794 
2795   return false;
2796 }
2797 
2798 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2799                                           LookupResult &R, bool NeedsADL,
2800                                           bool AcceptInvalidDecl) {
2801   // If this is a single, fully-resolved result and we don't need ADL,
2802   // just build an ordinary singleton decl ref.
2803   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2804     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2805                                     R.getRepresentativeDecl(), nullptr,
2806                                     AcceptInvalidDecl);
2807 
2808   // We only need to check the declaration if there's exactly one
2809   // result, because in the overloaded case the results can only be
2810   // functions and function templates.
2811   if (R.isSingleResult() &&
2812       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2813     return ExprError();
2814 
2815   // Otherwise, just build an unresolved lookup expression.  Suppress
2816   // any lookup-related diagnostics; we'll hash these out later, when
2817   // we've picked a target.
2818   R.suppressDiagnostics();
2819 
2820   UnresolvedLookupExpr *ULE
2821     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2822                                    SS.getWithLocInContext(Context),
2823                                    R.getLookupNameInfo(),
2824                                    NeedsADL, R.isOverloadedResult(),
2825                                    R.begin(), R.end());
2826 
2827   return ULE;
2828 }
2829 
2830 static void
2831 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2832                                    ValueDecl *var, DeclContext *DC);
2833 
2834 /// \brief Complete semantic analysis for a reference to the given declaration.
2835 ExprResult Sema::BuildDeclarationNameExpr(
2836     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2837     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2838     bool AcceptInvalidDecl) {
2839   assert(D && "Cannot refer to a NULL declaration");
2840   assert(!isa<FunctionTemplateDecl>(D) &&
2841          "Cannot refer unambiguously to a function template");
2842 
2843   SourceLocation Loc = NameInfo.getLoc();
2844   if (CheckDeclInExpr(*this, Loc, D))
2845     return ExprError();
2846 
2847   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2848     // Specifically diagnose references to class templates that are missing
2849     // a template argument list.
2850     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2851                                            << Template << SS.getRange();
2852     Diag(Template->getLocation(), diag::note_template_decl_here);
2853     return ExprError();
2854   }
2855 
2856   // Make sure that we're referring to a value.
2857   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2858   if (!VD) {
2859     Diag(Loc, diag::err_ref_non_value)
2860       << D << SS.getRange();
2861     Diag(D->getLocation(), diag::note_declared_at);
2862     return ExprError();
2863   }
2864 
2865   // Check whether this declaration can be used. Note that we suppress
2866   // this check when we're going to perform argument-dependent lookup
2867   // on this function name, because this might not be the function
2868   // that overload resolution actually selects.
2869   if (DiagnoseUseOfDecl(VD, Loc))
2870     return ExprError();
2871 
2872   // Only create DeclRefExpr's for valid Decl's.
2873   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2874     return ExprError();
2875 
2876   // Handle members of anonymous structs and unions.  If we got here,
2877   // and the reference is to a class member indirect field, then this
2878   // must be the subject of a pointer-to-member expression.
2879   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2880     if (!indirectField->isCXXClassMember())
2881       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2882                                                       indirectField);
2883 
2884   {
2885     QualType type = VD->getType();
2886     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2887       // C++ [except.spec]p17:
2888       //   An exception-specification is considered to be needed when:
2889       //   - in an expression, the function is the unique lookup result or
2890       //     the selected member of a set of overloaded functions.
2891       ResolveExceptionSpec(Loc, FPT);
2892       type = VD->getType();
2893     }
2894     ExprValueKind valueKind = VK_RValue;
2895 
2896     switch (D->getKind()) {
2897     // Ignore all the non-ValueDecl kinds.
2898 #define ABSTRACT_DECL(kind)
2899 #define VALUE(type, base)
2900 #define DECL(type, base) \
2901     case Decl::type:
2902 #include "clang/AST/DeclNodes.inc"
2903       llvm_unreachable("invalid value decl kind");
2904 
2905     // These shouldn't make it here.
2906     case Decl::ObjCAtDefsField:
2907     case Decl::ObjCIvar:
2908       llvm_unreachable("forming non-member reference to ivar?");
2909 
2910     // Enum constants are always r-values and never references.
2911     // Unresolved using declarations are dependent.
2912     case Decl::EnumConstant:
2913     case Decl::UnresolvedUsingValue:
2914     case Decl::OMPDeclareReduction:
2915       valueKind = VK_RValue;
2916       break;
2917 
2918     // Fields and indirect fields that got here must be for
2919     // pointer-to-member expressions; we just call them l-values for
2920     // internal consistency, because this subexpression doesn't really
2921     // exist in the high-level semantics.
2922     case Decl::Field:
2923     case Decl::IndirectField:
2924       assert(getLangOpts().CPlusPlus &&
2925              "building reference to field in C?");
2926 
2927       // These can't have reference type in well-formed programs, but
2928       // for internal consistency we do this anyway.
2929       type = type.getNonReferenceType();
2930       valueKind = VK_LValue;
2931       break;
2932 
2933     // Non-type template parameters are either l-values or r-values
2934     // depending on the type.
2935     case Decl::NonTypeTemplateParm: {
2936       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2937         type = reftype->getPointeeType();
2938         valueKind = VK_LValue; // even if the parameter is an r-value reference
2939         break;
2940       }
2941 
2942       // For non-references, we need to strip qualifiers just in case
2943       // the template parameter was declared as 'const int' or whatever.
2944       valueKind = VK_RValue;
2945       type = type.getUnqualifiedType();
2946       break;
2947     }
2948 
2949     case Decl::Var:
2950     case Decl::VarTemplateSpecialization:
2951     case Decl::VarTemplatePartialSpecialization:
2952     case Decl::Decomposition:
2953     case Decl::OMPCapturedExpr:
2954       // In C, "extern void blah;" is valid and is an r-value.
2955       if (!getLangOpts().CPlusPlus &&
2956           !type.hasQualifiers() &&
2957           type->isVoidType()) {
2958         valueKind = VK_RValue;
2959         break;
2960       }
2961       // fallthrough
2962 
2963     case Decl::ImplicitParam:
2964     case Decl::ParmVar: {
2965       // These are always l-values.
2966       valueKind = VK_LValue;
2967       type = type.getNonReferenceType();
2968 
2969       // FIXME: Does the addition of const really only apply in
2970       // potentially-evaluated contexts? Since the variable isn't actually
2971       // captured in an unevaluated context, it seems that the answer is no.
2972       if (!isUnevaluatedContext()) {
2973         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2974         if (!CapturedType.isNull())
2975           type = CapturedType;
2976       }
2977 
2978       break;
2979     }
2980 
2981     case Decl::Binding: {
2982       // These are always lvalues.
2983       valueKind = VK_LValue;
2984       type = type.getNonReferenceType();
2985       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2986       // decides how that's supposed to work.
2987       auto *BD = cast<BindingDecl>(VD);
2988       if (BD->getDeclContext()->isFunctionOrMethod() &&
2989           BD->getDeclContext() != CurContext)
2990         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2991       break;
2992     }
2993 
2994     case Decl::Function: {
2995       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2996         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2997           type = Context.BuiltinFnTy;
2998           valueKind = VK_RValue;
2999           break;
3000         }
3001       }
3002 
3003       const FunctionType *fty = type->castAs<FunctionType>();
3004 
3005       // If we're referring to a function with an __unknown_anytype
3006       // result type, make the entire expression __unknown_anytype.
3007       if (fty->getReturnType() == Context.UnknownAnyTy) {
3008         type = Context.UnknownAnyTy;
3009         valueKind = VK_RValue;
3010         break;
3011       }
3012 
3013       // Functions are l-values in C++.
3014       if (getLangOpts().CPlusPlus) {
3015         valueKind = VK_LValue;
3016         break;
3017       }
3018 
3019       // C99 DR 316 says that, if a function type comes from a
3020       // function definition (without a prototype), that type is only
3021       // used for checking compatibility. Therefore, when referencing
3022       // the function, we pretend that we don't have the full function
3023       // type.
3024       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3025           isa<FunctionProtoType>(fty))
3026         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3027                                               fty->getExtInfo());
3028 
3029       // Functions are r-values in C.
3030       valueKind = VK_RValue;
3031       break;
3032     }
3033 
3034     case Decl::MSProperty:
3035       valueKind = VK_LValue;
3036       break;
3037 
3038     case Decl::CXXMethod:
3039       // If we're referring to a method with an __unknown_anytype
3040       // result type, make the entire expression __unknown_anytype.
3041       // This should only be possible with a type written directly.
3042       if (const FunctionProtoType *proto
3043             = dyn_cast<FunctionProtoType>(VD->getType()))
3044         if (proto->getReturnType() == Context.UnknownAnyTy) {
3045           type = Context.UnknownAnyTy;
3046           valueKind = VK_RValue;
3047           break;
3048         }
3049 
3050       // C++ methods are l-values if static, r-values if non-static.
3051       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3052         valueKind = VK_LValue;
3053         break;
3054       }
3055       // fallthrough
3056 
3057     case Decl::CXXConversion:
3058     case Decl::CXXDestructor:
3059     case Decl::CXXConstructor:
3060       valueKind = VK_RValue;
3061       break;
3062     }
3063 
3064     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3065                             TemplateArgs);
3066   }
3067 }
3068 
3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3070                                     SmallString<32> &Target) {
3071   Target.resize(CharByteWidth * (Source.size() + 1));
3072   char *ResultPtr = &Target[0];
3073   const llvm::UTF8 *ErrorPtr;
3074   bool success =
3075       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3076   (void)success;
3077   assert(success);
3078   Target.resize(ResultPtr - &Target[0]);
3079 }
3080 
3081 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3082                                      PredefinedExpr::IdentType IT) {
3083   // Pick the current block, lambda, captured statement or function.
3084   Decl *currentDecl = nullptr;
3085   if (const BlockScopeInfo *BSI = getCurBlock())
3086     currentDecl = BSI->TheDecl;
3087   else if (const LambdaScopeInfo *LSI = getCurLambda())
3088     currentDecl = LSI->CallOperator;
3089   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3090     currentDecl = CSI->TheCapturedDecl;
3091   else
3092     currentDecl = getCurFunctionOrMethodDecl();
3093 
3094   if (!currentDecl) {
3095     Diag(Loc, diag::ext_predef_outside_function);
3096     currentDecl = Context.getTranslationUnitDecl();
3097   }
3098 
3099   QualType ResTy;
3100   StringLiteral *SL = nullptr;
3101   if (cast<DeclContext>(currentDecl)->isDependentContext())
3102     ResTy = Context.DependentTy;
3103   else {
3104     // Pre-defined identifiers are of type char[x], where x is the length of
3105     // the string.
3106     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3107     unsigned Length = Str.length();
3108 
3109     llvm::APInt LengthI(32, Length + 1);
3110     if (IT == PredefinedExpr::LFunction) {
3111       ResTy = Context.WideCharTy.withConst();
3112       SmallString<32> RawChars;
3113       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3114                               Str, RawChars);
3115       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3116                                            /*IndexTypeQuals*/ 0);
3117       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3118                                  /*Pascal*/ false, ResTy, Loc);
3119     } else {
3120       ResTy = Context.CharTy.withConst();
3121       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3122                                            /*IndexTypeQuals*/ 0);
3123       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3124                                  /*Pascal*/ false, ResTy, Loc);
3125     }
3126   }
3127 
3128   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3129 }
3130 
3131 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3132   PredefinedExpr::IdentType IT;
3133 
3134   switch (Kind) {
3135   default: llvm_unreachable("Unknown simple primary expr!");
3136   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3137   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3138   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3139   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3140   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3141   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3142   }
3143 
3144   return BuildPredefinedExpr(Loc, IT);
3145 }
3146 
3147 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3148   SmallString<16> CharBuffer;
3149   bool Invalid = false;
3150   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3151   if (Invalid)
3152     return ExprError();
3153 
3154   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3155                             PP, Tok.getKind());
3156   if (Literal.hadError())
3157     return ExprError();
3158 
3159   QualType Ty;
3160   if (Literal.isWide())
3161     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3162   else if (Literal.isUTF16())
3163     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3164   else if (Literal.isUTF32())
3165     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3166   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3167     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3168   else
3169     Ty = Context.CharTy;  // 'x' -> char in C++
3170 
3171   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3172   if (Literal.isWide())
3173     Kind = CharacterLiteral::Wide;
3174   else if (Literal.isUTF16())
3175     Kind = CharacterLiteral::UTF16;
3176   else if (Literal.isUTF32())
3177     Kind = CharacterLiteral::UTF32;
3178   else if (Literal.isUTF8())
3179     Kind = CharacterLiteral::UTF8;
3180 
3181   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3182                                              Tok.getLocation());
3183 
3184   if (Literal.getUDSuffix().empty())
3185     return Lit;
3186 
3187   // We're building a user-defined literal.
3188   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3189   SourceLocation UDSuffixLoc =
3190     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3191 
3192   // Make sure we're allowed user-defined literals here.
3193   if (!UDLScope)
3194     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3195 
3196   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3197   //   operator "" X (ch)
3198   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3199                                         Lit, Tok.getLocation());
3200 }
3201 
3202 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3203   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3204   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3205                                 Context.IntTy, Loc);
3206 }
3207 
3208 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3209                                   QualType Ty, SourceLocation Loc) {
3210   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3211 
3212   using llvm::APFloat;
3213   APFloat Val(Format);
3214 
3215   APFloat::opStatus result = Literal.GetFloatValue(Val);
3216 
3217   // Overflow is always an error, but underflow is only an error if
3218   // we underflowed to zero (APFloat reports denormals as underflow).
3219   if ((result & APFloat::opOverflow) ||
3220       ((result & APFloat::opUnderflow) && Val.isZero())) {
3221     unsigned diagnostic;
3222     SmallString<20> buffer;
3223     if (result & APFloat::opOverflow) {
3224       diagnostic = diag::warn_float_overflow;
3225       APFloat::getLargest(Format).toString(buffer);
3226     } else {
3227       diagnostic = diag::warn_float_underflow;
3228       APFloat::getSmallest(Format).toString(buffer);
3229     }
3230 
3231     S.Diag(Loc, diagnostic)
3232       << Ty
3233       << StringRef(buffer.data(), buffer.size());
3234   }
3235 
3236   bool isExact = (result == APFloat::opOK);
3237   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3238 }
3239 
3240 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3241   assert(E && "Invalid expression");
3242 
3243   if (E->isValueDependent())
3244     return false;
3245 
3246   QualType QT = E->getType();
3247   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3248     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3249     return true;
3250   }
3251 
3252   llvm::APSInt ValueAPS;
3253   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3254 
3255   if (R.isInvalid())
3256     return true;
3257 
3258   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3259   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3260     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3261         << ValueAPS.toString(10) << ValueIsPositive;
3262     return true;
3263   }
3264 
3265   return false;
3266 }
3267 
3268 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3269   // Fast path for a single digit (which is quite common).  A single digit
3270   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3271   if (Tok.getLength() == 1) {
3272     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3273     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3274   }
3275 
3276   SmallString<128> SpellingBuffer;
3277   // NumericLiteralParser wants to overread by one character.  Add padding to
3278   // the buffer in case the token is copied to the buffer.  If getSpelling()
3279   // returns a StringRef to the memory buffer, it should have a null char at
3280   // the EOF, so it is also safe.
3281   SpellingBuffer.resize(Tok.getLength() + 1);
3282 
3283   // Get the spelling of the token, which eliminates trigraphs, etc.
3284   bool Invalid = false;
3285   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3286   if (Invalid)
3287     return ExprError();
3288 
3289   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3290   if (Literal.hadError)
3291     return ExprError();
3292 
3293   if (Literal.hasUDSuffix()) {
3294     // We're building a user-defined literal.
3295     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296     SourceLocation UDSuffixLoc =
3297       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299     // Make sure we're allowed user-defined literals here.
3300     if (!UDLScope)
3301       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3302 
3303     QualType CookedTy;
3304     if (Literal.isFloatingLiteral()) {
3305       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3306       // long double, the literal is treated as a call of the form
3307       //   operator "" X (f L)
3308       CookedTy = Context.LongDoubleTy;
3309     } else {
3310       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3311       // unsigned long long, the literal is treated as a call of the form
3312       //   operator "" X (n ULL)
3313       CookedTy = Context.UnsignedLongLongTy;
3314     }
3315 
3316     DeclarationName OpName =
3317       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3318     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3319     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3320 
3321     SourceLocation TokLoc = Tok.getLocation();
3322 
3323     // Perform literal operator lookup to determine if we're building a raw
3324     // literal or a cooked one.
3325     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3326     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3327                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3328                                   /*AllowStringTemplate*/false)) {
3329     case LOLR_Error:
3330       return ExprError();
3331 
3332     case LOLR_Cooked: {
3333       Expr *Lit;
3334       if (Literal.isFloatingLiteral()) {
3335         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3336       } else {
3337         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3338         if (Literal.GetIntegerValue(ResultVal))
3339           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3340               << /* Unsigned */ 1;
3341         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3342                                      Tok.getLocation());
3343       }
3344       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3345     }
3346 
3347     case LOLR_Raw: {
3348       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3349       // literal is treated as a call of the form
3350       //   operator "" X ("n")
3351       unsigned Length = Literal.getUDSuffixOffset();
3352       QualType StrTy = Context.getConstantArrayType(
3353           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3354           ArrayType::Normal, 0);
3355       Expr *Lit = StringLiteral::Create(
3356           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3357           /*Pascal*/false, StrTy, &TokLoc, 1);
3358       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3359     }
3360 
3361     case LOLR_Template: {
3362       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3363       // template), L is treated as a call fo the form
3364       //   operator "" X <'c1', 'c2', ... 'ck'>()
3365       // where n is the source character sequence c1 c2 ... ck.
3366       TemplateArgumentListInfo ExplicitArgs;
3367       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3368       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3369       llvm::APSInt Value(CharBits, CharIsUnsigned);
3370       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3371         Value = TokSpelling[I];
3372         TemplateArgument Arg(Context, Value, Context.CharTy);
3373         TemplateArgumentLocInfo ArgInfo;
3374         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3375       }
3376       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3377                                       &ExplicitArgs);
3378     }
3379     case LOLR_StringTemplate:
3380       llvm_unreachable("unexpected literal operator lookup result");
3381     }
3382   }
3383 
3384   Expr *Res;
3385 
3386   if (Literal.isFloatingLiteral()) {
3387     QualType Ty;
3388     if (Literal.isHalf){
3389       if (getOpenCLOptions().cl_khr_fp16)
3390         Ty = Context.HalfTy;
3391       else {
3392         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3393         return ExprError();
3394       }
3395     } else if (Literal.isFloat)
3396       Ty = Context.FloatTy;
3397     else if (Literal.isLong)
3398       Ty = Context.LongDoubleTy;
3399     else if (Literal.isFloat128)
3400       Ty = Context.Float128Ty;
3401     else
3402       Ty = Context.DoubleTy;
3403 
3404     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3405 
3406     if (Ty == Context.DoubleTy) {
3407       if (getLangOpts().SinglePrecisionConstants) {
3408         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3409         if (BTy->getKind() != BuiltinType::Float) {
3410           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3411         }
3412       } else if (getLangOpts().OpenCL &&
3413                  !(getOpenCLOptions().cl_khr_fp64)) {
3414         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3415         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3416         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3417       }
3418     }
3419   } else if (!Literal.isIntegerLiteral()) {
3420     return ExprError();
3421   } else {
3422     QualType Ty;
3423 
3424     // 'long long' is a C99 or C++11 feature.
3425     if (!getLangOpts().C99 && Literal.isLongLong) {
3426       if (getLangOpts().CPlusPlus)
3427         Diag(Tok.getLocation(),
3428              getLangOpts().CPlusPlus11 ?
3429              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3430       else
3431         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3432     }
3433 
3434     // Get the value in the widest-possible width.
3435     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3436     llvm::APInt ResultVal(MaxWidth, 0);
3437 
3438     if (Literal.GetIntegerValue(ResultVal)) {
3439       // If this value didn't fit into uintmax_t, error and force to ull.
3440       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3441           << /* Unsigned */ 1;
3442       Ty = Context.UnsignedLongLongTy;
3443       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3444              "long long is not intmax_t?");
3445     } else {
3446       // If this value fits into a ULL, try to figure out what else it fits into
3447       // according to the rules of C99 6.4.4.1p5.
3448 
3449       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3450       // be an unsigned int.
3451       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3452 
3453       // Check from smallest to largest, picking the smallest type we can.
3454       unsigned Width = 0;
3455 
3456       // Microsoft specific integer suffixes are explicitly sized.
3457       if (Literal.MicrosoftInteger) {
3458         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3459           Width = 8;
3460           Ty = Context.CharTy;
3461         } else {
3462           Width = Literal.MicrosoftInteger;
3463           Ty = Context.getIntTypeForBitwidth(Width,
3464                                              /*Signed=*/!Literal.isUnsigned);
3465         }
3466       }
3467 
3468       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3469         // Are int/unsigned possibilities?
3470         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3471 
3472         // Does it fit in a unsigned int?
3473         if (ResultVal.isIntN(IntSize)) {
3474           // Does it fit in a signed int?
3475           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3476             Ty = Context.IntTy;
3477           else if (AllowUnsigned)
3478             Ty = Context.UnsignedIntTy;
3479           Width = IntSize;
3480         }
3481       }
3482 
3483       // Are long/unsigned long possibilities?
3484       if (Ty.isNull() && !Literal.isLongLong) {
3485         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3486 
3487         // Does it fit in a unsigned long?
3488         if (ResultVal.isIntN(LongSize)) {
3489           // Does it fit in a signed long?
3490           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3491             Ty = Context.LongTy;
3492           else if (AllowUnsigned)
3493             Ty = Context.UnsignedLongTy;
3494           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3495           // is compatible.
3496           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3497             const unsigned LongLongSize =
3498                 Context.getTargetInfo().getLongLongWidth();
3499             Diag(Tok.getLocation(),
3500                  getLangOpts().CPlusPlus
3501                      ? Literal.isLong
3502                            ? diag::warn_old_implicitly_unsigned_long_cxx
3503                            : /*C++98 UB*/ diag::
3504                                  ext_old_implicitly_unsigned_long_cxx
3505                      : diag::warn_old_implicitly_unsigned_long)
3506                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3507                                             : /*will be ill-formed*/ 1);
3508             Ty = Context.UnsignedLongTy;
3509           }
3510           Width = LongSize;
3511         }
3512       }
3513 
3514       // Check long long if needed.
3515       if (Ty.isNull()) {
3516         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3517 
3518         // Does it fit in a unsigned long long?
3519         if (ResultVal.isIntN(LongLongSize)) {
3520           // Does it fit in a signed long long?
3521           // To be compatible with MSVC, hex integer literals ending with the
3522           // LL or i64 suffix are always signed in Microsoft mode.
3523           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3524               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3525             Ty = Context.LongLongTy;
3526           else if (AllowUnsigned)
3527             Ty = Context.UnsignedLongLongTy;
3528           Width = LongLongSize;
3529         }
3530       }
3531 
3532       // If we still couldn't decide a type, we probably have something that
3533       // does not fit in a signed long long, but has no U suffix.
3534       if (Ty.isNull()) {
3535         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3536         Ty = Context.UnsignedLongLongTy;
3537         Width = Context.getTargetInfo().getLongLongWidth();
3538       }
3539 
3540       if (ResultVal.getBitWidth() != Width)
3541         ResultVal = ResultVal.trunc(Width);
3542     }
3543     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3544   }
3545 
3546   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3547   if (Literal.isImaginary)
3548     Res = new (Context) ImaginaryLiteral(Res,
3549                                         Context.getComplexType(Res->getType()));
3550 
3551   return Res;
3552 }
3553 
3554 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3555   assert(E && "ActOnParenExpr() missing expr");
3556   return new (Context) ParenExpr(L, R, E);
3557 }
3558 
3559 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3560                                          SourceLocation Loc,
3561                                          SourceRange ArgRange) {
3562   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3563   // scalar or vector data type argument..."
3564   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3565   // type (C99 6.2.5p18) or void.
3566   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3567     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3568       << T << ArgRange;
3569     return true;
3570   }
3571 
3572   assert((T->isVoidType() || !T->isIncompleteType()) &&
3573          "Scalar types should always be complete");
3574   return false;
3575 }
3576 
3577 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3578                                            SourceLocation Loc,
3579                                            SourceRange ArgRange,
3580                                            UnaryExprOrTypeTrait TraitKind) {
3581   // Invalid types must be hard errors for SFINAE in C++.
3582   if (S.LangOpts.CPlusPlus)
3583     return true;
3584 
3585   // C99 6.5.3.4p1:
3586   if (T->isFunctionType() &&
3587       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3588     // sizeof(function)/alignof(function) is allowed as an extension.
3589     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3590       << TraitKind << ArgRange;
3591     return false;
3592   }
3593 
3594   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3595   // this is an error (OpenCL v1.1 s6.3.k)
3596   if (T->isVoidType()) {
3597     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3598                                         : diag::ext_sizeof_alignof_void_type;
3599     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3600     return false;
3601   }
3602 
3603   return true;
3604 }
3605 
3606 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3607                                              SourceLocation Loc,
3608                                              SourceRange ArgRange,
3609                                              UnaryExprOrTypeTrait TraitKind) {
3610   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3611   // runtime doesn't allow it.
3612   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3613     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3614       << T << (TraitKind == UETT_SizeOf)
3615       << ArgRange;
3616     return true;
3617   }
3618 
3619   return false;
3620 }
3621 
3622 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3623 /// pointer type is equal to T) and emit a warning if it is.
3624 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3625                                      Expr *E) {
3626   // Don't warn if the operation changed the type.
3627   if (T != E->getType())
3628     return;
3629 
3630   // Now look for array decays.
3631   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3632   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3633     return;
3634 
3635   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3636                                              << ICE->getType()
3637                                              << ICE->getSubExpr()->getType();
3638 }
3639 
3640 /// \brief Check the constraints on expression operands to unary type expression
3641 /// and type traits.
3642 ///
3643 /// Completes any types necessary and validates the constraints on the operand
3644 /// expression. The logic mostly mirrors the type-based overload, but may modify
3645 /// the expression as it completes the type for that expression through template
3646 /// instantiation, etc.
3647 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3648                                             UnaryExprOrTypeTrait ExprKind) {
3649   QualType ExprTy = E->getType();
3650   assert(!ExprTy->isReferenceType());
3651 
3652   if (ExprKind == UETT_VecStep)
3653     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3654                                         E->getSourceRange());
3655 
3656   // Whitelist some types as extensions
3657   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3658                                       E->getSourceRange(), ExprKind))
3659     return false;
3660 
3661   // 'alignof' applied to an expression only requires the base element type of
3662   // the expression to be complete. 'sizeof' requires the expression's type to
3663   // be complete (and will attempt to complete it if it's an array of unknown
3664   // bound).
3665   if (ExprKind == UETT_AlignOf) {
3666     if (RequireCompleteType(E->getExprLoc(),
3667                             Context.getBaseElementType(E->getType()),
3668                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3669                             E->getSourceRange()))
3670       return true;
3671   } else {
3672     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3673                                 ExprKind, E->getSourceRange()))
3674       return true;
3675   }
3676 
3677   // Completing the expression's type may have changed it.
3678   ExprTy = E->getType();
3679   assert(!ExprTy->isReferenceType());
3680 
3681   if (ExprTy->isFunctionType()) {
3682     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3683       << ExprKind << E->getSourceRange();
3684     return true;
3685   }
3686 
3687   // The operand for sizeof and alignof is in an unevaluated expression context,
3688   // so side effects could result in unintended consequences.
3689   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3690       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3691     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3692 
3693   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3694                                        E->getSourceRange(), ExprKind))
3695     return true;
3696 
3697   if (ExprKind == UETT_SizeOf) {
3698     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3699       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3700         QualType OType = PVD->getOriginalType();
3701         QualType Type = PVD->getType();
3702         if (Type->isPointerType() && OType->isArrayType()) {
3703           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3704             << Type << OType;
3705           Diag(PVD->getLocation(), diag::note_declared_at);
3706         }
3707       }
3708     }
3709 
3710     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3711     // decays into a pointer and returns an unintended result. This is most
3712     // likely a typo for "sizeof(array) op x".
3713     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3714       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3715                                BO->getLHS());
3716       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3717                                BO->getRHS());
3718     }
3719   }
3720 
3721   return false;
3722 }
3723 
3724 /// \brief Check the constraints on operands to unary expression and type
3725 /// traits.
3726 ///
3727 /// This will complete any types necessary, and validate the various constraints
3728 /// on those operands.
3729 ///
3730 /// The UsualUnaryConversions() function is *not* called by this routine.
3731 /// C99 6.3.2.1p[2-4] all state:
3732 ///   Except when it is the operand of the sizeof operator ...
3733 ///
3734 /// C++ [expr.sizeof]p4
3735 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3736 ///   standard conversions are not applied to the operand of sizeof.
3737 ///
3738 /// This policy is followed for all of the unary trait expressions.
3739 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3740                                             SourceLocation OpLoc,
3741                                             SourceRange ExprRange,
3742                                             UnaryExprOrTypeTrait ExprKind) {
3743   if (ExprType->isDependentType())
3744     return false;
3745 
3746   // C++ [expr.sizeof]p2:
3747   //     When applied to a reference or a reference type, the result
3748   //     is the size of the referenced type.
3749   // C++11 [expr.alignof]p3:
3750   //     When alignof is applied to a reference type, the result
3751   //     shall be the alignment of the referenced type.
3752   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3753     ExprType = Ref->getPointeeType();
3754 
3755   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3756   //   When alignof or _Alignof is applied to an array type, the result
3757   //   is the alignment of the element type.
3758   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3759     ExprType = Context.getBaseElementType(ExprType);
3760 
3761   if (ExprKind == UETT_VecStep)
3762     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3763 
3764   // Whitelist some types as extensions
3765   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3766                                       ExprKind))
3767     return false;
3768 
3769   if (RequireCompleteType(OpLoc, ExprType,
3770                           diag::err_sizeof_alignof_incomplete_type,
3771                           ExprKind, ExprRange))
3772     return true;
3773 
3774   if (ExprType->isFunctionType()) {
3775     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3776       << ExprKind << ExprRange;
3777     return true;
3778   }
3779 
3780   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3781                                        ExprKind))
3782     return true;
3783 
3784   return false;
3785 }
3786 
3787 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3788   E = E->IgnoreParens();
3789 
3790   // Cannot know anything else if the expression is dependent.
3791   if (E->isTypeDependent())
3792     return false;
3793 
3794   if (E->getObjectKind() == OK_BitField) {
3795     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3796        << 1 << E->getSourceRange();
3797     return true;
3798   }
3799 
3800   ValueDecl *D = nullptr;
3801   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3802     D = DRE->getDecl();
3803   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3804     D = ME->getMemberDecl();
3805   }
3806 
3807   // If it's a field, require the containing struct to have a
3808   // complete definition so that we can compute the layout.
3809   //
3810   // This can happen in C++11 onwards, either by naming the member
3811   // in a way that is not transformed into a member access expression
3812   // (in an unevaluated operand, for instance), or by naming the member
3813   // in a trailing-return-type.
3814   //
3815   // For the record, since __alignof__ on expressions is a GCC
3816   // extension, GCC seems to permit this but always gives the
3817   // nonsensical answer 0.
3818   //
3819   // We don't really need the layout here --- we could instead just
3820   // directly check for all the appropriate alignment-lowing
3821   // attributes --- but that would require duplicating a lot of
3822   // logic that just isn't worth duplicating for such a marginal
3823   // use-case.
3824   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3825     // Fast path this check, since we at least know the record has a
3826     // definition if we can find a member of it.
3827     if (!FD->getParent()->isCompleteDefinition()) {
3828       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3829         << E->getSourceRange();
3830       return true;
3831     }
3832 
3833     // Otherwise, if it's a field, and the field doesn't have
3834     // reference type, then it must have a complete type (or be a
3835     // flexible array member, which we explicitly want to
3836     // white-list anyway), which makes the following checks trivial.
3837     if (!FD->getType()->isReferenceType())
3838       return false;
3839   }
3840 
3841   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3842 }
3843 
3844 bool Sema::CheckVecStepExpr(Expr *E) {
3845   E = E->IgnoreParens();
3846 
3847   // Cannot know anything else if the expression is dependent.
3848   if (E->isTypeDependent())
3849     return false;
3850 
3851   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3852 }
3853 
3854 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3855                                         CapturingScopeInfo *CSI) {
3856   assert(T->isVariablyModifiedType());
3857   assert(CSI != nullptr);
3858 
3859   // We're going to walk down into the type and look for VLA expressions.
3860   do {
3861     const Type *Ty = T.getTypePtr();
3862     switch (Ty->getTypeClass()) {
3863 #define TYPE(Class, Base)
3864 #define ABSTRACT_TYPE(Class, Base)
3865 #define NON_CANONICAL_TYPE(Class, Base)
3866 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3867 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3868 #include "clang/AST/TypeNodes.def"
3869       T = QualType();
3870       break;
3871     // These types are never variably-modified.
3872     case Type::Builtin:
3873     case Type::Complex:
3874     case Type::Vector:
3875     case Type::ExtVector:
3876     case Type::Record:
3877     case Type::Enum:
3878     case Type::Elaborated:
3879     case Type::TemplateSpecialization:
3880     case Type::ObjCObject:
3881     case Type::ObjCInterface:
3882     case Type::ObjCObjectPointer:
3883     case Type::ObjCTypeParam:
3884     case Type::Pipe:
3885       llvm_unreachable("type class is never variably-modified!");
3886     case Type::Adjusted:
3887       T = cast<AdjustedType>(Ty)->getOriginalType();
3888       break;
3889     case Type::Decayed:
3890       T = cast<DecayedType>(Ty)->getPointeeType();
3891       break;
3892     case Type::Pointer:
3893       T = cast<PointerType>(Ty)->getPointeeType();
3894       break;
3895     case Type::BlockPointer:
3896       T = cast<BlockPointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::LValueReference:
3899     case Type::RValueReference:
3900       T = cast<ReferenceType>(Ty)->getPointeeType();
3901       break;
3902     case Type::MemberPointer:
3903       T = cast<MemberPointerType>(Ty)->getPointeeType();
3904       break;
3905     case Type::ConstantArray:
3906     case Type::IncompleteArray:
3907       // Losing element qualification here is fine.
3908       T = cast<ArrayType>(Ty)->getElementType();
3909       break;
3910     case Type::VariableArray: {
3911       // Losing element qualification here is fine.
3912       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3913 
3914       // Unknown size indication requires no size computation.
3915       // Otherwise, evaluate and record it.
3916       if (auto Size = VAT->getSizeExpr()) {
3917         if (!CSI->isVLATypeCaptured(VAT)) {
3918           RecordDecl *CapRecord = nullptr;
3919           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3920             CapRecord = LSI->Lambda;
3921           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3922             CapRecord = CRSI->TheRecordDecl;
3923           }
3924           if (CapRecord) {
3925             auto ExprLoc = Size->getExprLoc();
3926             auto SizeType = Context.getSizeType();
3927             // Build the non-static data member.
3928             auto Field =
3929                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3930                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3931                                   /*BW*/ nullptr, /*Mutable*/ false,
3932                                   /*InitStyle*/ ICIS_NoInit);
3933             Field->setImplicit(true);
3934             Field->setAccess(AS_private);
3935             Field->setCapturedVLAType(VAT);
3936             CapRecord->addDecl(Field);
3937 
3938             CSI->addVLATypeCapture(ExprLoc, SizeType);
3939           }
3940         }
3941       }
3942       T = VAT->getElementType();
3943       break;
3944     }
3945     case Type::FunctionProto:
3946     case Type::FunctionNoProto:
3947       T = cast<FunctionType>(Ty)->getReturnType();
3948       break;
3949     case Type::Paren:
3950     case Type::TypeOf:
3951     case Type::UnaryTransform:
3952     case Type::Attributed:
3953     case Type::SubstTemplateTypeParm:
3954     case Type::PackExpansion:
3955       // Keep walking after single level desugaring.
3956       T = T.getSingleStepDesugaredType(Context);
3957       break;
3958     case Type::Typedef:
3959       T = cast<TypedefType>(Ty)->desugar();
3960       break;
3961     case Type::Decltype:
3962       T = cast<DecltypeType>(Ty)->desugar();
3963       break;
3964     case Type::Auto:
3965       T = cast<AutoType>(Ty)->getDeducedType();
3966       break;
3967     case Type::TypeOfExpr:
3968       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3969       break;
3970     case Type::Atomic:
3971       T = cast<AtomicType>(Ty)->getValueType();
3972       break;
3973     }
3974   } while (!T.isNull() && T->isVariablyModifiedType());
3975 }
3976 
3977 /// \brief Build a sizeof or alignof expression given a type operand.
3978 ExprResult
3979 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3980                                      SourceLocation OpLoc,
3981                                      UnaryExprOrTypeTrait ExprKind,
3982                                      SourceRange R) {
3983   if (!TInfo)
3984     return ExprError();
3985 
3986   QualType T = TInfo->getType();
3987 
3988   if (!T->isDependentType() &&
3989       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3990     return ExprError();
3991 
3992   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3993     if (auto *TT = T->getAs<TypedefType>()) {
3994       for (auto I = FunctionScopes.rbegin(),
3995                 E = std::prev(FunctionScopes.rend());
3996            I != E; ++I) {
3997         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3998         if (CSI == nullptr)
3999           break;
4000         DeclContext *DC = nullptr;
4001         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4002           DC = LSI->CallOperator;
4003         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4004           DC = CRSI->TheCapturedDecl;
4005         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4006           DC = BSI->TheDecl;
4007         if (DC) {
4008           if (DC->containsDecl(TT->getDecl()))
4009             break;
4010           captureVariablyModifiedType(Context, T, CSI);
4011         }
4012       }
4013     }
4014   }
4015 
4016   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4017   return new (Context) UnaryExprOrTypeTraitExpr(
4018       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4019 }
4020 
4021 /// \brief Build a sizeof or alignof expression given an expression
4022 /// operand.
4023 ExprResult
4024 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4025                                      UnaryExprOrTypeTrait ExprKind) {
4026   ExprResult PE = CheckPlaceholderExpr(E);
4027   if (PE.isInvalid())
4028     return ExprError();
4029 
4030   E = PE.get();
4031 
4032   // Verify that the operand is valid.
4033   bool isInvalid = false;
4034   if (E->isTypeDependent()) {
4035     // Delay type-checking for type-dependent expressions.
4036   } else if (ExprKind == UETT_AlignOf) {
4037     isInvalid = CheckAlignOfExpr(*this, E);
4038   } else if (ExprKind == UETT_VecStep) {
4039     isInvalid = CheckVecStepExpr(E);
4040   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4041       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4042       isInvalid = true;
4043   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4044     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4045     isInvalid = true;
4046   } else {
4047     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4048   }
4049 
4050   if (isInvalid)
4051     return ExprError();
4052 
4053   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4054     PE = TransformToPotentiallyEvaluated(E);
4055     if (PE.isInvalid()) return ExprError();
4056     E = PE.get();
4057   }
4058 
4059   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4060   return new (Context) UnaryExprOrTypeTraitExpr(
4061       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4062 }
4063 
4064 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4065 /// expr and the same for @c alignof and @c __alignof
4066 /// Note that the ArgRange is invalid if isType is false.
4067 ExprResult
4068 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4069                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4070                                     void *TyOrEx, SourceRange ArgRange) {
4071   // If error parsing type, ignore.
4072   if (!TyOrEx) return ExprError();
4073 
4074   if (IsType) {
4075     TypeSourceInfo *TInfo;
4076     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4077     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4078   }
4079 
4080   Expr *ArgEx = (Expr *)TyOrEx;
4081   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4082   return Result;
4083 }
4084 
4085 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4086                                      bool IsReal) {
4087   if (V.get()->isTypeDependent())
4088     return S.Context.DependentTy;
4089 
4090   // _Real and _Imag are only l-values for normal l-values.
4091   if (V.get()->getObjectKind() != OK_Ordinary) {
4092     V = S.DefaultLvalueConversion(V.get());
4093     if (V.isInvalid())
4094       return QualType();
4095   }
4096 
4097   // These operators return the element type of a complex type.
4098   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4099     return CT->getElementType();
4100 
4101   // Otherwise they pass through real integer and floating point types here.
4102   if (V.get()->getType()->isArithmeticType())
4103     return V.get()->getType();
4104 
4105   // Test for placeholders.
4106   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4107   if (PR.isInvalid()) return QualType();
4108   if (PR.get() != V.get()) {
4109     V = PR;
4110     return CheckRealImagOperand(S, V, Loc, IsReal);
4111   }
4112 
4113   // Reject anything else.
4114   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4115     << (IsReal ? "__real" : "__imag");
4116   return QualType();
4117 }
4118 
4119 
4120 
4121 ExprResult
4122 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4123                           tok::TokenKind Kind, Expr *Input) {
4124   UnaryOperatorKind Opc;
4125   switch (Kind) {
4126   default: llvm_unreachable("Unknown unary op!");
4127   case tok::plusplus:   Opc = UO_PostInc; break;
4128   case tok::minusminus: Opc = UO_PostDec; break;
4129   }
4130 
4131   // Since this might is a postfix expression, get rid of ParenListExprs.
4132   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4133   if (Result.isInvalid()) return ExprError();
4134   Input = Result.get();
4135 
4136   return BuildUnaryOp(S, OpLoc, Opc, Input);
4137 }
4138 
4139 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4140 ///
4141 /// \return true on error
4142 static bool checkArithmeticOnObjCPointer(Sema &S,
4143                                          SourceLocation opLoc,
4144                                          Expr *op) {
4145   assert(op->getType()->isObjCObjectPointerType());
4146   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4147       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4148     return false;
4149 
4150   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4151     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4152     << op->getSourceRange();
4153   return true;
4154 }
4155 
4156 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4157   auto *BaseNoParens = Base->IgnoreParens();
4158   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4159     return MSProp->getPropertyDecl()->getType()->isArrayType();
4160   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4161 }
4162 
4163 ExprResult
4164 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4165                               Expr *idx, SourceLocation rbLoc) {
4166   if (base && !base->getType().isNull() &&
4167       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4168     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4169                                     /*Length=*/nullptr, rbLoc);
4170 
4171   // Since this might be a postfix expression, get rid of ParenListExprs.
4172   if (isa<ParenListExpr>(base)) {
4173     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4174     if (result.isInvalid()) return ExprError();
4175     base = result.get();
4176   }
4177 
4178   // Handle any non-overload placeholder types in the base and index
4179   // expressions.  We can't handle overloads here because the other
4180   // operand might be an overloadable type, in which case the overload
4181   // resolution for the operator overload should get the first crack
4182   // at the overload.
4183   bool IsMSPropertySubscript = false;
4184   if (base->getType()->isNonOverloadPlaceholderType()) {
4185     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4186     if (!IsMSPropertySubscript) {
4187       ExprResult result = CheckPlaceholderExpr(base);
4188       if (result.isInvalid())
4189         return ExprError();
4190       base = result.get();
4191     }
4192   }
4193   if (idx->getType()->isNonOverloadPlaceholderType()) {
4194     ExprResult result = CheckPlaceholderExpr(idx);
4195     if (result.isInvalid()) return ExprError();
4196     idx = result.get();
4197   }
4198 
4199   // Build an unanalyzed expression if either operand is type-dependent.
4200   if (getLangOpts().CPlusPlus &&
4201       (base->isTypeDependent() || idx->isTypeDependent())) {
4202     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4203                                             VK_LValue, OK_Ordinary, rbLoc);
4204   }
4205 
4206   // MSDN, property (C++)
4207   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4208   // This attribute can also be used in the declaration of an empty array in a
4209   // class or structure definition. For example:
4210   // __declspec(property(get=GetX, put=PutX)) int x[];
4211   // The above statement indicates that x[] can be used with one or more array
4212   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4213   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4214   if (IsMSPropertySubscript) {
4215     // Build MS property subscript expression if base is MS property reference
4216     // or MS property subscript.
4217     return new (Context) MSPropertySubscriptExpr(
4218         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4219   }
4220 
4221   // Use C++ overloaded-operator rules if either operand has record
4222   // type.  The spec says to do this if either type is *overloadable*,
4223   // but enum types can't declare subscript operators or conversion
4224   // operators, so there's nothing interesting for overload resolution
4225   // to do if there aren't any record types involved.
4226   //
4227   // ObjC pointers have their own subscripting logic that is not tied
4228   // to overload resolution and so should not take this path.
4229   if (getLangOpts().CPlusPlus &&
4230       (base->getType()->isRecordType() ||
4231        (!base->getType()->isObjCObjectPointerType() &&
4232         idx->getType()->isRecordType()))) {
4233     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4234   }
4235 
4236   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4237 }
4238 
4239 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4240                                           Expr *LowerBound,
4241                                           SourceLocation ColonLoc, Expr *Length,
4242                                           SourceLocation RBLoc) {
4243   if (Base->getType()->isPlaceholderType() &&
4244       !Base->getType()->isSpecificPlaceholderType(
4245           BuiltinType::OMPArraySection)) {
4246     ExprResult Result = CheckPlaceholderExpr(Base);
4247     if (Result.isInvalid())
4248       return ExprError();
4249     Base = Result.get();
4250   }
4251   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4252     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4253     if (Result.isInvalid())
4254       return ExprError();
4255     Result = DefaultLvalueConversion(Result.get());
4256     if (Result.isInvalid())
4257       return ExprError();
4258     LowerBound = Result.get();
4259   }
4260   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4261     ExprResult Result = CheckPlaceholderExpr(Length);
4262     if (Result.isInvalid())
4263       return ExprError();
4264     Result = DefaultLvalueConversion(Result.get());
4265     if (Result.isInvalid())
4266       return ExprError();
4267     Length = Result.get();
4268   }
4269 
4270   // Build an unanalyzed expression if either operand is type-dependent.
4271   if (Base->isTypeDependent() ||
4272       (LowerBound &&
4273        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4274       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4275     return new (Context)
4276         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4277                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4278   }
4279 
4280   // Perform default conversions.
4281   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4282   QualType ResultTy;
4283   if (OriginalTy->isAnyPointerType()) {
4284     ResultTy = OriginalTy->getPointeeType();
4285   } else if (OriginalTy->isArrayType()) {
4286     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4287   } else {
4288     return ExprError(
4289         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4290         << Base->getSourceRange());
4291   }
4292   // C99 6.5.2.1p1
4293   if (LowerBound) {
4294     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4295                                                       LowerBound);
4296     if (Res.isInvalid())
4297       return ExprError(Diag(LowerBound->getExprLoc(),
4298                             diag::err_omp_typecheck_section_not_integer)
4299                        << 0 << LowerBound->getSourceRange());
4300     LowerBound = Res.get();
4301 
4302     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4303         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4304       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4305           << 0 << LowerBound->getSourceRange();
4306   }
4307   if (Length) {
4308     auto Res =
4309         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4310     if (Res.isInvalid())
4311       return ExprError(Diag(Length->getExprLoc(),
4312                             diag::err_omp_typecheck_section_not_integer)
4313                        << 1 << Length->getSourceRange());
4314     Length = Res.get();
4315 
4316     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4317         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4318       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4319           << 1 << Length->getSourceRange();
4320   }
4321 
4322   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4323   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4324   // type. Note that functions are not objects, and that (in C99 parlance)
4325   // incomplete types are not object types.
4326   if (ResultTy->isFunctionType()) {
4327     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4328         << ResultTy << Base->getSourceRange();
4329     return ExprError();
4330   }
4331 
4332   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4333                           diag::err_omp_section_incomplete_type, Base))
4334     return ExprError();
4335 
4336   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4337     llvm::APSInt LowerBoundValue;
4338     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4339       // OpenMP 4.5, [2.4 Array Sections]
4340       // The array section must be a subset of the original array.
4341       if (LowerBoundValue.isNegative()) {
4342         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4343             << LowerBound->getSourceRange();
4344         return ExprError();
4345       }
4346     }
4347   }
4348 
4349   if (Length) {
4350     llvm::APSInt LengthValue;
4351     if (Length->EvaluateAsInt(LengthValue, Context)) {
4352       // OpenMP 4.5, [2.4 Array Sections]
4353       // The length must evaluate to non-negative integers.
4354       if (LengthValue.isNegative()) {
4355         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4356             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4357             << Length->getSourceRange();
4358         return ExprError();
4359       }
4360     }
4361   } else if (ColonLoc.isValid() &&
4362              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4363                                       !OriginalTy->isVariableArrayType()))) {
4364     // OpenMP 4.5, [2.4 Array Sections]
4365     // When the size of the array dimension is not known, the length must be
4366     // specified explicitly.
4367     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4368         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4369     return ExprError();
4370   }
4371 
4372   if (!Base->getType()->isSpecificPlaceholderType(
4373           BuiltinType::OMPArraySection)) {
4374     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4375     if (Result.isInvalid())
4376       return ExprError();
4377     Base = Result.get();
4378   }
4379   return new (Context)
4380       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4381                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4382 }
4383 
4384 ExprResult
4385 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4386                                       Expr *Idx, SourceLocation RLoc) {
4387   Expr *LHSExp = Base;
4388   Expr *RHSExp = Idx;
4389 
4390   ExprValueKind VK = VK_LValue;
4391   ExprObjectKind OK = OK_Ordinary;
4392 
4393   // Per C++ core issue 1213, the result is an xvalue if either operand is
4394   // a non-lvalue array, and an lvalue otherwise.
4395   if (getLangOpts().CPlusPlus11 &&
4396       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4397        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4398     VK = VK_XValue;
4399 
4400   // Perform default conversions.
4401   if (!LHSExp->getType()->getAs<VectorType>()) {
4402     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4403     if (Result.isInvalid())
4404       return ExprError();
4405     LHSExp = Result.get();
4406   }
4407   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4408   if (Result.isInvalid())
4409     return ExprError();
4410   RHSExp = Result.get();
4411 
4412   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4413 
4414   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4415   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4416   // in the subscript position. As a result, we need to derive the array base
4417   // and index from the expression types.
4418   Expr *BaseExpr, *IndexExpr;
4419   QualType ResultType;
4420   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4421     BaseExpr = LHSExp;
4422     IndexExpr = RHSExp;
4423     ResultType = Context.DependentTy;
4424   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4425     BaseExpr = LHSExp;
4426     IndexExpr = RHSExp;
4427     ResultType = PTy->getPointeeType();
4428   } else if (const ObjCObjectPointerType *PTy =
4429                LHSTy->getAs<ObjCObjectPointerType>()) {
4430     BaseExpr = LHSExp;
4431     IndexExpr = RHSExp;
4432 
4433     // Use custom logic if this should be the pseudo-object subscript
4434     // expression.
4435     if (!LangOpts.isSubscriptPointerArithmetic())
4436       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4437                                           nullptr);
4438 
4439     ResultType = PTy->getPointeeType();
4440   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4441      // Handle the uncommon case of "123[Ptr]".
4442     BaseExpr = RHSExp;
4443     IndexExpr = LHSExp;
4444     ResultType = PTy->getPointeeType();
4445   } else if (const ObjCObjectPointerType *PTy =
4446                RHSTy->getAs<ObjCObjectPointerType>()) {
4447      // Handle the uncommon case of "123[Ptr]".
4448     BaseExpr = RHSExp;
4449     IndexExpr = LHSExp;
4450     ResultType = PTy->getPointeeType();
4451     if (!LangOpts.isSubscriptPointerArithmetic()) {
4452       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4453         << ResultType << BaseExpr->getSourceRange();
4454       return ExprError();
4455     }
4456   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4457     BaseExpr = LHSExp;    // vectors: V[123]
4458     IndexExpr = RHSExp;
4459     VK = LHSExp->getValueKind();
4460     if (VK != VK_RValue)
4461       OK = OK_VectorComponent;
4462 
4463     // FIXME: need to deal with const...
4464     ResultType = VTy->getElementType();
4465   } else if (LHSTy->isArrayType()) {
4466     // If we see an array that wasn't promoted by
4467     // DefaultFunctionArrayLvalueConversion, it must be an array that
4468     // wasn't promoted because of the C90 rule that doesn't
4469     // allow promoting non-lvalue arrays.  Warn, then
4470     // force the promotion here.
4471     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4472         LHSExp->getSourceRange();
4473     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4474                                CK_ArrayToPointerDecay).get();
4475     LHSTy = LHSExp->getType();
4476 
4477     BaseExpr = LHSExp;
4478     IndexExpr = RHSExp;
4479     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4480   } else if (RHSTy->isArrayType()) {
4481     // Same as previous, except for 123[f().a] case
4482     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4483         RHSExp->getSourceRange();
4484     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4485                                CK_ArrayToPointerDecay).get();
4486     RHSTy = RHSExp->getType();
4487 
4488     BaseExpr = RHSExp;
4489     IndexExpr = LHSExp;
4490     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4491   } else {
4492     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4493        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4494   }
4495   // C99 6.5.2.1p1
4496   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4497     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4498                      << IndexExpr->getSourceRange());
4499 
4500   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4501        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4502          && !IndexExpr->isTypeDependent())
4503     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4504 
4505   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4506   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4507   // type. Note that Functions are not objects, and that (in C99 parlance)
4508   // incomplete types are not object types.
4509   if (ResultType->isFunctionType()) {
4510     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4511       << ResultType << BaseExpr->getSourceRange();
4512     return ExprError();
4513   }
4514 
4515   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4516     // GNU extension: subscripting on pointer to void
4517     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4518       << BaseExpr->getSourceRange();
4519 
4520     // C forbids expressions of unqualified void type from being l-values.
4521     // See IsCForbiddenLValueType.
4522     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4523   } else if (!ResultType->isDependentType() &&
4524       RequireCompleteType(LLoc, ResultType,
4525                           diag::err_subscript_incomplete_type, BaseExpr))
4526     return ExprError();
4527 
4528   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4529          !ResultType.isCForbiddenLValueType());
4530 
4531   return new (Context)
4532       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4533 }
4534 
4535 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4536                                   ParmVarDecl *Param) {
4537   if (Param->hasUnparsedDefaultArg()) {
4538     Diag(CallLoc,
4539          diag::err_use_of_default_argument_to_function_declared_later) <<
4540       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4541     Diag(UnparsedDefaultArgLocs[Param],
4542          diag::note_default_argument_declared_here);
4543     return true;
4544   }
4545 
4546   if (Param->hasUninstantiatedDefaultArg()) {
4547     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4548 
4549     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4550                                                  Param);
4551 
4552     // Instantiate the expression.
4553     MultiLevelTemplateArgumentList MutiLevelArgList
4554       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4555 
4556     InstantiatingTemplate Inst(*this, CallLoc, Param,
4557                                MutiLevelArgList.getInnermost());
4558     if (Inst.isInvalid())
4559       return true;
4560     if (Inst.isAlreadyInstantiating()) {
4561       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4562       Param->setInvalidDecl();
4563       return true;
4564     }
4565 
4566     ExprResult Result;
4567     {
4568       // C++ [dcl.fct.default]p5:
4569       //   The names in the [default argument] expression are bound, and
4570       //   the semantic constraints are checked, at the point where the
4571       //   default argument expression appears.
4572       ContextRAII SavedContext(*this, FD);
4573       LocalInstantiationScope Local(*this);
4574       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4575                                 /*DirectInit*/false);
4576     }
4577     if (Result.isInvalid())
4578       return true;
4579 
4580     // Check the expression as an initializer for the parameter.
4581     InitializedEntity Entity
4582       = InitializedEntity::InitializeParameter(Context, Param);
4583     InitializationKind Kind
4584       = InitializationKind::CreateCopy(Param->getLocation(),
4585              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4586     Expr *ResultE = Result.getAs<Expr>();
4587 
4588     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4589     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4590     if (Result.isInvalid())
4591       return true;
4592 
4593     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4594                                  Param->getOuterLocStart());
4595     if (Result.isInvalid())
4596       return true;
4597 
4598     // Remember the instantiated default argument.
4599     Param->setDefaultArg(Result.getAs<Expr>());
4600     if (ASTMutationListener *L = getASTMutationListener()) {
4601       L->DefaultArgumentInstantiated(Param);
4602     }
4603   }
4604 
4605   // If the default argument expression is not set yet, we are building it now.
4606   if (!Param->hasInit()) {
4607     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4608     Param->setInvalidDecl();
4609     return true;
4610   }
4611 
4612   // If the default expression creates temporaries, we need to
4613   // push them to the current stack of expression temporaries so they'll
4614   // be properly destroyed.
4615   // FIXME: We should really be rebuilding the default argument with new
4616   // bound temporaries; see the comment in PR5810.
4617   // We don't need to do that with block decls, though, because
4618   // blocks in default argument expression can never capture anything.
4619   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4620     // Set the "needs cleanups" bit regardless of whether there are
4621     // any explicit objects.
4622     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4623 
4624     // Append all the objects to the cleanup list.  Right now, this
4625     // should always be a no-op, because blocks in default argument
4626     // expressions should never be able to capture anything.
4627     assert(!Init->getNumObjects() &&
4628            "default argument expression has capturing blocks?");
4629   }
4630 
4631   // We already type-checked the argument, so we know it works.
4632   // Just mark all of the declarations in this potentially-evaluated expression
4633   // as being "referenced".
4634   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4635                                    /*SkipLocalVariables=*/true);
4636   return false;
4637 }
4638 
4639 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4640                                         FunctionDecl *FD, ParmVarDecl *Param) {
4641   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4642     return ExprError();
4643   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4644 }
4645 
4646 Sema::VariadicCallType
4647 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4648                           Expr *Fn) {
4649   if (Proto && Proto->isVariadic()) {
4650     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4651       return VariadicConstructor;
4652     else if (Fn && Fn->getType()->isBlockPointerType())
4653       return VariadicBlock;
4654     else if (FDecl) {
4655       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4656         if (Method->isInstance())
4657           return VariadicMethod;
4658     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4659       return VariadicMethod;
4660     return VariadicFunction;
4661   }
4662   return VariadicDoesNotApply;
4663 }
4664 
4665 namespace {
4666 class FunctionCallCCC : public FunctionCallFilterCCC {
4667 public:
4668   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4669                   unsigned NumArgs, MemberExpr *ME)
4670       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4671         FunctionName(FuncName) {}
4672 
4673   bool ValidateCandidate(const TypoCorrection &candidate) override {
4674     if (!candidate.getCorrectionSpecifier() ||
4675         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4676       return false;
4677     }
4678 
4679     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4680   }
4681 
4682 private:
4683   const IdentifierInfo *const FunctionName;
4684 };
4685 }
4686 
4687 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4688                                                FunctionDecl *FDecl,
4689                                                ArrayRef<Expr *> Args) {
4690   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4691   DeclarationName FuncName = FDecl->getDeclName();
4692   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4693 
4694   if (TypoCorrection Corrected = S.CorrectTypo(
4695           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4696           S.getScopeForContext(S.CurContext), nullptr,
4697           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4698                                              Args.size(), ME),
4699           Sema::CTK_ErrorRecovery)) {
4700     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4701       if (Corrected.isOverloaded()) {
4702         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4703         OverloadCandidateSet::iterator Best;
4704         for (NamedDecl *CD : Corrected) {
4705           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4706             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4707                                    OCS);
4708         }
4709         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4710         case OR_Success:
4711           ND = Best->FoundDecl;
4712           Corrected.setCorrectionDecl(ND);
4713           break;
4714         default:
4715           break;
4716         }
4717       }
4718       ND = ND->getUnderlyingDecl();
4719       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4720         return Corrected;
4721     }
4722   }
4723   return TypoCorrection();
4724 }
4725 
4726 /// ConvertArgumentsForCall - Converts the arguments specified in
4727 /// Args/NumArgs to the parameter types of the function FDecl with
4728 /// function prototype Proto. Call is the call expression itself, and
4729 /// Fn is the function expression. For a C++ member function, this
4730 /// routine does not attempt to convert the object argument. Returns
4731 /// true if the call is ill-formed.
4732 bool
4733 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4734                               FunctionDecl *FDecl,
4735                               const FunctionProtoType *Proto,
4736                               ArrayRef<Expr *> Args,
4737                               SourceLocation RParenLoc,
4738                               bool IsExecConfig) {
4739   // Bail out early if calling a builtin with custom typechecking.
4740   if (FDecl)
4741     if (unsigned ID = FDecl->getBuiltinID())
4742       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4743         return false;
4744 
4745   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4746   // assignment, to the types of the corresponding parameter, ...
4747   unsigned NumParams = Proto->getNumParams();
4748   bool Invalid = false;
4749   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4750   unsigned FnKind = Fn->getType()->isBlockPointerType()
4751                        ? 1 /* block */
4752                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4753                                        : 0 /* function */);
4754 
4755   // If too few arguments are available (and we don't have default
4756   // arguments for the remaining parameters), don't make the call.
4757   if (Args.size() < NumParams) {
4758     if (Args.size() < MinArgs) {
4759       TypoCorrection TC;
4760       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4761         unsigned diag_id =
4762             MinArgs == NumParams && !Proto->isVariadic()
4763                 ? diag::err_typecheck_call_too_few_args_suggest
4764                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4765         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4766                                         << static_cast<unsigned>(Args.size())
4767                                         << TC.getCorrectionRange());
4768       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4769         Diag(RParenLoc,
4770              MinArgs == NumParams && !Proto->isVariadic()
4771                  ? diag::err_typecheck_call_too_few_args_one
4772                  : diag::err_typecheck_call_too_few_args_at_least_one)
4773             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4774       else
4775         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4776                             ? diag::err_typecheck_call_too_few_args
4777                             : diag::err_typecheck_call_too_few_args_at_least)
4778             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4779             << Fn->getSourceRange();
4780 
4781       // Emit the location of the prototype.
4782       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4783         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4784           << FDecl;
4785 
4786       return true;
4787     }
4788     Call->setNumArgs(Context, NumParams);
4789   }
4790 
4791   // If too many are passed and not variadic, error on the extras and drop
4792   // them.
4793   if (Args.size() > NumParams) {
4794     if (!Proto->isVariadic()) {
4795       TypoCorrection TC;
4796       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4797         unsigned diag_id =
4798             MinArgs == NumParams && !Proto->isVariadic()
4799                 ? diag::err_typecheck_call_too_many_args_suggest
4800                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4801         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4802                                         << static_cast<unsigned>(Args.size())
4803                                         << TC.getCorrectionRange());
4804       } else if (NumParams == 1 && FDecl &&
4805                  FDecl->getParamDecl(0)->getDeclName())
4806         Diag(Args[NumParams]->getLocStart(),
4807              MinArgs == NumParams
4808                  ? diag::err_typecheck_call_too_many_args_one
4809                  : diag::err_typecheck_call_too_many_args_at_most_one)
4810             << FnKind << FDecl->getParamDecl(0)
4811             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4812             << SourceRange(Args[NumParams]->getLocStart(),
4813                            Args.back()->getLocEnd());
4814       else
4815         Diag(Args[NumParams]->getLocStart(),
4816              MinArgs == NumParams
4817                  ? diag::err_typecheck_call_too_many_args
4818                  : diag::err_typecheck_call_too_many_args_at_most)
4819             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4820             << Fn->getSourceRange()
4821             << SourceRange(Args[NumParams]->getLocStart(),
4822                            Args.back()->getLocEnd());
4823 
4824       // Emit the location of the prototype.
4825       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4826         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4827           << FDecl;
4828 
4829       // This deletes the extra arguments.
4830       Call->setNumArgs(Context, NumParams);
4831       return true;
4832     }
4833   }
4834   SmallVector<Expr *, 8> AllArgs;
4835   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4836 
4837   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4838                                    Proto, 0, Args, AllArgs, CallType);
4839   if (Invalid)
4840     return true;
4841   unsigned TotalNumArgs = AllArgs.size();
4842   for (unsigned i = 0; i < TotalNumArgs; ++i)
4843     Call->setArg(i, AllArgs[i]);
4844 
4845   return false;
4846 }
4847 
4848 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4849                                   const FunctionProtoType *Proto,
4850                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4851                                   SmallVectorImpl<Expr *> &AllArgs,
4852                                   VariadicCallType CallType, bool AllowExplicit,
4853                                   bool IsListInitialization) {
4854   unsigned NumParams = Proto->getNumParams();
4855   bool Invalid = false;
4856   size_t ArgIx = 0;
4857   // Continue to check argument types (even if we have too few/many args).
4858   for (unsigned i = FirstParam; i < NumParams; i++) {
4859     QualType ProtoArgType = Proto->getParamType(i);
4860 
4861     Expr *Arg;
4862     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4863     if (ArgIx < Args.size()) {
4864       Arg = Args[ArgIx++];
4865 
4866       if (RequireCompleteType(Arg->getLocStart(),
4867                               ProtoArgType,
4868                               diag::err_call_incomplete_argument, Arg))
4869         return true;
4870 
4871       // Strip the unbridged-cast placeholder expression off, if applicable.
4872       bool CFAudited = false;
4873       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4874           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4875           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4876         Arg = stripARCUnbridgedCast(Arg);
4877       else if (getLangOpts().ObjCAutoRefCount &&
4878                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4879                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4880         CFAudited = true;
4881 
4882       InitializedEntity Entity =
4883           Param ? InitializedEntity::InitializeParameter(Context, Param,
4884                                                          ProtoArgType)
4885                 : InitializedEntity::InitializeParameter(
4886                       Context, ProtoArgType, Proto->isParamConsumed(i));
4887 
4888       // Remember that parameter belongs to a CF audited API.
4889       if (CFAudited)
4890         Entity.setParameterCFAudited();
4891 
4892       ExprResult ArgE = PerformCopyInitialization(
4893           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4894       if (ArgE.isInvalid())
4895         return true;
4896 
4897       Arg = ArgE.getAs<Expr>();
4898     } else {
4899       assert(Param && "can't use default arguments without a known callee");
4900 
4901       ExprResult ArgExpr =
4902         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4903       if (ArgExpr.isInvalid())
4904         return true;
4905 
4906       Arg = ArgExpr.getAs<Expr>();
4907     }
4908 
4909     // Check for array bounds violations for each argument to the call. This
4910     // check only triggers warnings when the argument isn't a more complex Expr
4911     // with its own checking, such as a BinaryOperator.
4912     CheckArrayAccess(Arg);
4913 
4914     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4915     CheckStaticArrayArgument(CallLoc, Param, Arg);
4916 
4917     AllArgs.push_back(Arg);
4918   }
4919 
4920   // If this is a variadic call, handle args passed through "...".
4921   if (CallType != VariadicDoesNotApply) {
4922     // Assume that extern "C" functions with variadic arguments that
4923     // return __unknown_anytype aren't *really* variadic.
4924     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4925         FDecl->isExternC()) {
4926       for (Expr *A : Args.slice(ArgIx)) {
4927         QualType paramType; // ignored
4928         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4929         Invalid |= arg.isInvalid();
4930         AllArgs.push_back(arg.get());
4931       }
4932 
4933     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4934     } else {
4935       for (Expr *A : Args.slice(ArgIx)) {
4936         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4937         Invalid |= Arg.isInvalid();
4938         AllArgs.push_back(Arg.get());
4939       }
4940     }
4941 
4942     // Check for array bounds violations.
4943     for (Expr *A : Args.slice(ArgIx))
4944       CheckArrayAccess(A);
4945   }
4946   return Invalid;
4947 }
4948 
4949 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4950   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4951   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4952     TL = DTL.getOriginalLoc();
4953   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4954     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4955       << ATL.getLocalSourceRange();
4956 }
4957 
4958 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4959 /// array parameter, check that it is non-null, and that if it is formed by
4960 /// array-to-pointer decay, the underlying array is sufficiently large.
4961 ///
4962 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4963 /// array type derivation, then for each call to the function, the value of the
4964 /// corresponding actual argument shall provide access to the first element of
4965 /// an array with at least as many elements as specified by the size expression.
4966 void
4967 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4968                                ParmVarDecl *Param,
4969                                const Expr *ArgExpr) {
4970   // Static array parameters are not supported in C++.
4971   if (!Param || getLangOpts().CPlusPlus)
4972     return;
4973 
4974   QualType OrigTy = Param->getOriginalType();
4975 
4976   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4977   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4978     return;
4979 
4980   if (ArgExpr->isNullPointerConstant(Context,
4981                                      Expr::NPC_NeverValueDependent)) {
4982     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4983     DiagnoseCalleeStaticArrayParam(*this, Param);
4984     return;
4985   }
4986 
4987   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4988   if (!CAT)
4989     return;
4990 
4991   const ConstantArrayType *ArgCAT =
4992     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4993   if (!ArgCAT)
4994     return;
4995 
4996   if (ArgCAT->getSize().ult(CAT->getSize())) {
4997     Diag(CallLoc, diag::warn_static_array_too_small)
4998       << ArgExpr->getSourceRange()
4999       << (unsigned) ArgCAT->getSize().getZExtValue()
5000       << (unsigned) CAT->getSize().getZExtValue();
5001     DiagnoseCalleeStaticArrayParam(*this, Param);
5002   }
5003 }
5004 
5005 /// Given a function expression of unknown-any type, try to rebuild it
5006 /// to have a function type.
5007 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5008 
5009 /// Is the given type a placeholder that we need to lower out
5010 /// immediately during argument processing?
5011 static bool isPlaceholderToRemoveAsArg(QualType type) {
5012   // Placeholders are never sugared.
5013   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5014   if (!placeholder) return false;
5015 
5016   switch (placeholder->getKind()) {
5017   // Ignore all the non-placeholder types.
5018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5019   case BuiltinType::Id:
5020 #include "clang/Basic/OpenCLImageTypes.def"
5021 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5022 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5023 #include "clang/AST/BuiltinTypes.def"
5024     return false;
5025 
5026   // We cannot lower out overload sets; they might validly be resolved
5027   // by the call machinery.
5028   case BuiltinType::Overload:
5029     return false;
5030 
5031   // Unbridged casts in ARC can be handled in some call positions and
5032   // should be left in place.
5033   case BuiltinType::ARCUnbridgedCast:
5034     return false;
5035 
5036   // Pseudo-objects should be converted as soon as possible.
5037   case BuiltinType::PseudoObject:
5038     return true;
5039 
5040   // The debugger mode could theoretically but currently does not try
5041   // to resolve unknown-typed arguments based on known parameter types.
5042   case BuiltinType::UnknownAny:
5043     return true;
5044 
5045   // These are always invalid as call arguments and should be reported.
5046   case BuiltinType::BoundMember:
5047   case BuiltinType::BuiltinFn:
5048   case BuiltinType::OMPArraySection:
5049     return true;
5050 
5051   }
5052   llvm_unreachable("bad builtin type kind");
5053 }
5054 
5055 /// Check an argument list for placeholders that we won't try to
5056 /// handle later.
5057 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5058   // Apply this processing to all the arguments at once instead of
5059   // dying at the first failure.
5060   bool hasInvalid = false;
5061   for (size_t i = 0, e = args.size(); i != e; i++) {
5062     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5063       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5064       if (result.isInvalid()) hasInvalid = true;
5065       else args[i] = result.get();
5066     } else if (hasInvalid) {
5067       (void)S.CorrectDelayedTyposInExpr(args[i]);
5068     }
5069   }
5070   return hasInvalid;
5071 }
5072 
5073 /// If a builtin function has a pointer argument with no explicit address
5074 /// space, then it should be able to accept a pointer to any address
5075 /// space as input.  In order to do this, we need to replace the
5076 /// standard builtin declaration with one that uses the same address space
5077 /// as the call.
5078 ///
5079 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5080 ///                  it does not contain any pointer arguments without
5081 ///                  an address space qualifer.  Otherwise the rewritten
5082 ///                  FunctionDecl is returned.
5083 /// TODO: Handle pointer return types.
5084 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5085                                                 const FunctionDecl *FDecl,
5086                                                 MultiExprArg ArgExprs) {
5087 
5088   QualType DeclType = FDecl->getType();
5089   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5090 
5091   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5092       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5093     return nullptr;
5094 
5095   bool NeedsNewDecl = false;
5096   unsigned i = 0;
5097   SmallVector<QualType, 8> OverloadParams;
5098 
5099   for (QualType ParamType : FT->param_types()) {
5100 
5101     // Convert array arguments to pointer to simplify type lookup.
5102     ExprResult ArgRes =
5103         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5104     if (ArgRes.isInvalid())
5105       return nullptr;
5106     Expr *Arg = ArgRes.get();
5107     QualType ArgType = Arg->getType();
5108     if (!ParamType->isPointerType() ||
5109         ParamType.getQualifiers().hasAddressSpace() ||
5110         !ArgType->isPointerType() ||
5111         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5112       OverloadParams.push_back(ParamType);
5113       continue;
5114     }
5115 
5116     NeedsNewDecl = true;
5117     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5118 
5119     QualType PointeeType = ParamType->getPointeeType();
5120     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5121     OverloadParams.push_back(Context.getPointerType(PointeeType));
5122   }
5123 
5124   if (!NeedsNewDecl)
5125     return nullptr;
5126 
5127   FunctionProtoType::ExtProtoInfo EPI;
5128   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5129                                                 OverloadParams, EPI);
5130   DeclContext *Parent = Context.getTranslationUnitDecl();
5131   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5132                                                     FDecl->getLocation(),
5133                                                     FDecl->getLocation(),
5134                                                     FDecl->getIdentifier(),
5135                                                     OverloadTy,
5136                                                     /*TInfo=*/nullptr,
5137                                                     SC_Extern, false,
5138                                                     /*hasPrototype=*/true);
5139   SmallVector<ParmVarDecl*, 16> Params;
5140   FT = cast<FunctionProtoType>(OverloadTy);
5141   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5142     QualType ParamType = FT->getParamType(i);
5143     ParmVarDecl *Parm =
5144         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5145                                 SourceLocation(), nullptr, ParamType,
5146                                 /*TInfo=*/nullptr, SC_None, nullptr);
5147     Parm->setScopeInfo(0, i);
5148     Params.push_back(Parm);
5149   }
5150   OverloadDecl->setParams(Params);
5151   return OverloadDecl;
5152 }
5153 
5154 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5155                                        std::size_t NumArgs) {
5156   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5157                          /*PartialOverloading=*/false))
5158     return Callee->isVariadic();
5159   return Callee->getMinRequiredArguments() <= NumArgs;
5160 }
5161 
5162 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5163 /// This provides the location of the left/right parens and a list of comma
5164 /// locations.
5165 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5166                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5167                                Expr *ExecConfig, bool IsExecConfig) {
5168   // Since this might be a postfix expression, get rid of ParenListExprs.
5169   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5170   if (Result.isInvalid()) return ExprError();
5171   Fn = Result.get();
5172 
5173   if (checkArgsForPlaceholders(*this, ArgExprs))
5174     return ExprError();
5175 
5176   if (getLangOpts().CPlusPlus) {
5177     // If this is a pseudo-destructor expression, build the call immediately.
5178     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5179       if (!ArgExprs.empty()) {
5180         // Pseudo-destructor calls should not have any arguments.
5181         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5182             << FixItHint::CreateRemoval(
5183                    SourceRange(ArgExprs.front()->getLocStart(),
5184                                ArgExprs.back()->getLocEnd()));
5185       }
5186 
5187       return new (Context)
5188           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5189     }
5190     if (Fn->getType() == Context.PseudoObjectTy) {
5191       ExprResult result = CheckPlaceholderExpr(Fn);
5192       if (result.isInvalid()) return ExprError();
5193       Fn = result.get();
5194     }
5195 
5196     // Determine whether this is a dependent call inside a C++ template,
5197     // in which case we won't do any semantic analysis now.
5198     bool Dependent = false;
5199     if (Fn->isTypeDependent())
5200       Dependent = true;
5201     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5202       Dependent = true;
5203 
5204     if (Dependent) {
5205       if (ExecConfig) {
5206         return new (Context) CUDAKernelCallExpr(
5207             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5208             Context.DependentTy, VK_RValue, RParenLoc);
5209       } else {
5210         return new (Context) CallExpr(
5211             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5212       }
5213     }
5214 
5215     // Determine whether this is a call to an object (C++ [over.call.object]).
5216     if (Fn->getType()->isRecordType())
5217       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5218                                           RParenLoc);
5219 
5220     if (Fn->getType() == Context.UnknownAnyTy) {
5221       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5222       if (result.isInvalid()) return ExprError();
5223       Fn = result.get();
5224     }
5225 
5226     if (Fn->getType() == Context.BoundMemberTy) {
5227       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5228                                        RParenLoc);
5229     }
5230   }
5231 
5232   // Check for overloaded calls.  This can happen even in C due to extensions.
5233   if (Fn->getType() == Context.OverloadTy) {
5234     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5235 
5236     // We aren't supposed to apply this logic for if there'Scope an '&'
5237     // involved.
5238     if (!find.HasFormOfMemberPointer) {
5239       OverloadExpr *ovl = find.Expression;
5240       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5241         return BuildOverloadedCallExpr(
5242             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5243             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5244       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5245                                        RParenLoc);
5246     }
5247   }
5248 
5249   // If we're directly calling a function, get the appropriate declaration.
5250   if (Fn->getType() == Context.UnknownAnyTy) {
5251     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5252     if (result.isInvalid()) return ExprError();
5253     Fn = result.get();
5254   }
5255 
5256   Expr *NakedFn = Fn->IgnoreParens();
5257 
5258   bool CallingNDeclIndirectly = false;
5259   NamedDecl *NDecl = nullptr;
5260   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5261     if (UnOp->getOpcode() == UO_AddrOf) {
5262       CallingNDeclIndirectly = true;
5263       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5264     }
5265   }
5266 
5267   if (isa<DeclRefExpr>(NakedFn)) {
5268     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5269 
5270     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5271     if (FDecl && FDecl->getBuiltinID()) {
5272       // Rewrite the function decl for this builtin by replacing parameters
5273       // with no explicit address space with the address space of the arguments
5274       // in ArgExprs.
5275       if ((FDecl =
5276                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5277         NDecl = FDecl;
5278         Fn = DeclRefExpr::Create(
5279             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5280             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5281       }
5282     }
5283   } else if (isa<MemberExpr>(NakedFn))
5284     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5285 
5286   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5287     if (CallingNDeclIndirectly &&
5288         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5289                                            Fn->getLocStart()))
5290       return ExprError();
5291 
5292     // CheckEnableIf assumes that the we're passing in a sane number of args for
5293     // FD, but that doesn't always hold true here. This is because, in some
5294     // cases, we'll emit a diag about an ill-formed function call, but then
5295     // we'll continue on as if the function call wasn't ill-formed. So, if the
5296     // number of args looks incorrect, don't do enable_if checks; we should've
5297     // already emitted an error about the bad call.
5298     if (FD->hasAttr<EnableIfAttr>() &&
5299         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5300       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5301         Diag(Fn->getLocStart(),
5302              isa<CXXMethodDecl>(FD)
5303                  ? diag::err_ovl_no_viable_member_function_in_call
5304                  : diag::err_ovl_no_viable_function_in_call)
5305             << FD << FD->getSourceRange();
5306         Diag(FD->getLocation(),
5307              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5308             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5309       }
5310     }
5311   }
5312 
5313   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5314                                ExecConfig, IsExecConfig);
5315 }
5316 
5317 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5318 ///
5319 /// __builtin_astype( value, dst type )
5320 ///
5321 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5322                                  SourceLocation BuiltinLoc,
5323                                  SourceLocation RParenLoc) {
5324   ExprValueKind VK = VK_RValue;
5325   ExprObjectKind OK = OK_Ordinary;
5326   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5327   QualType SrcTy = E->getType();
5328   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5329     return ExprError(Diag(BuiltinLoc,
5330                           diag::err_invalid_astype_of_different_size)
5331                      << DstTy
5332                      << SrcTy
5333                      << E->getSourceRange());
5334   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5335 }
5336 
5337 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5338 /// provided arguments.
5339 ///
5340 /// __builtin_convertvector( value, dst type )
5341 ///
5342 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5343                                         SourceLocation BuiltinLoc,
5344                                         SourceLocation RParenLoc) {
5345   TypeSourceInfo *TInfo;
5346   GetTypeFromParser(ParsedDestTy, &TInfo);
5347   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5348 }
5349 
5350 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5351 /// i.e. an expression not of \p OverloadTy.  The expression should
5352 /// unary-convert to an expression of function-pointer or
5353 /// block-pointer type.
5354 ///
5355 /// \param NDecl the declaration being called, if available
5356 ExprResult
5357 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5358                             SourceLocation LParenLoc,
5359                             ArrayRef<Expr *> Args,
5360                             SourceLocation RParenLoc,
5361                             Expr *Config, bool IsExecConfig) {
5362   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5363   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5364 
5365   // Functions with 'interrupt' attribute cannot be called directly.
5366   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5367     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5368     return ExprError();
5369   }
5370 
5371   // Promote the function operand.
5372   // We special-case function promotion here because we only allow promoting
5373   // builtin functions to function pointers in the callee of a call.
5374   ExprResult Result;
5375   if (BuiltinID &&
5376       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5377     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5378                                CK_BuiltinFnToFnPtr).get();
5379   } else {
5380     Result = CallExprUnaryConversions(Fn);
5381   }
5382   if (Result.isInvalid())
5383     return ExprError();
5384   Fn = Result.get();
5385 
5386   // Make the call expr early, before semantic checks.  This guarantees cleanup
5387   // of arguments and function on error.
5388   CallExpr *TheCall;
5389   if (Config)
5390     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5391                                                cast<CallExpr>(Config), Args,
5392                                                Context.BoolTy, VK_RValue,
5393                                                RParenLoc);
5394   else
5395     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5396                                      VK_RValue, RParenLoc);
5397 
5398   if (!getLangOpts().CPlusPlus) {
5399     // C cannot always handle TypoExpr nodes in builtin calls and direct
5400     // function calls as their argument checking don't necessarily handle
5401     // dependent types properly, so make sure any TypoExprs have been
5402     // dealt with.
5403     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5404     if (!Result.isUsable()) return ExprError();
5405     TheCall = dyn_cast<CallExpr>(Result.get());
5406     if (!TheCall) return Result;
5407     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5408   }
5409 
5410   // Bail out early if calling a builtin with custom typechecking.
5411   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5412     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5413 
5414  retry:
5415   const FunctionType *FuncT;
5416   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5417     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5418     // have type pointer to function".
5419     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5420     if (!FuncT)
5421       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5422                          << Fn->getType() << Fn->getSourceRange());
5423   } else if (const BlockPointerType *BPT =
5424                Fn->getType()->getAs<BlockPointerType>()) {
5425     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5426   } else {
5427     // Handle calls to expressions of unknown-any type.
5428     if (Fn->getType() == Context.UnknownAnyTy) {
5429       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5430       if (rewrite.isInvalid()) return ExprError();
5431       Fn = rewrite.get();
5432       TheCall->setCallee(Fn);
5433       goto retry;
5434     }
5435 
5436     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5437       << Fn->getType() << Fn->getSourceRange());
5438   }
5439 
5440   if (getLangOpts().CUDA) {
5441     if (Config) {
5442       // CUDA: Kernel calls must be to global functions
5443       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5444         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5445             << FDecl->getName() << Fn->getSourceRange());
5446 
5447       // CUDA: Kernel function must have 'void' return type
5448       if (!FuncT->getReturnType()->isVoidType())
5449         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5450             << Fn->getType() << Fn->getSourceRange());
5451     } else {
5452       // CUDA: Calls to global functions must be configured
5453       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5454         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5455             << FDecl->getName() << Fn->getSourceRange());
5456     }
5457   }
5458 
5459   // Check for a valid return type
5460   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5461                           FDecl))
5462     return ExprError();
5463 
5464   // We know the result type of the call, set it.
5465   TheCall->setType(FuncT->getCallResultType(Context));
5466   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5467 
5468   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5469   if (Proto) {
5470     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5471                                 IsExecConfig))
5472       return ExprError();
5473   } else {
5474     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5475 
5476     if (FDecl) {
5477       // Check if we have too few/too many template arguments, based
5478       // on our knowledge of the function definition.
5479       const FunctionDecl *Def = nullptr;
5480       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5481         Proto = Def->getType()->getAs<FunctionProtoType>();
5482        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5483           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5484           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5485       }
5486 
5487       // If the function we're calling isn't a function prototype, but we have
5488       // a function prototype from a prior declaratiom, use that prototype.
5489       if (!FDecl->hasPrototype())
5490         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5491     }
5492 
5493     // Promote the arguments (C99 6.5.2.2p6).
5494     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5495       Expr *Arg = Args[i];
5496 
5497       if (Proto && i < Proto->getNumParams()) {
5498         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5499             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5500         ExprResult ArgE =
5501             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5502         if (ArgE.isInvalid())
5503           return true;
5504 
5505         Arg = ArgE.getAs<Expr>();
5506 
5507       } else {
5508         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5509 
5510         if (ArgE.isInvalid())
5511           return true;
5512 
5513         Arg = ArgE.getAs<Expr>();
5514       }
5515 
5516       if (RequireCompleteType(Arg->getLocStart(),
5517                               Arg->getType(),
5518                               diag::err_call_incomplete_argument, Arg))
5519         return ExprError();
5520 
5521       TheCall->setArg(i, Arg);
5522     }
5523   }
5524 
5525   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5526     if (!Method->isStatic())
5527       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5528         << Fn->getSourceRange());
5529 
5530   // Check for sentinels
5531   if (NDecl)
5532     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5533 
5534   // Do special checking on direct calls to functions.
5535   if (FDecl) {
5536     if (CheckFunctionCall(FDecl, TheCall, Proto))
5537       return ExprError();
5538 
5539     if (BuiltinID)
5540       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5541   } else if (NDecl) {
5542     if (CheckPointerCall(NDecl, TheCall, Proto))
5543       return ExprError();
5544   } else {
5545     if (CheckOtherCall(TheCall, Proto))
5546       return ExprError();
5547   }
5548 
5549   return MaybeBindToTemporary(TheCall);
5550 }
5551 
5552 ExprResult
5553 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5554                            SourceLocation RParenLoc, Expr *InitExpr) {
5555   assert(Ty && "ActOnCompoundLiteral(): missing type");
5556   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5557 
5558   TypeSourceInfo *TInfo;
5559   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5560   if (!TInfo)
5561     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5562 
5563   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5564 }
5565 
5566 ExprResult
5567 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5568                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5569   QualType literalType = TInfo->getType();
5570 
5571   if (literalType->isArrayType()) {
5572     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5573           diag::err_illegal_decl_array_incomplete_type,
5574           SourceRange(LParenLoc,
5575                       LiteralExpr->getSourceRange().getEnd())))
5576       return ExprError();
5577     if (literalType->isVariableArrayType())
5578       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5579         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5580   } else if (!literalType->isDependentType() &&
5581              RequireCompleteType(LParenLoc, literalType,
5582                diag::err_typecheck_decl_incomplete_type,
5583                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5584     return ExprError();
5585 
5586   InitializedEntity Entity
5587     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5588   InitializationKind Kind
5589     = InitializationKind::CreateCStyleCast(LParenLoc,
5590                                            SourceRange(LParenLoc, RParenLoc),
5591                                            /*InitList=*/true);
5592   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5593   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5594                                       &literalType);
5595   if (Result.isInvalid())
5596     return ExprError();
5597   LiteralExpr = Result.get();
5598 
5599   bool isFileScope = !CurContext->isFunctionOrMethod();
5600   if (isFileScope &&
5601       !LiteralExpr->isTypeDependent() &&
5602       !LiteralExpr->isValueDependent() &&
5603       !literalType->isDependentType()) { // 6.5.2.5p3
5604     if (CheckForConstantInitializer(LiteralExpr, literalType))
5605       return ExprError();
5606   }
5607 
5608   // In C, compound literals are l-values for some reason.
5609   // For GCC compatibility, in C++, file-scope array compound literals with
5610   // constant initializers are also l-values, and compound literals are
5611   // otherwise prvalues.
5612   //
5613   // (GCC also treats C++ list-initialized file-scope array prvalues with
5614   // constant initializers as l-values, but that's non-conforming, so we don't
5615   // follow it there.)
5616   //
5617   // FIXME: It would be better to handle the lvalue cases as materializing and
5618   // lifetime-extending a temporary object, but our materialized temporaries
5619   // representation only supports lifetime extension from a variable, not "out
5620   // of thin air".
5621   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5622   // is bound to the result of applying array-to-pointer decay to the compound
5623   // literal.
5624   // FIXME: GCC supports compound literals of reference type, which should
5625   // obviously have a value kind derived from the kind of reference involved.
5626   ExprValueKind VK =
5627       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5628           ? VK_RValue
5629           : VK_LValue;
5630 
5631   return MaybeBindToTemporary(
5632       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5633                                         VK, LiteralExpr, isFileScope));
5634 }
5635 
5636 ExprResult
5637 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5638                     SourceLocation RBraceLoc) {
5639   // Immediately handle non-overload placeholders.  Overloads can be
5640   // resolved contextually, but everything else here can't.
5641   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5642     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5643       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5644 
5645       // Ignore failures; dropping the entire initializer list because
5646       // of one failure would be terrible for indexing/etc.
5647       if (result.isInvalid()) continue;
5648 
5649       InitArgList[I] = result.get();
5650     }
5651   }
5652 
5653   // Semantic analysis for initializers is done by ActOnDeclarator() and
5654   // CheckInitializer() - it requires knowledge of the object being intialized.
5655 
5656   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5657                                                RBraceLoc);
5658   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5659   return E;
5660 }
5661 
5662 /// Do an explicit extend of the given block pointer if we're in ARC.
5663 void Sema::maybeExtendBlockObject(ExprResult &E) {
5664   assert(E.get()->getType()->isBlockPointerType());
5665   assert(E.get()->isRValue());
5666 
5667   // Only do this in an r-value context.
5668   if (!getLangOpts().ObjCAutoRefCount) return;
5669 
5670   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5671                                CK_ARCExtendBlockObject, E.get(),
5672                                /*base path*/ nullptr, VK_RValue);
5673   Cleanup.setExprNeedsCleanups(true);
5674 }
5675 
5676 /// Prepare a conversion of the given expression to an ObjC object
5677 /// pointer type.
5678 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5679   QualType type = E.get()->getType();
5680   if (type->isObjCObjectPointerType()) {
5681     return CK_BitCast;
5682   } else if (type->isBlockPointerType()) {
5683     maybeExtendBlockObject(E);
5684     return CK_BlockPointerToObjCPointerCast;
5685   } else {
5686     assert(type->isPointerType());
5687     return CK_CPointerToObjCPointerCast;
5688   }
5689 }
5690 
5691 /// Prepares for a scalar cast, performing all the necessary stages
5692 /// except the final cast and returning the kind required.
5693 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5694   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5695   // Also, callers should have filtered out the invalid cases with
5696   // pointers.  Everything else should be possible.
5697 
5698   QualType SrcTy = Src.get()->getType();
5699   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5700     return CK_NoOp;
5701 
5702   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5703   case Type::STK_MemberPointer:
5704     llvm_unreachable("member pointer type in C");
5705 
5706   case Type::STK_CPointer:
5707   case Type::STK_BlockPointer:
5708   case Type::STK_ObjCObjectPointer:
5709     switch (DestTy->getScalarTypeKind()) {
5710     case Type::STK_CPointer: {
5711       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5712       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5713       if (SrcAS != DestAS)
5714         return CK_AddressSpaceConversion;
5715       return CK_BitCast;
5716     }
5717     case Type::STK_BlockPointer:
5718       return (SrcKind == Type::STK_BlockPointer
5719                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5720     case Type::STK_ObjCObjectPointer:
5721       if (SrcKind == Type::STK_ObjCObjectPointer)
5722         return CK_BitCast;
5723       if (SrcKind == Type::STK_CPointer)
5724         return CK_CPointerToObjCPointerCast;
5725       maybeExtendBlockObject(Src);
5726       return CK_BlockPointerToObjCPointerCast;
5727     case Type::STK_Bool:
5728       return CK_PointerToBoolean;
5729     case Type::STK_Integral:
5730       return CK_PointerToIntegral;
5731     case Type::STK_Floating:
5732     case Type::STK_FloatingComplex:
5733     case Type::STK_IntegralComplex:
5734     case Type::STK_MemberPointer:
5735       llvm_unreachable("illegal cast from pointer");
5736     }
5737     llvm_unreachable("Should have returned before this");
5738 
5739   case Type::STK_Bool: // casting from bool is like casting from an integer
5740   case Type::STK_Integral:
5741     switch (DestTy->getScalarTypeKind()) {
5742     case Type::STK_CPointer:
5743     case Type::STK_ObjCObjectPointer:
5744     case Type::STK_BlockPointer:
5745       if (Src.get()->isNullPointerConstant(Context,
5746                                            Expr::NPC_ValueDependentIsNull))
5747         return CK_NullToPointer;
5748       return CK_IntegralToPointer;
5749     case Type::STK_Bool:
5750       return CK_IntegralToBoolean;
5751     case Type::STK_Integral:
5752       return CK_IntegralCast;
5753     case Type::STK_Floating:
5754       return CK_IntegralToFloating;
5755     case Type::STK_IntegralComplex:
5756       Src = ImpCastExprToType(Src.get(),
5757                       DestTy->castAs<ComplexType>()->getElementType(),
5758                       CK_IntegralCast);
5759       return CK_IntegralRealToComplex;
5760     case Type::STK_FloatingComplex:
5761       Src = ImpCastExprToType(Src.get(),
5762                       DestTy->castAs<ComplexType>()->getElementType(),
5763                       CK_IntegralToFloating);
5764       return CK_FloatingRealToComplex;
5765     case Type::STK_MemberPointer:
5766       llvm_unreachable("member pointer type in C");
5767     }
5768     llvm_unreachable("Should have returned before this");
5769 
5770   case Type::STK_Floating:
5771     switch (DestTy->getScalarTypeKind()) {
5772     case Type::STK_Floating:
5773       return CK_FloatingCast;
5774     case Type::STK_Bool:
5775       return CK_FloatingToBoolean;
5776     case Type::STK_Integral:
5777       return CK_FloatingToIntegral;
5778     case Type::STK_FloatingComplex:
5779       Src = ImpCastExprToType(Src.get(),
5780                               DestTy->castAs<ComplexType>()->getElementType(),
5781                               CK_FloatingCast);
5782       return CK_FloatingRealToComplex;
5783     case Type::STK_IntegralComplex:
5784       Src = ImpCastExprToType(Src.get(),
5785                               DestTy->castAs<ComplexType>()->getElementType(),
5786                               CK_FloatingToIntegral);
5787       return CK_IntegralRealToComplex;
5788     case Type::STK_CPointer:
5789     case Type::STK_ObjCObjectPointer:
5790     case Type::STK_BlockPointer:
5791       llvm_unreachable("valid float->pointer cast?");
5792     case Type::STK_MemberPointer:
5793       llvm_unreachable("member pointer type in C");
5794     }
5795     llvm_unreachable("Should have returned before this");
5796 
5797   case Type::STK_FloatingComplex:
5798     switch (DestTy->getScalarTypeKind()) {
5799     case Type::STK_FloatingComplex:
5800       return CK_FloatingComplexCast;
5801     case Type::STK_IntegralComplex:
5802       return CK_FloatingComplexToIntegralComplex;
5803     case Type::STK_Floating: {
5804       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5805       if (Context.hasSameType(ET, DestTy))
5806         return CK_FloatingComplexToReal;
5807       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5808       return CK_FloatingCast;
5809     }
5810     case Type::STK_Bool:
5811       return CK_FloatingComplexToBoolean;
5812     case Type::STK_Integral:
5813       Src = ImpCastExprToType(Src.get(),
5814                               SrcTy->castAs<ComplexType>()->getElementType(),
5815                               CK_FloatingComplexToReal);
5816       return CK_FloatingToIntegral;
5817     case Type::STK_CPointer:
5818     case Type::STK_ObjCObjectPointer:
5819     case Type::STK_BlockPointer:
5820       llvm_unreachable("valid complex float->pointer cast?");
5821     case Type::STK_MemberPointer:
5822       llvm_unreachable("member pointer type in C");
5823     }
5824     llvm_unreachable("Should have returned before this");
5825 
5826   case Type::STK_IntegralComplex:
5827     switch (DestTy->getScalarTypeKind()) {
5828     case Type::STK_FloatingComplex:
5829       return CK_IntegralComplexToFloatingComplex;
5830     case Type::STK_IntegralComplex:
5831       return CK_IntegralComplexCast;
5832     case Type::STK_Integral: {
5833       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5834       if (Context.hasSameType(ET, DestTy))
5835         return CK_IntegralComplexToReal;
5836       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5837       return CK_IntegralCast;
5838     }
5839     case Type::STK_Bool:
5840       return CK_IntegralComplexToBoolean;
5841     case Type::STK_Floating:
5842       Src = ImpCastExprToType(Src.get(),
5843                               SrcTy->castAs<ComplexType>()->getElementType(),
5844                               CK_IntegralComplexToReal);
5845       return CK_IntegralToFloating;
5846     case Type::STK_CPointer:
5847     case Type::STK_ObjCObjectPointer:
5848     case Type::STK_BlockPointer:
5849       llvm_unreachable("valid complex int->pointer cast?");
5850     case Type::STK_MemberPointer:
5851       llvm_unreachable("member pointer type in C");
5852     }
5853     llvm_unreachable("Should have returned before this");
5854   }
5855 
5856   llvm_unreachable("Unhandled scalar cast");
5857 }
5858 
5859 static bool breakDownVectorType(QualType type, uint64_t &len,
5860                                 QualType &eltType) {
5861   // Vectors are simple.
5862   if (const VectorType *vecType = type->getAs<VectorType>()) {
5863     len = vecType->getNumElements();
5864     eltType = vecType->getElementType();
5865     assert(eltType->isScalarType());
5866     return true;
5867   }
5868 
5869   // We allow lax conversion to and from non-vector types, but only if
5870   // they're real types (i.e. non-complex, non-pointer scalar types).
5871   if (!type->isRealType()) return false;
5872 
5873   len = 1;
5874   eltType = type;
5875   return true;
5876 }
5877 
5878 /// Are the two types lax-compatible vector types?  That is, given
5879 /// that one of them is a vector, do they have equal storage sizes,
5880 /// where the storage size is the number of elements times the element
5881 /// size?
5882 ///
5883 /// This will also return false if either of the types is neither a
5884 /// vector nor a real type.
5885 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5886   assert(destTy->isVectorType() || srcTy->isVectorType());
5887 
5888   // Disallow lax conversions between scalars and ExtVectors (these
5889   // conversions are allowed for other vector types because common headers
5890   // depend on them).  Most scalar OP ExtVector cases are handled by the
5891   // splat path anyway, which does what we want (convert, not bitcast).
5892   // What this rules out for ExtVectors is crazy things like char4*float.
5893   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5894   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5895 
5896   uint64_t srcLen, destLen;
5897   QualType srcEltTy, destEltTy;
5898   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5899   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5900 
5901   // ASTContext::getTypeSize will return the size rounded up to a
5902   // power of 2, so instead of using that, we need to use the raw
5903   // element size multiplied by the element count.
5904   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5905   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5906 
5907   return (srcLen * srcEltSize == destLen * destEltSize);
5908 }
5909 
5910 /// Is this a legal conversion between two types, one of which is
5911 /// known to be a vector type?
5912 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5913   assert(destTy->isVectorType() || srcTy->isVectorType());
5914 
5915   if (!Context.getLangOpts().LaxVectorConversions)
5916     return false;
5917   return areLaxCompatibleVectorTypes(srcTy, destTy);
5918 }
5919 
5920 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5921                            CastKind &Kind) {
5922   assert(VectorTy->isVectorType() && "Not a vector type!");
5923 
5924   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5925     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5926       return Diag(R.getBegin(),
5927                   Ty->isVectorType() ?
5928                   diag::err_invalid_conversion_between_vectors :
5929                   diag::err_invalid_conversion_between_vector_and_integer)
5930         << VectorTy << Ty << R;
5931   } else
5932     return Diag(R.getBegin(),
5933                 diag::err_invalid_conversion_between_vector_and_scalar)
5934       << VectorTy << Ty << R;
5935 
5936   Kind = CK_BitCast;
5937   return false;
5938 }
5939 
5940 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5941   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5942 
5943   if (DestElemTy == SplattedExpr->getType())
5944     return SplattedExpr;
5945 
5946   assert(DestElemTy->isFloatingType() ||
5947          DestElemTy->isIntegralOrEnumerationType());
5948 
5949   CastKind CK;
5950   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5951     // OpenCL requires that we convert `true` boolean expressions to -1, but
5952     // only when splatting vectors.
5953     if (DestElemTy->isFloatingType()) {
5954       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5955       // in two steps: boolean to signed integral, then to floating.
5956       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5957                                                  CK_BooleanToSignedIntegral);
5958       SplattedExpr = CastExprRes.get();
5959       CK = CK_IntegralToFloating;
5960     } else {
5961       CK = CK_BooleanToSignedIntegral;
5962     }
5963   } else {
5964     ExprResult CastExprRes = SplattedExpr;
5965     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5966     if (CastExprRes.isInvalid())
5967       return ExprError();
5968     SplattedExpr = CastExprRes.get();
5969   }
5970   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5971 }
5972 
5973 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5974                                     Expr *CastExpr, CastKind &Kind) {
5975   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5976 
5977   QualType SrcTy = CastExpr->getType();
5978 
5979   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5980   // an ExtVectorType.
5981   // In OpenCL, casts between vectors of different types are not allowed.
5982   // (See OpenCL 6.2).
5983   if (SrcTy->isVectorType()) {
5984     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5985         || (getLangOpts().OpenCL &&
5986             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5987       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5988         << DestTy << SrcTy << R;
5989       return ExprError();
5990     }
5991     Kind = CK_BitCast;
5992     return CastExpr;
5993   }
5994 
5995   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5996   // conversion will take place first from scalar to elt type, and then
5997   // splat from elt type to vector.
5998   if (SrcTy->isPointerType())
5999     return Diag(R.getBegin(),
6000                 diag::err_invalid_conversion_between_vector_and_scalar)
6001       << DestTy << SrcTy << R;
6002 
6003   Kind = CK_VectorSplat;
6004   return prepareVectorSplat(DestTy, CastExpr);
6005 }
6006 
6007 ExprResult
6008 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6009                     Declarator &D, ParsedType &Ty,
6010                     SourceLocation RParenLoc, Expr *CastExpr) {
6011   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6012          "ActOnCastExpr(): missing type or expr");
6013 
6014   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6015   if (D.isInvalidType())
6016     return ExprError();
6017 
6018   if (getLangOpts().CPlusPlus) {
6019     // Check that there are no default arguments (C++ only).
6020     CheckExtraCXXDefaultArguments(D);
6021   } else {
6022     // Make sure any TypoExprs have been dealt with.
6023     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6024     if (!Res.isUsable())
6025       return ExprError();
6026     CastExpr = Res.get();
6027   }
6028 
6029   checkUnusedDeclAttributes(D);
6030 
6031   QualType castType = castTInfo->getType();
6032   Ty = CreateParsedType(castType, castTInfo);
6033 
6034   bool isVectorLiteral = false;
6035 
6036   // Check for an altivec or OpenCL literal,
6037   // i.e. all the elements are integer constants.
6038   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6039   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6040   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6041        && castType->isVectorType() && (PE || PLE)) {
6042     if (PLE && PLE->getNumExprs() == 0) {
6043       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6044       return ExprError();
6045     }
6046     if (PE || PLE->getNumExprs() == 1) {
6047       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6048       if (!E->getType()->isVectorType())
6049         isVectorLiteral = true;
6050     }
6051     else
6052       isVectorLiteral = true;
6053   }
6054 
6055   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6056   // then handle it as such.
6057   if (isVectorLiteral)
6058     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6059 
6060   // If the Expr being casted is a ParenListExpr, handle it specially.
6061   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6062   // sequence of BinOp comma operators.
6063   if (isa<ParenListExpr>(CastExpr)) {
6064     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6065     if (Result.isInvalid()) return ExprError();
6066     CastExpr = Result.get();
6067   }
6068 
6069   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6070       !getSourceManager().isInSystemMacro(LParenLoc))
6071     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6072 
6073   CheckTollFreeBridgeCast(castType, CastExpr);
6074 
6075   CheckObjCBridgeRelatedCast(castType, CastExpr);
6076 
6077   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6078 
6079   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6080 }
6081 
6082 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6083                                     SourceLocation RParenLoc, Expr *E,
6084                                     TypeSourceInfo *TInfo) {
6085   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6086          "Expected paren or paren list expression");
6087 
6088   Expr **exprs;
6089   unsigned numExprs;
6090   Expr *subExpr;
6091   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6092   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6093     LiteralLParenLoc = PE->getLParenLoc();
6094     LiteralRParenLoc = PE->getRParenLoc();
6095     exprs = PE->getExprs();
6096     numExprs = PE->getNumExprs();
6097   } else { // isa<ParenExpr> by assertion at function entrance
6098     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6099     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6100     subExpr = cast<ParenExpr>(E)->getSubExpr();
6101     exprs = &subExpr;
6102     numExprs = 1;
6103   }
6104 
6105   QualType Ty = TInfo->getType();
6106   assert(Ty->isVectorType() && "Expected vector type");
6107 
6108   SmallVector<Expr *, 8> initExprs;
6109   const VectorType *VTy = Ty->getAs<VectorType>();
6110   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6111 
6112   // '(...)' form of vector initialization in AltiVec: the number of
6113   // initializers must be one or must match the size of the vector.
6114   // If a single value is specified in the initializer then it will be
6115   // replicated to all the components of the vector
6116   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6117     // The number of initializers must be one or must match the size of the
6118     // vector. If a single value is specified in the initializer then it will
6119     // be replicated to all the components of the vector
6120     if (numExprs == 1) {
6121       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6122       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6123       if (Literal.isInvalid())
6124         return ExprError();
6125       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6126                                   PrepareScalarCast(Literal, ElemTy));
6127       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6128     }
6129     else if (numExprs < numElems) {
6130       Diag(E->getExprLoc(),
6131            diag::err_incorrect_number_of_vector_initializers);
6132       return ExprError();
6133     }
6134     else
6135       initExprs.append(exprs, exprs + numExprs);
6136   }
6137   else {
6138     // For OpenCL, when the number of initializers is a single value,
6139     // it will be replicated to all components of the vector.
6140     if (getLangOpts().OpenCL &&
6141         VTy->getVectorKind() == VectorType::GenericVector &&
6142         numExprs == 1) {
6143         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6144         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6145         if (Literal.isInvalid())
6146           return ExprError();
6147         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6148                                     PrepareScalarCast(Literal, ElemTy));
6149         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6150     }
6151 
6152     initExprs.append(exprs, exprs + numExprs);
6153   }
6154   // FIXME: This means that pretty-printing the final AST will produce curly
6155   // braces instead of the original commas.
6156   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6157                                                    initExprs, LiteralRParenLoc);
6158   initE->setType(Ty);
6159   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6160 }
6161 
6162 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6163 /// the ParenListExpr into a sequence of comma binary operators.
6164 ExprResult
6165 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6166   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6167   if (!E)
6168     return OrigExpr;
6169 
6170   ExprResult Result(E->getExpr(0));
6171 
6172   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6173     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6174                         E->getExpr(i));
6175 
6176   if (Result.isInvalid()) return ExprError();
6177 
6178   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6179 }
6180 
6181 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6182                                     SourceLocation R,
6183                                     MultiExprArg Val) {
6184   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6185   return expr;
6186 }
6187 
6188 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6189 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6190 /// emitted.
6191 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6192                                       SourceLocation QuestionLoc) {
6193   Expr *NullExpr = LHSExpr;
6194   Expr *NonPointerExpr = RHSExpr;
6195   Expr::NullPointerConstantKind NullKind =
6196       NullExpr->isNullPointerConstant(Context,
6197                                       Expr::NPC_ValueDependentIsNotNull);
6198 
6199   if (NullKind == Expr::NPCK_NotNull) {
6200     NullExpr = RHSExpr;
6201     NonPointerExpr = LHSExpr;
6202     NullKind =
6203         NullExpr->isNullPointerConstant(Context,
6204                                         Expr::NPC_ValueDependentIsNotNull);
6205   }
6206 
6207   if (NullKind == Expr::NPCK_NotNull)
6208     return false;
6209 
6210   if (NullKind == Expr::NPCK_ZeroExpression)
6211     return false;
6212 
6213   if (NullKind == Expr::NPCK_ZeroLiteral) {
6214     // In this case, check to make sure that we got here from a "NULL"
6215     // string in the source code.
6216     NullExpr = NullExpr->IgnoreParenImpCasts();
6217     SourceLocation loc = NullExpr->getExprLoc();
6218     if (!findMacroSpelling(loc, "NULL"))
6219       return false;
6220   }
6221 
6222   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6223   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6224       << NonPointerExpr->getType() << DiagType
6225       << NonPointerExpr->getSourceRange();
6226   return true;
6227 }
6228 
6229 /// \brief Return false if the condition expression is valid, true otherwise.
6230 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6231   QualType CondTy = Cond->getType();
6232 
6233   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6234   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6235     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6236       << CondTy << Cond->getSourceRange();
6237     return true;
6238   }
6239 
6240   // C99 6.5.15p2
6241   if (CondTy->isScalarType()) return false;
6242 
6243   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6244     << CondTy << Cond->getSourceRange();
6245   return true;
6246 }
6247 
6248 /// \brief Handle when one or both operands are void type.
6249 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6250                                          ExprResult &RHS) {
6251     Expr *LHSExpr = LHS.get();
6252     Expr *RHSExpr = RHS.get();
6253 
6254     if (!LHSExpr->getType()->isVoidType())
6255       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6256         << RHSExpr->getSourceRange();
6257     if (!RHSExpr->getType()->isVoidType())
6258       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6259         << LHSExpr->getSourceRange();
6260     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6261     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6262     return S.Context.VoidTy;
6263 }
6264 
6265 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6266 /// true otherwise.
6267 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6268                                         QualType PointerTy) {
6269   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6270       !NullExpr.get()->isNullPointerConstant(S.Context,
6271                                             Expr::NPC_ValueDependentIsNull))
6272     return true;
6273 
6274   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6275   return false;
6276 }
6277 
6278 /// \brief Checks compatibility between two pointers and return the resulting
6279 /// type.
6280 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6281                                                      ExprResult &RHS,
6282                                                      SourceLocation Loc) {
6283   QualType LHSTy = LHS.get()->getType();
6284   QualType RHSTy = RHS.get()->getType();
6285 
6286   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6287     // Two identical pointers types are always compatible.
6288     return LHSTy;
6289   }
6290 
6291   QualType lhptee, rhptee;
6292 
6293   // Get the pointee types.
6294   bool IsBlockPointer = false;
6295   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6296     lhptee = LHSBTy->getPointeeType();
6297     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6298     IsBlockPointer = true;
6299   } else {
6300     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6301     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6302   }
6303 
6304   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6305   // differently qualified versions of compatible types, the result type is
6306   // a pointer to an appropriately qualified version of the composite
6307   // type.
6308 
6309   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6310   // clause doesn't make sense for our extensions. E.g. address space 2 should
6311   // be incompatible with address space 3: they may live on different devices or
6312   // anything.
6313   Qualifiers lhQual = lhptee.getQualifiers();
6314   Qualifiers rhQual = rhptee.getQualifiers();
6315 
6316   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6317   lhQual.removeCVRQualifiers();
6318   rhQual.removeCVRQualifiers();
6319 
6320   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6321   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6322 
6323   // For OpenCL:
6324   // 1. If LHS and RHS types match exactly and:
6325   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6326   //  (b) AS overlap => generate addrspacecast
6327   //  (c) AS don't overlap => give an error
6328   // 2. if LHS and RHS types don't match:
6329   //  (a) AS match => use standard C rules, generate bitcast
6330   //  (b) AS overlap => generate addrspacecast instead of bitcast
6331   //  (c) AS don't overlap => give an error
6332 
6333   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6334   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6335 
6336   // OpenCL cases 1c, 2a, 2b, and 2c.
6337   if (CompositeTy.isNull()) {
6338     // In this situation, we assume void* type. No especially good
6339     // reason, but this is what gcc does, and we do have to pick
6340     // to get a consistent AST.
6341     QualType incompatTy;
6342     if (S.getLangOpts().OpenCL) {
6343       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6344       // spaces is disallowed.
6345       unsigned ResultAddrSpace;
6346       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6347         // Cases 2a and 2b.
6348         ResultAddrSpace = lhQual.getAddressSpace();
6349       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6350         // Cases 2a and 2b.
6351         ResultAddrSpace = rhQual.getAddressSpace();
6352       } else {
6353         // Cases 1c and 2c.
6354         S.Diag(Loc,
6355                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6356             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6357             << RHS.get()->getSourceRange();
6358         return QualType();
6359       }
6360 
6361       // Continue handling cases 2a and 2b.
6362       incompatTy = S.Context.getPointerType(
6363           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6364       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6365                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6366                                     ? CK_AddressSpaceConversion /* 2b */
6367                                     : CK_BitCast /* 2a */);
6368       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6369                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6370                                     ? CK_AddressSpaceConversion /* 2b */
6371                                     : CK_BitCast /* 2a */);
6372     } else {
6373       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6374           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6375           << RHS.get()->getSourceRange();
6376       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6377       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6378       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6379     }
6380     return incompatTy;
6381   }
6382 
6383   // The pointer types are compatible.
6384   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6385   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6386   if (IsBlockPointer)
6387     ResultTy = S.Context.getBlockPointerType(ResultTy);
6388   else {
6389     // Cases 1a and 1b for OpenCL.
6390     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6391     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6392                       ? CK_BitCast /* 1a */
6393                       : CK_AddressSpaceConversion /* 1b */;
6394     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6395                       ? CK_BitCast /* 1a */
6396                       : CK_AddressSpaceConversion /* 1b */;
6397     ResultTy = S.Context.getPointerType(ResultTy);
6398   }
6399 
6400   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6401   // if the target type does not change.
6402   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6403   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6404   return ResultTy;
6405 }
6406 
6407 /// \brief Return the resulting type when the operands are both block pointers.
6408 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6409                                                           ExprResult &LHS,
6410                                                           ExprResult &RHS,
6411                                                           SourceLocation Loc) {
6412   QualType LHSTy = LHS.get()->getType();
6413   QualType RHSTy = RHS.get()->getType();
6414 
6415   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6416     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6417       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6418       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6419       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6420       return destType;
6421     }
6422     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6423       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6424       << RHS.get()->getSourceRange();
6425     return QualType();
6426   }
6427 
6428   // We have 2 block pointer types.
6429   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6430 }
6431 
6432 /// \brief Return the resulting type when the operands are both pointers.
6433 static QualType
6434 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6435                                             ExprResult &RHS,
6436                                             SourceLocation Loc) {
6437   // get the pointer types
6438   QualType LHSTy = LHS.get()->getType();
6439   QualType RHSTy = RHS.get()->getType();
6440 
6441   // get the "pointed to" types
6442   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6443   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6444 
6445   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6446   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6447     // Figure out necessary qualifiers (C99 6.5.15p6)
6448     QualType destPointee
6449       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6450     QualType destType = S.Context.getPointerType(destPointee);
6451     // Add qualifiers if necessary.
6452     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6453     // Promote to void*.
6454     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6455     return destType;
6456   }
6457   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6458     QualType destPointee
6459       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6460     QualType destType = S.Context.getPointerType(destPointee);
6461     // Add qualifiers if necessary.
6462     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6463     // Promote to void*.
6464     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6465     return destType;
6466   }
6467 
6468   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6469 }
6470 
6471 /// \brief Return false if the first expression is not an integer and the second
6472 /// expression is not a pointer, true otherwise.
6473 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6474                                         Expr* PointerExpr, SourceLocation Loc,
6475                                         bool IsIntFirstExpr) {
6476   if (!PointerExpr->getType()->isPointerType() ||
6477       !Int.get()->getType()->isIntegerType())
6478     return false;
6479 
6480   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6481   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6482 
6483   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6484     << Expr1->getType() << Expr2->getType()
6485     << Expr1->getSourceRange() << Expr2->getSourceRange();
6486   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6487                             CK_IntegralToPointer);
6488   return true;
6489 }
6490 
6491 /// \brief Simple conversion between integer and floating point types.
6492 ///
6493 /// Used when handling the OpenCL conditional operator where the
6494 /// condition is a vector while the other operands are scalar.
6495 ///
6496 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6497 /// types are either integer or floating type. Between the two
6498 /// operands, the type with the higher rank is defined as the "result
6499 /// type". The other operand needs to be promoted to the same type. No
6500 /// other type promotion is allowed. We cannot use
6501 /// UsualArithmeticConversions() for this purpose, since it always
6502 /// promotes promotable types.
6503 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6504                                             ExprResult &RHS,
6505                                             SourceLocation QuestionLoc) {
6506   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6507   if (LHS.isInvalid())
6508     return QualType();
6509   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6510   if (RHS.isInvalid())
6511     return QualType();
6512 
6513   // For conversion purposes, we ignore any qualifiers.
6514   // For example, "const float" and "float" are equivalent.
6515   QualType LHSType =
6516     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6517   QualType RHSType =
6518     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6519 
6520   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6521     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6522       << LHSType << LHS.get()->getSourceRange();
6523     return QualType();
6524   }
6525 
6526   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6527     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6528       << RHSType << RHS.get()->getSourceRange();
6529     return QualType();
6530   }
6531 
6532   // If both types are identical, no conversion is needed.
6533   if (LHSType == RHSType)
6534     return LHSType;
6535 
6536   // Now handle "real" floating types (i.e. float, double, long double).
6537   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6538     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6539                                  /*IsCompAssign = */ false);
6540 
6541   // Finally, we have two differing integer types.
6542   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6543   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6544 }
6545 
6546 /// \brief Convert scalar operands to a vector that matches the
6547 ///        condition in length.
6548 ///
6549 /// Used when handling the OpenCL conditional operator where the
6550 /// condition is a vector while the other operands are scalar.
6551 ///
6552 /// We first compute the "result type" for the scalar operands
6553 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6554 /// into a vector of that type where the length matches the condition
6555 /// vector type. s6.11.6 requires that the element types of the result
6556 /// and the condition must have the same number of bits.
6557 static QualType
6558 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6559                               QualType CondTy, SourceLocation QuestionLoc) {
6560   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6561   if (ResTy.isNull()) return QualType();
6562 
6563   const VectorType *CV = CondTy->getAs<VectorType>();
6564   assert(CV);
6565 
6566   // Determine the vector result type
6567   unsigned NumElements = CV->getNumElements();
6568   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6569 
6570   // Ensure that all types have the same number of bits
6571   if (S.Context.getTypeSize(CV->getElementType())
6572       != S.Context.getTypeSize(ResTy)) {
6573     // Since VectorTy is created internally, it does not pretty print
6574     // with an OpenCL name. Instead, we just print a description.
6575     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6576     SmallString<64> Str;
6577     llvm::raw_svector_ostream OS(Str);
6578     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6579     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6580       << CondTy << OS.str();
6581     return QualType();
6582   }
6583 
6584   // Convert operands to the vector result type
6585   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6586   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6587 
6588   return VectorTy;
6589 }
6590 
6591 /// \brief Return false if this is a valid OpenCL condition vector
6592 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6593                                        SourceLocation QuestionLoc) {
6594   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6595   // integral type.
6596   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6597   assert(CondTy);
6598   QualType EleTy = CondTy->getElementType();
6599   if (EleTy->isIntegerType()) return false;
6600 
6601   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6602     << Cond->getType() << Cond->getSourceRange();
6603   return true;
6604 }
6605 
6606 /// \brief Return false if the vector condition type and the vector
6607 ///        result type are compatible.
6608 ///
6609 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6610 /// number of elements, and their element types have the same number
6611 /// of bits.
6612 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6613                               SourceLocation QuestionLoc) {
6614   const VectorType *CV = CondTy->getAs<VectorType>();
6615   const VectorType *RV = VecResTy->getAs<VectorType>();
6616   assert(CV && RV);
6617 
6618   if (CV->getNumElements() != RV->getNumElements()) {
6619     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6620       << CondTy << VecResTy;
6621     return true;
6622   }
6623 
6624   QualType CVE = CV->getElementType();
6625   QualType RVE = RV->getElementType();
6626 
6627   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6628     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6629       << CondTy << VecResTy;
6630     return true;
6631   }
6632 
6633   return false;
6634 }
6635 
6636 /// \brief Return the resulting type for the conditional operator in
6637 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6638 ///        s6.3.i) when the condition is a vector type.
6639 static QualType
6640 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6641                              ExprResult &LHS, ExprResult &RHS,
6642                              SourceLocation QuestionLoc) {
6643   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6644   if (Cond.isInvalid())
6645     return QualType();
6646   QualType CondTy = Cond.get()->getType();
6647 
6648   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6649     return QualType();
6650 
6651   // If either operand is a vector then find the vector type of the
6652   // result as specified in OpenCL v1.1 s6.3.i.
6653   if (LHS.get()->getType()->isVectorType() ||
6654       RHS.get()->getType()->isVectorType()) {
6655     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6656                                               /*isCompAssign*/false,
6657                                               /*AllowBothBool*/true,
6658                                               /*AllowBoolConversions*/false);
6659     if (VecResTy.isNull()) return QualType();
6660     // The result type must match the condition type as specified in
6661     // OpenCL v1.1 s6.11.6.
6662     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6663       return QualType();
6664     return VecResTy;
6665   }
6666 
6667   // Both operands are scalar.
6668   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6669 }
6670 
6671 /// \brief Return true if the Expr is block type
6672 static bool checkBlockType(Sema &S, const Expr *E) {
6673   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6674     QualType Ty = CE->getCallee()->getType();
6675     if (Ty->isBlockPointerType()) {
6676       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6677       return true;
6678     }
6679   }
6680   return false;
6681 }
6682 
6683 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6684 /// In that case, LHS = cond.
6685 /// C99 6.5.15
6686 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6687                                         ExprResult &RHS, ExprValueKind &VK,
6688                                         ExprObjectKind &OK,
6689                                         SourceLocation QuestionLoc) {
6690 
6691   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6692   if (!LHSResult.isUsable()) return QualType();
6693   LHS = LHSResult;
6694 
6695   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6696   if (!RHSResult.isUsable()) return QualType();
6697   RHS = RHSResult;
6698 
6699   // C++ is sufficiently different to merit its own checker.
6700   if (getLangOpts().CPlusPlus)
6701     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6702 
6703   VK = VK_RValue;
6704   OK = OK_Ordinary;
6705 
6706   // The OpenCL operator with a vector condition is sufficiently
6707   // different to merit its own checker.
6708   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6709     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6710 
6711   // First, check the condition.
6712   Cond = UsualUnaryConversions(Cond.get());
6713   if (Cond.isInvalid())
6714     return QualType();
6715   if (checkCondition(*this, Cond.get(), QuestionLoc))
6716     return QualType();
6717 
6718   // Now check the two expressions.
6719   if (LHS.get()->getType()->isVectorType() ||
6720       RHS.get()->getType()->isVectorType())
6721     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6722                                /*AllowBothBool*/true,
6723                                /*AllowBoolConversions*/false);
6724 
6725   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6726   if (LHS.isInvalid() || RHS.isInvalid())
6727     return QualType();
6728 
6729   QualType LHSTy = LHS.get()->getType();
6730   QualType RHSTy = RHS.get()->getType();
6731 
6732   // Diagnose attempts to convert between __float128 and long double where
6733   // such conversions currently can't be handled.
6734   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6735     Diag(QuestionLoc,
6736          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6737       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6738     return QualType();
6739   }
6740 
6741   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6742   // selection operator (?:).
6743   if (getLangOpts().OpenCL &&
6744       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6745     return QualType();
6746   }
6747 
6748   // If both operands have arithmetic type, do the usual arithmetic conversions
6749   // to find a common type: C99 6.5.15p3,5.
6750   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6751     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6752     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6753 
6754     return ResTy;
6755   }
6756 
6757   // If both operands are the same structure or union type, the result is that
6758   // type.
6759   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6760     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6761       if (LHSRT->getDecl() == RHSRT->getDecl())
6762         // "If both the operands have structure or union type, the result has
6763         // that type."  This implies that CV qualifiers are dropped.
6764         return LHSTy.getUnqualifiedType();
6765     // FIXME: Type of conditional expression must be complete in C mode.
6766   }
6767 
6768   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6769   // The following || allows only one side to be void (a GCC-ism).
6770   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6771     return checkConditionalVoidType(*this, LHS, RHS);
6772   }
6773 
6774   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6775   // the type of the other operand."
6776   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6777   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6778 
6779   // All objective-c pointer type analysis is done here.
6780   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6781                                                         QuestionLoc);
6782   if (LHS.isInvalid() || RHS.isInvalid())
6783     return QualType();
6784   if (!compositeType.isNull())
6785     return compositeType;
6786 
6787 
6788   // Handle block pointer types.
6789   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6790     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6791                                                      QuestionLoc);
6792 
6793   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6794   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6795     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6796                                                        QuestionLoc);
6797 
6798   // GCC compatibility: soften pointer/integer mismatch.  Note that
6799   // null pointers have been filtered out by this point.
6800   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6801       /*isIntFirstExpr=*/true))
6802     return RHSTy;
6803   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6804       /*isIntFirstExpr=*/false))
6805     return LHSTy;
6806 
6807   // Emit a better diagnostic if one of the expressions is a null pointer
6808   // constant and the other is not a pointer type. In this case, the user most
6809   // likely forgot to take the address of the other expression.
6810   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6811     return QualType();
6812 
6813   // Otherwise, the operands are not compatible.
6814   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6815     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6816     << RHS.get()->getSourceRange();
6817   return QualType();
6818 }
6819 
6820 /// FindCompositeObjCPointerType - Helper method to find composite type of
6821 /// two objective-c pointer types of the two input expressions.
6822 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6823                                             SourceLocation QuestionLoc) {
6824   QualType LHSTy = LHS.get()->getType();
6825   QualType RHSTy = RHS.get()->getType();
6826 
6827   // Handle things like Class and struct objc_class*.  Here we case the result
6828   // to the pseudo-builtin, because that will be implicitly cast back to the
6829   // redefinition type if an attempt is made to access its fields.
6830   if (LHSTy->isObjCClassType() &&
6831       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6832     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6833     return LHSTy;
6834   }
6835   if (RHSTy->isObjCClassType() &&
6836       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6837     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6838     return RHSTy;
6839   }
6840   // And the same for struct objc_object* / id
6841   if (LHSTy->isObjCIdType() &&
6842       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6843     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6844     return LHSTy;
6845   }
6846   if (RHSTy->isObjCIdType() &&
6847       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6848     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6849     return RHSTy;
6850   }
6851   // And the same for struct objc_selector* / SEL
6852   if (Context.isObjCSelType(LHSTy) &&
6853       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6854     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6855     return LHSTy;
6856   }
6857   if (Context.isObjCSelType(RHSTy) &&
6858       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6859     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6860     return RHSTy;
6861   }
6862   // Check constraints for Objective-C object pointers types.
6863   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6864 
6865     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6866       // Two identical object pointer types are always compatible.
6867       return LHSTy;
6868     }
6869     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6870     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6871     QualType compositeType = LHSTy;
6872 
6873     // If both operands are interfaces and either operand can be
6874     // assigned to the other, use that type as the composite
6875     // type. This allows
6876     //   xxx ? (A*) a : (B*) b
6877     // where B is a subclass of A.
6878     //
6879     // Additionally, as for assignment, if either type is 'id'
6880     // allow silent coercion. Finally, if the types are
6881     // incompatible then make sure to use 'id' as the composite
6882     // type so the result is acceptable for sending messages to.
6883 
6884     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6885     // It could return the composite type.
6886     if (!(compositeType =
6887           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6888       // Nothing more to do.
6889     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6890       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6891     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6892       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6893     } else if ((LHSTy->isObjCQualifiedIdType() ||
6894                 RHSTy->isObjCQualifiedIdType()) &&
6895                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6896       // Need to handle "id<xx>" explicitly.
6897       // GCC allows qualified id and any Objective-C type to devolve to
6898       // id. Currently localizing to here until clear this should be
6899       // part of ObjCQualifiedIdTypesAreCompatible.
6900       compositeType = Context.getObjCIdType();
6901     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6902       compositeType = Context.getObjCIdType();
6903     } else {
6904       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6905       << LHSTy << RHSTy
6906       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6907       QualType incompatTy = Context.getObjCIdType();
6908       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6909       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6910       return incompatTy;
6911     }
6912     // The object pointer types are compatible.
6913     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6914     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6915     return compositeType;
6916   }
6917   // Check Objective-C object pointer types and 'void *'
6918   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6919     if (getLangOpts().ObjCAutoRefCount) {
6920       // ARC forbids the implicit conversion of object pointers to 'void *',
6921       // so these types are not compatible.
6922       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6923           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6924       LHS = RHS = true;
6925       return QualType();
6926     }
6927     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6928     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6929     QualType destPointee
6930     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6931     QualType destType = Context.getPointerType(destPointee);
6932     // Add qualifiers if necessary.
6933     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6934     // Promote to void*.
6935     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6936     return destType;
6937   }
6938   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
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<ObjCObjectPointerType>()->getPointeeType();
6948     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6949     QualType destPointee
6950     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6951     QualType destType = Context.getPointerType(destPointee);
6952     // Add qualifiers if necessary.
6953     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6954     // Promote to void*.
6955     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6956     return destType;
6957   }
6958   return QualType();
6959 }
6960 
6961 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6962 /// ParenRange in parentheses.
6963 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6964                                const PartialDiagnostic &Note,
6965                                SourceRange ParenRange) {
6966   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6967   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6968       EndLoc.isValid()) {
6969     Self.Diag(Loc, Note)
6970       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6971       << FixItHint::CreateInsertion(EndLoc, ")");
6972   } else {
6973     // We can't display the parentheses, so just show the bare note.
6974     Self.Diag(Loc, Note) << ParenRange;
6975   }
6976 }
6977 
6978 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6979   return BinaryOperator::isAdditiveOp(Opc) ||
6980          BinaryOperator::isMultiplicativeOp(Opc) ||
6981          BinaryOperator::isShiftOp(Opc);
6982 }
6983 
6984 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6985 /// expression, either using a built-in or overloaded operator,
6986 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6987 /// expression.
6988 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6989                                    Expr **RHSExprs) {
6990   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6991   E = E->IgnoreImpCasts();
6992   E = E->IgnoreConversionOperator();
6993   E = E->IgnoreImpCasts();
6994 
6995   // Built-in binary operator.
6996   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6997     if (IsArithmeticOp(OP->getOpcode())) {
6998       *Opcode = OP->getOpcode();
6999       *RHSExprs = OP->getRHS();
7000       return true;
7001     }
7002   }
7003 
7004   // Overloaded operator.
7005   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7006     if (Call->getNumArgs() != 2)
7007       return false;
7008 
7009     // Make sure this is really a binary operator that is safe to pass into
7010     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7011     OverloadedOperatorKind OO = Call->getOperator();
7012     if (OO < OO_Plus || OO > OO_Arrow ||
7013         OO == OO_PlusPlus || OO == OO_MinusMinus)
7014       return false;
7015 
7016     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7017     if (IsArithmeticOp(OpKind)) {
7018       *Opcode = OpKind;
7019       *RHSExprs = Call->getArg(1);
7020       return true;
7021     }
7022   }
7023 
7024   return false;
7025 }
7026 
7027 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7028 /// or is a logical expression such as (x==y) which has int type, but is
7029 /// commonly interpreted as boolean.
7030 static bool ExprLooksBoolean(Expr *E) {
7031   E = E->IgnoreParenImpCasts();
7032 
7033   if (E->getType()->isBooleanType())
7034     return true;
7035   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7036     return OP->isComparisonOp() || OP->isLogicalOp();
7037   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7038     return OP->getOpcode() == UO_LNot;
7039   if (E->getType()->isPointerType())
7040     return true;
7041 
7042   return false;
7043 }
7044 
7045 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7046 /// and binary operator are mixed in a way that suggests the programmer assumed
7047 /// the conditional operator has higher precedence, for example:
7048 /// "int x = a + someBinaryCondition ? 1 : 2".
7049 static void DiagnoseConditionalPrecedence(Sema &Self,
7050                                           SourceLocation OpLoc,
7051                                           Expr *Condition,
7052                                           Expr *LHSExpr,
7053                                           Expr *RHSExpr) {
7054   BinaryOperatorKind CondOpcode;
7055   Expr *CondRHS;
7056 
7057   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7058     return;
7059   if (!ExprLooksBoolean(CondRHS))
7060     return;
7061 
7062   // The condition is an arithmetic binary expression, with a right-
7063   // hand side that looks boolean, so warn.
7064 
7065   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7066       << Condition->getSourceRange()
7067       << BinaryOperator::getOpcodeStr(CondOpcode);
7068 
7069   SuggestParentheses(Self, OpLoc,
7070     Self.PDiag(diag::note_precedence_silence)
7071       << BinaryOperator::getOpcodeStr(CondOpcode),
7072     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7073 
7074   SuggestParentheses(Self, OpLoc,
7075     Self.PDiag(diag::note_precedence_conditional_first),
7076     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7077 }
7078 
7079 /// Compute the nullability of a conditional expression.
7080 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7081                                               QualType LHSTy, QualType RHSTy,
7082                                               ASTContext &Ctx) {
7083   if (!ResTy->isAnyPointerType())
7084     return ResTy;
7085 
7086   auto GetNullability = [&Ctx](QualType Ty) {
7087     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7088     if (Kind)
7089       return *Kind;
7090     return NullabilityKind::Unspecified;
7091   };
7092 
7093   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7094   NullabilityKind MergedKind;
7095 
7096   // Compute nullability of a binary conditional expression.
7097   if (IsBin) {
7098     if (LHSKind == NullabilityKind::NonNull)
7099       MergedKind = NullabilityKind::NonNull;
7100     else
7101       MergedKind = RHSKind;
7102   // Compute nullability of a normal conditional expression.
7103   } else {
7104     if (LHSKind == NullabilityKind::Nullable ||
7105         RHSKind == NullabilityKind::Nullable)
7106       MergedKind = NullabilityKind::Nullable;
7107     else if (LHSKind == NullabilityKind::NonNull)
7108       MergedKind = RHSKind;
7109     else if (RHSKind == NullabilityKind::NonNull)
7110       MergedKind = LHSKind;
7111     else
7112       MergedKind = NullabilityKind::Unspecified;
7113   }
7114 
7115   // Return if ResTy already has the correct nullability.
7116   if (GetNullability(ResTy) == MergedKind)
7117     return ResTy;
7118 
7119   // Strip all nullability from ResTy.
7120   while (ResTy->getNullability(Ctx))
7121     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7122 
7123   // Create a new AttributedType with the new nullability kind.
7124   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7125   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7126 }
7127 
7128 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7129 /// in the case of a the GNU conditional expr extension.
7130 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7131                                     SourceLocation ColonLoc,
7132                                     Expr *CondExpr, Expr *LHSExpr,
7133                                     Expr *RHSExpr) {
7134   if (!getLangOpts().CPlusPlus) {
7135     // C cannot handle TypoExpr nodes in the condition because it
7136     // doesn't handle dependent types properly, so make sure any TypoExprs have
7137     // been dealt with before checking the operands.
7138     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7139     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7140     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7141 
7142     if (!CondResult.isUsable())
7143       return ExprError();
7144 
7145     if (LHSExpr) {
7146       if (!LHSResult.isUsable())
7147         return ExprError();
7148     }
7149 
7150     if (!RHSResult.isUsable())
7151       return ExprError();
7152 
7153     CondExpr = CondResult.get();
7154     LHSExpr = LHSResult.get();
7155     RHSExpr = RHSResult.get();
7156   }
7157 
7158   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7159   // was the condition.
7160   OpaqueValueExpr *opaqueValue = nullptr;
7161   Expr *commonExpr = nullptr;
7162   if (!LHSExpr) {
7163     commonExpr = CondExpr;
7164     // Lower out placeholder types first.  This is important so that we don't
7165     // try to capture a placeholder. This happens in few cases in C++; such
7166     // as Objective-C++'s dictionary subscripting syntax.
7167     if (commonExpr->hasPlaceholderType()) {
7168       ExprResult result = CheckPlaceholderExpr(commonExpr);
7169       if (!result.isUsable()) return ExprError();
7170       commonExpr = result.get();
7171     }
7172     // We usually want to apply unary conversions *before* saving, except
7173     // in the special case of a C++ l-value conditional.
7174     if (!(getLangOpts().CPlusPlus
7175           && !commonExpr->isTypeDependent()
7176           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7177           && commonExpr->isGLValue()
7178           && commonExpr->isOrdinaryOrBitFieldObject()
7179           && RHSExpr->isOrdinaryOrBitFieldObject()
7180           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7181       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7182       if (commonRes.isInvalid())
7183         return ExprError();
7184       commonExpr = commonRes.get();
7185     }
7186 
7187     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7188                                                 commonExpr->getType(),
7189                                                 commonExpr->getValueKind(),
7190                                                 commonExpr->getObjectKind(),
7191                                                 commonExpr);
7192     LHSExpr = CondExpr = opaqueValue;
7193   }
7194 
7195   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7196   ExprValueKind VK = VK_RValue;
7197   ExprObjectKind OK = OK_Ordinary;
7198   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7199   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7200                                              VK, OK, QuestionLoc);
7201   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7202       RHS.isInvalid())
7203     return ExprError();
7204 
7205   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7206                                 RHS.get());
7207 
7208   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7209 
7210   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7211                                          Context);
7212 
7213   if (!commonExpr)
7214     return new (Context)
7215         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7216                             RHS.get(), result, VK, OK);
7217 
7218   return new (Context) BinaryConditionalOperator(
7219       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7220       ColonLoc, result, VK, OK);
7221 }
7222 
7223 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7224 // being closely modeled after the C99 spec:-). The odd characteristic of this
7225 // routine is it effectively iqnores the qualifiers on the top level pointee.
7226 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7227 // FIXME: add a couple examples in this comment.
7228 static Sema::AssignConvertType
7229 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7230   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7231   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7232 
7233   // get the "pointed to" type (ignoring qualifiers at the top level)
7234   const Type *lhptee, *rhptee;
7235   Qualifiers lhq, rhq;
7236   std::tie(lhptee, lhq) =
7237       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7238   std::tie(rhptee, rhq) =
7239       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7240 
7241   Sema::AssignConvertType ConvTy = Sema::Compatible;
7242 
7243   // C99 6.5.16.1p1: This following citation is common to constraints
7244   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7245   // qualifiers of the type *pointed to* by the right;
7246 
7247   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7248   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7249       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7250     // Ignore lifetime for further calculation.
7251     lhq.removeObjCLifetime();
7252     rhq.removeObjCLifetime();
7253   }
7254 
7255   if (!lhq.compatiblyIncludes(rhq)) {
7256     // Treat address-space mismatches as fatal.  TODO: address subspaces
7257     if (!lhq.isAddressSpaceSupersetOf(rhq))
7258       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7259 
7260     // It's okay to add or remove GC or lifetime qualifiers when converting to
7261     // and from void*.
7262     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7263                         .compatiblyIncludes(
7264                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7265              && (lhptee->isVoidType() || rhptee->isVoidType()))
7266       ; // keep old
7267 
7268     // Treat lifetime mismatches as fatal.
7269     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7270       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7271 
7272     // For GCC/MS compatibility, other qualifier mismatches are treated
7273     // as still compatible in C.
7274     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7275   }
7276 
7277   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7278   // incomplete type and the other is a pointer to a qualified or unqualified
7279   // version of void...
7280   if (lhptee->isVoidType()) {
7281     if (rhptee->isIncompleteOrObjectType())
7282       return ConvTy;
7283 
7284     // As an extension, we allow cast to/from void* to function pointer.
7285     assert(rhptee->isFunctionType());
7286     return Sema::FunctionVoidPointer;
7287   }
7288 
7289   if (rhptee->isVoidType()) {
7290     if (lhptee->isIncompleteOrObjectType())
7291       return ConvTy;
7292 
7293     // As an extension, we allow cast to/from void* to function pointer.
7294     assert(lhptee->isFunctionType());
7295     return Sema::FunctionVoidPointer;
7296   }
7297 
7298   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7299   // unqualified versions of compatible types, ...
7300   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7301   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7302     // Check if the pointee types are compatible ignoring the sign.
7303     // We explicitly check for char so that we catch "char" vs
7304     // "unsigned char" on systems where "char" is unsigned.
7305     if (lhptee->isCharType())
7306       ltrans = S.Context.UnsignedCharTy;
7307     else if (lhptee->hasSignedIntegerRepresentation())
7308       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7309 
7310     if (rhptee->isCharType())
7311       rtrans = S.Context.UnsignedCharTy;
7312     else if (rhptee->hasSignedIntegerRepresentation())
7313       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7314 
7315     if (ltrans == rtrans) {
7316       // Types are compatible ignoring the sign. Qualifier incompatibility
7317       // takes priority over sign incompatibility because the sign
7318       // warning can be disabled.
7319       if (ConvTy != Sema::Compatible)
7320         return ConvTy;
7321 
7322       return Sema::IncompatiblePointerSign;
7323     }
7324 
7325     // If we are a multi-level pointer, it's possible that our issue is simply
7326     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7327     // the eventual target type is the same and the pointers have the same
7328     // level of indirection, this must be the issue.
7329     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7330       do {
7331         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7332         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7333       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7334 
7335       if (lhptee == rhptee)
7336         return Sema::IncompatibleNestedPointerQualifiers;
7337     }
7338 
7339     // General pointer incompatibility takes priority over qualifiers.
7340     return Sema::IncompatiblePointer;
7341   }
7342   if (!S.getLangOpts().CPlusPlus &&
7343       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7344     return Sema::IncompatiblePointer;
7345   return ConvTy;
7346 }
7347 
7348 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7349 /// block pointer types are compatible or whether a block and normal pointer
7350 /// are compatible. It is more restrict than comparing two function pointer
7351 // types.
7352 static Sema::AssignConvertType
7353 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7354                                     QualType RHSType) {
7355   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7356   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7357 
7358   QualType lhptee, rhptee;
7359 
7360   // get the "pointed to" type (ignoring qualifiers at the top level)
7361   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7362   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7363 
7364   // In C++, the types have to match exactly.
7365   if (S.getLangOpts().CPlusPlus)
7366     return Sema::IncompatibleBlockPointer;
7367 
7368   Sema::AssignConvertType ConvTy = Sema::Compatible;
7369 
7370   // For blocks we enforce that qualifiers are identical.
7371   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7372     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7373 
7374   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7375     return Sema::IncompatibleBlockPointer;
7376 
7377   return ConvTy;
7378 }
7379 
7380 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7381 /// for assignment compatibility.
7382 static Sema::AssignConvertType
7383 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7384                                    QualType RHSType) {
7385   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7386   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7387 
7388   if (LHSType->isObjCBuiltinType()) {
7389     // Class is not compatible with ObjC object pointers.
7390     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7391         !RHSType->isObjCQualifiedClassType())
7392       return Sema::IncompatiblePointer;
7393     return Sema::Compatible;
7394   }
7395   if (RHSType->isObjCBuiltinType()) {
7396     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7397         !LHSType->isObjCQualifiedClassType())
7398       return Sema::IncompatiblePointer;
7399     return Sema::Compatible;
7400   }
7401   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7402   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7403 
7404   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7405       // make an exception for id<P>
7406       !LHSType->isObjCQualifiedIdType())
7407     return Sema::CompatiblePointerDiscardsQualifiers;
7408 
7409   if (S.Context.typesAreCompatible(LHSType, RHSType))
7410     return Sema::Compatible;
7411   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7412     return Sema::IncompatibleObjCQualifiedId;
7413   return Sema::IncompatiblePointer;
7414 }
7415 
7416 Sema::AssignConvertType
7417 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7418                                  QualType LHSType, QualType RHSType) {
7419   // Fake up an opaque expression.  We don't actually care about what
7420   // cast operations are required, so if CheckAssignmentConstraints
7421   // adds casts to this they'll be wasted, but fortunately that doesn't
7422   // usually happen on valid code.
7423   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7424   ExprResult RHSPtr = &RHSExpr;
7425   CastKind K = CK_Invalid;
7426 
7427   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7428 }
7429 
7430 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7431 /// has code to accommodate several GCC extensions when type checking
7432 /// pointers. Here are some objectionable examples that GCC considers warnings:
7433 ///
7434 ///  int a, *pint;
7435 ///  short *pshort;
7436 ///  struct foo *pfoo;
7437 ///
7438 ///  pint = pshort; // warning: assignment from incompatible pointer type
7439 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7440 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7441 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7442 ///
7443 /// As a result, the code for dealing with pointers is more complex than the
7444 /// C99 spec dictates.
7445 ///
7446 /// Sets 'Kind' for any result kind except Incompatible.
7447 Sema::AssignConvertType
7448 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7449                                  CastKind &Kind, bool ConvertRHS) {
7450   QualType RHSType = RHS.get()->getType();
7451   QualType OrigLHSType = LHSType;
7452 
7453   // Get canonical types.  We're not formatting these types, just comparing
7454   // them.
7455   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7456   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7457 
7458   // Common case: no conversion required.
7459   if (LHSType == RHSType) {
7460     Kind = CK_NoOp;
7461     return Compatible;
7462   }
7463 
7464   // If we have an atomic type, try a non-atomic assignment, then just add an
7465   // atomic qualification step.
7466   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7467     Sema::AssignConvertType result =
7468       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7469     if (result != Compatible)
7470       return result;
7471     if (Kind != CK_NoOp && ConvertRHS)
7472       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7473     Kind = CK_NonAtomicToAtomic;
7474     return Compatible;
7475   }
7476 
7477   // If the left-hand side is a reference type, then we are in a
7478   // (rare!) case where we've allowed the use of references in C,
7479   // e.g., as a parameter type in a built-in function. In this case,
7480   // just make sure that the type referenced is compatible with the
7481   // right-hand side type. The caller is responsible for adjusting
7482   // LHSType so that the resulting expression does not have reference
7483   // type.
7484   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7485     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7486       Kind = CK_LValueBitCast;
7487       return Compatible;
7488     }
7489     return Incompatible;
7490   }
7491 
7492   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7493   // to the same ExtVector type.
7494   if (LHSType->isExtVectorType()) {
7495     if (RHSType->isExtVectorType())
7496       return Incompatible;
7497     if (RHSType->isArithmeticType()) {
7498       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7499       if (ConvertRHS)
7500         RHS = prepareVectorSplat(LHSType, RHS.get());
7501       Kind = CK_VectorSplat;
7502       return Compatible;
7503     }
7504   }
7505 
7506   // Conversions to or from vector type.
7507   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7508     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7509       // Allow assignments of an AltiVec vector type to an equivalent GCC
7510       // vector type and vice versa
7511       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7512         Kind = CK_BitCast;
7513         return Compatible;
7514       }
7515 
7516       // If we are allowing lax vector conversions, and LHS and RHS are both
7517       // vectors, the total size only needs to be the same. This is a bitcast;
7518       // no bits are changed but the result type is different.
7519       if (isLaxVectorConversion(RHSType, LHSType)) {
7520         Kind = CK_BitCast;
7521         return IncompatibleVectors;
7522       }
7523     }
7524 
7525     // When the RHS comes from another lax conversion (e.g. binops between
7526     // scalars and vectors) the result is canonicalized as a vector. When the
7527     // LHS is also a vector, the lax is allowed by the condition above. Handle
7528     // the case where LHS is a scalar.
7529     if (LHSType->isScalarType()) {
7530       const VectorType *VecType = RHSType->getAs<VectorType>();
7531       if (VecType && VecType->getNumElements() == 1 &&
7532           isLaxVectorConversion(RHSType, LHSType)) {
7533         ExprResult *VecExpr = &RHS;
7534         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7535         Kind = CK_BitCast;
7536         return Compatible;
7537       }
7538     }
7539 
7540     return Incompatible;
7541   }
7542 
7543   // Diagnose attempts to convert between __float128 and long double where
7544   // such conversions currently can't be handled.
7545   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7546     return Incompatible;
7547 
7548   // Arithmetic conversions.
7549   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7550       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7551     if (ConvertRHS)
7552       Kind = PrepareScalarCast(RHS, LHSType);
7553     return Compatible;
7554   }
7555 
7556   // Conversions to normal pointers.
7557   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7558     // U* -> T*
7559     if (isa<PointerType>(RHSType)) {
7560       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7561       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7562       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7563       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7564     }
7565 
7566     // int -> T*
7567     if (RHSType->isIntegerType()) {
7568       Kind = CK_IntegralToPointer; // FIXME: null?
7569       return IntToPointer;
7570     }
7571 
7572     // C pointers are not compatible with ObjC object pointers,
7573     // with two exceptions:
7574     if (isa<ObjCObjectPointerType>(RHSType)) {
7575       //  - conversions to void*
7576       if (LHSPointer->getPointeeType()->isVoidType()) {
7577         Kind = CK_BitCast;
7578         return Compatible;
7579       }
7580 
7581       //  - conversions from 'Class' to the redefinition type
7582       if (RHSType->isObjCClassType() &&
7583           Context.hasSameType(LHSType,
7584                               Context.getObjCClassRedefinitionType())) {
7585         Kind = CK_BitCast;
7586         return Compatible;
7587       }
7588 
7589       Kind = CK_BitCast;
7590       return IncompatiblePointer;
7591     }
7592 
7593     // U^ -> void*
7594     if (RHSType->getAs<BlockPointerType>()) {
7595       if (LHSPointer->getPointeeType()->isVoidType()) {
7596         Kind = CK_BitCast;
7597         return Compatible;
7598       }
7599     }
7600 
7601     return Incompatible;
7602   }
7603 
7604   // Conversions to block pointers.
7605   if (isa<BlockPointerType>(LHSType)) {
7606     // U^ -> T^
7607     if (RHSType->isBlockPointerType()) {
7608       Kind = CK_BitCast;
7609       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7610     }
7611 
7612     // int or null -> T^
7613     if (RHSType->isIntegerType()) {
7614       Kind = CK_IntegralToPointer; // FIXME: null
7615       return IntToBlockPointer;
7616     }
7617 
7618     // id -> T^
7619     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7620       Kind = CK_AnyPointerToBlockPointerCast;
7621       return Compatible;
7622     }
7623 
7624     // void* -> T^
7625     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7626       if (RHSPT->getPointeeType()->isVoidType()) {
7627         Kind = CK_AnyPointerToBlockPointerCast;
7628         return Compatible;
7629       }
7630 
7631     return Incompatible;
7632   }
7633 
7634   // Conversions to Objective-C pointers.
7635   if (isa<ObjCObjectPointerType>(LHSType)) {
7636     // A* -> B*
7637     if (RHSType->isObjCObjectPointerType()) {
7638       Kind = CK_BitCast;
7639       Sema::AssignConvertType result =
7640         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7641       if (getLangOpts().ObjCAutoRefCount &&
7642           result == Compatible &&
7643           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7644         result = IncompatibleObjCWeakRef;
7645       return result;
7646     }
7647 
7648     // int or null -> A*
7649     if (RHSType->isIntegerType()) {
7650       Kind = CK_IntegralToPointer; // FIXME: null
7651       return IntToPointer;
7652     }
7653 
7654     // In general, C pointers are not compatible with ObjC object pointers,
7655     // with two exceptions:
7656     if (isa<PointerType>(RHSType)) {
7657       Kind = CK_CPointerToObjCPointerCast;
7658 
7659       //  - conversions from 'void*'
7660       if (RHSType->isVoidPointerType()) {
7661         return Compatible;
7662       }
7663 
7664       //  - conversions to 'Class' from its redefinition type
7665       if (LHSType->isObjCClassType() &&
7666           Context.hasSameType(RHSType,
7667                               Context.getObjCClassRedefinitionType())) {
7668         return Compatible;
7669       }
7670 
7671       return IncompatiblePointer;
7672     }
7673 
7674     // Only under strict condition T^ is compatible with an Objective-C pointer.
7675     if (RHSType->isBlockPointerType() &&
7676         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7677       if (ConvertRHS)
7678         maybeExtendBlockObject(RHS);
7679       Kind = CK_BlockPointerToObjCPointerCast;
7680       return Compatible;
7681     }
7682 
7683     return Incompatible;
7684   }
7685 
7686   // Conversions from pointers that are not covered by the above.
7687   if (isa<PointerType>(RHSType)) {
7688     // T* -> _Bool
7689     if (LHSType == Context.BoolTy) {
7690       Kind = CK_PointerToBoolean;
7691       return Compatible;
7692     }
7693 
7694     // T* -> int
7695     if (LHSType->isIntegerType()) {
7696       Kind = CK_PointerToIntegral;
7697       return PointerToInt;
7698     }
7699 
7700     return Incompatible;
7701   }
7702 
7703   // Conversions from Objective-C pointers that are not covered by the above.
7704   if (isa<ObjCObjectPointerType>(RHSType)) {
7705     // T* -> _Bool
7706     if (LHSType == Context.BoolTy) {
7707       Kind = CK_PointerToBoolean;
7708       return Compatible;
7709     }
7710 
7711     // T* -> int
7712     if (LHSType->isIntegerType()) {
7713       Kind = CK_PointerToIntegral;
7714       return PointerToInt;
7715     }
7716 
7717     return Incompatible;
7718   }
7719 
7720   // struct A -> struct B
7721   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7722     if (Context.typesAreCompatible(LHSType, RHSType)) {
7723       Kind = CK_NoOp;
7724       return Compatible;
7725     }
7726   }
7727 
7728   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7729     Kind = CK_IntToOCLSampler;
7730     return Compatible;
7731   }
7732 
7733   return Incompatible;
7734 }
7735 
7736 /// \brief Constructs a transparent union from an expression that is
7737 /// used to initialize the transparent union.
7738 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7739                                       ExprResult &EResult, QualType UnionType,
7740                                       FieldDecl *Field) {
7741   // Build an initializer list that designates the appropriate member
7742   // of the transparent union.
7743   Expr *E = EResult.get();
7744   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7745                                                    E, SourceLocation());
7746   Initializer->setType(UnionType);
7747   Initializer->setInitializedFieldInUnion(Field);
7748 
7749   // Build a compound literal constructing a value of the transparent
7750   // union type from this initializer list.
7751   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7752   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7753                                         VK_RValue, Initializer, false);
7754 }
7755 
7756 Sema::AssignConvertType
7757 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7758                                                ExprResult &RHS) {
7759   QualType RHSType = RHS.get()->getType();
7760 
7761   // If the ArgType is a Union type, we want to handle a potential
7762   // transparent_union GCC extension.
7763   const RecordType *UT = ArgType->getAsUnionType();
7764   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7765     return Incompatible;
7766 
7767   // The field to initialize within the transparent union.
7768   RecordDecl *UD = UT->getDecl();
7769   FieldDecl *InitField = nullptr;
7770   // It's compatible if the expression matches any of the fields.
7771   for (auto *it : UD->fields()) {
7772     if (it->getType()->isPointerType()) {
7773       // If the transparent union contains a pointer type, we allow:
7774       // 1) void pointer
7775       // 2) null pointer constant
7776       if (RHSType->isPointerType())
7777         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7778           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7779           InitField = it;
7780           break;
7781         }
7782 
7783       if (RHS.get()->isNullPointerConstant(Context,
7784                                            Expr::NPC_ValueDependentIsNull)) {
7785         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7786                                 CK_NullToPointer);
7787         InitField = it;
7788         break;
7789       }
7790     }
7791 
7792     CastKind Kind = CK_Invalid;
7793     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7794           == Compatible) {
7795       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7796       InitField = it;
7797       break;
7798     }
7799   }
7800 
7801   if (!InitField)
7802     return Incompatible;
7803 
7804   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7805   return Compatible;
7806 }
7807 
7808 Sema::AssignConvertType
7809 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7810                                        bool Diagnose,
7811                                        bool DiagnoseCFAudited,
7812                                        bool ConvertRHS) {
7813   // We need to be able to tell the caller whether we diagnosed a problem, if
7814   // they ask us to issue diagnostics.
7815   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7816 
7817   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7818   // we can't avoid *all* modifications at the moment, so we need some somewhere
7819   // to put the updated value.
7820   ExprResult LocalRHS = CallerRHS;
7821   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7822 
7823   if (getLangOpts().CPlusPlus) {
7824     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7825       // C++ 5.17p3: If the left operand is not of class type, the
7826       // expression is implicitly converted (C++ 4) to the
7827       // cv-unqualified type of the left operand.
7828       QualType RHSType = RHS.get()->getType();
7829       if (Diagnose) {
7830         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7831                                         AA_Assigning);
7832       } else {
7833         ImplicitConversionSequence ICS =
7834             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7835                                   /*SuppressUserConversions=*/false,
7836                                   /*AllowExplicit=*/false,
7837                                   /*InOverloadResolution=*/false,
7838                                   /*CStyle=*/false,
7839                                   /*AllowObjCWritebackConversion=*/false);
7840         if (ICS.isFailure())
7841           return Incompatible;
7842         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7843                                         ICS, AA_Assigning);
7844       }
7845       if (RHS.isInvalid())
7846         return Incompatible;
7847       Sema::AssignConvertType result = Compatible;
7848       if (getLangOpts().ObjCAutoRefCount &&
7849           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7850         result = IncompatibleObjCWeakRef;
7851       return result;
7852     }
7853 
7854     // FIXME: Currently, we fall through and treat C++ classes like C
7855     // structures.
7856     // FIXME: We also fall through for atomics; not sure what should
7857     // happen there, though.
7858   } else if (RHS.get()->getType() == Context.OverloadTy) {
7859     // As a set of extensions to C, we support overloading on functions. These
7860     // functions need to be resolved here.
7861     DeclAccessPair DAP;
7862     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7863             RHS.get(), LHSType, /*Complain=*/false, DAP))
7864       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7865     else
7866       return Incompatible;
7867   }
7868 
7869   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7870   // a null pointer constant.
7871   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7872        LHSType->isBlockPointerType()) &&
7873       RHS.get()->isNullPointerConstant(Context,
7874                                        Expr::NPC_ValueDependentIsNull)) {
7875     if (Diagnose || ConvertRHS) {
7876       CastKind Kind;
7877       CXXCastPath Path;
7878       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7879                              /*IgnoreBaseAccess=*/false, Diagnose);
7880       if (ConvertRHS)
7881         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7882     }
7883     return Compatible;
7884   }
7885 
7886   // This check seems unnatural, however it is necessary to ensure the proper
7887   // conversion of functions/arrays. If the conversion were done for all
7888   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7889   // expressions that suppress this implicit conversion (&, sizeof).
7890   //
7891   // Suppress this for references: C++ 8.5.3p5.
7892   if (!LHSType->isReferenceType()) {
7893     // FIXME: We potentially allocate here even if ConvertRHS is false.
7894     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7895     if (RHS.isInvalid())
7896       return Incompatible;
7897   }
7898 
7899   Expr *PRE = RHS.get()->IgnoreParenCasts();
7900   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7901     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7902     if (PDecl && !PDecl->hasDefinition()) {
7903       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7904       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7905     }
7906   }
7907 
7908   CastKind Kind = CK_Invalid;
7909   Sema::AssignConvertType result =
7910     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7911 
7912   // C99 6.5.16.1p2: The value of the right operand is converted to the
7913   // type of the assignment expression.
7914   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7915   // so that we can use references in built-in functions even in C.
7916   // The getNonReferenceType() call makes sure that the resulting expression
7917   // does not have reference type.
7918   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7919     QualType Ty = LHSType.getNonLValueExprType(Context);
7920     Expr *E = RHS.get();
7921 
7922     // Check for various Objective-C errors. If we are not reporting
7923     // diagnostics and just checking for errors, e.g., during overload
7924     // resolution, return Incompatible to indicate the failure.
7925     if (getLangOpts().ObjCAutoRefCount &&
7926         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7927                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7928       if (!Diagnose)
7929         return Incompatible;
7930     }
7931     if (getLangOpts().ObjC1 &&
7932         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7933                                            E->getType(), E, Diagnose) ||
7934          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7935       if (!Diagnose)
7936         return Incompatible;
7937       // Replace the expression with a corrected version and continue so we
7938       // can find further errors.
7939       RHS = E;
7940       return Compatible;
7941     }
7942 
7943     if (ConvertRHS)
7944       RHS = ImpCastExprToType(E, Ty, Kind);
7945   }
7946   return result;
7947 }
7948 
7949 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7950                                ExprResult &RHS) {
7951   Diag(Loc, diag::err_typecheck_invalid_operands)
7952     << LHS.get()->getType() << RHS.get()->getType()
7953     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7954   return QualType();
7955 }
7956 
7957 /// Try to convert a value of non-vector type to a vector type by converting
7958 /// the type to the element type of the vector and then performing a splat.
7959 /// If the language is OpenCL, we only use conversions that promote scalar
7960 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7961 /// for float->int.
7962 ///
7963 /// \param scalar - if non-null, actually perform the conversions
7964 /// \return true if the operation fails (but without diagnosing the failure)
7965 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7966                                      QualType scalarTy,
7967                                      QualType vectorEltTy,
7968                                      QualType vectorTy) {
7969   // The conversion to apply to the scalar before splatting it,
7970   // if necessary.
7971   CastKind scalarCast = CK_Invalid;
7972 
7973   if (vectorEltTy->isIntegralType(S.Context)) {
7974     if (!scalarTy->isIntegralType(S.Context))
7975       return true;
7976     if (S.getLangOpts().OpenCL &&
7977         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7978       return true;
7979     scalarCast = CK_IntegralCast;
7980   } else if (vectorEltTy->isRealFloatingType()) {
7981     if (scalarTy->isRealFloatingType()) {
7982       if (S.getLangOpts().OpenCL &&
7983           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7984         return true;
7985       scalarCast = CK_FloatingCast;
7986     }
7987     else if (scalarTy->isIntegralType(S.Context))
7988       scalarCast = CK_IntegralToFloating;
7989     else
7990       return true;
7991   } else {
7992     return true;
7993   }
7994 
7995   // Adjust scalar if desired.
7996   if (scalar) {
7997     if (scalarCast != CK_Invalid)
7998       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7999     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8000   }
8001   return false;
8002 }
8003 
8004 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8005                                    SourceLocation Loc, bool IsCompAssign,
8006                                    bool AllowBothBool,
8007                                    bool AllowBoolConversions) {
8008   if (!IsCompAssign) {
8009     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8010     if (LHS.isInvalid())
8011       return QualType();
8012   }
8013   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8014   if (RHS.isInvalid())
8015     return QualType();
8016 
8017   // For conversion purposes, we ignore any qualifiers.
8018   // For example, "const float" and "float" are equivalent.
8019   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8020   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8021 
8022   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8023   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8024   assert(LHSVecType || RHSVecType);
8025 
8026   // AltiVec-style "vector bool op vector bool" combinations are allowed
8027   // for some operators but not others.
8028   if (!AllowBothBool &&
8029       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8030       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8031     return InvalidOperands(Loc, LHS, RHS);
8032 
8033   // If the vector types are identical, return.
8034   if (Context.hasSameType(LHSType, RHSType))
8035     return LHSType;
8036 
8037   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8038   if (LHSVecType && RHSVecType &&
8039       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8040     if (isa<ExtVectorType>(LHSVecType)) {
8041       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8042       return LHSType;
8043     }
8044 
8045     if (!IsCompAssign)
8046       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8047     return RHSType;
8048   }
8049 
8050   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8051   // can be mixed, with the result being the non-bool type.  The non-bool
8052   // operand must have integer element type.
8053   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8054       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8055       (Context.getTypeSize(LHSVecType->getElementType()) ==
8056        Context.getTypeSize(RHSVecType->getElementType()))) {
8057     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8058         LHSVecType->getElementType()->isIntegerType() &&
8059         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8060       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8061       return LHSType;
8062     }
8063     if (!IsCompAssign &&
8064         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8065         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8066         RHSVecType->getElementType()->isIntegerType()) {
8067       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8068       return RHSType;
8069     }
8070   }
8071 
8072   // If there's an ext-vector type and a scalar, try to convert the scalar to
8073   // the vector element type and splat.
8074   // FIXME: this should also work for regular vector types as supported in GCC.
8075   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8076     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8077                                   LHSVecType->getElementType(), LHSType))
8078       return LHSType;
8079   }
8080   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8081     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8082                                   LHSType, RHSVecType->getElementType(),
8083                                   RHSType))
8084       return RHSType;
8085   }
8086 
8087   // FIXME: The code below also handles convertion between vectors and
8088   // non-scalars, we should break this down into fine grained specific checks
8089   // and emit proper diagnostics.
8090   QualType VecType = LHSVecType ? LHSType : RHSType;
8091   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8092   QualType OtherType = LHSVecType ? RHSType : LHSType;
8093   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8094   if (isLaxVectorConversion(OtherType, VecType)) {
8095     // If we're allowing lax vector conversions, only the total (data) size
8096     // needs to be the same. For non compound assignment, if one of the types is
8097     // scalar, the result is always the vector type.
8098     if (!IsCompAssign) {
8099       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8100       return VecType;
8101     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8102     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8103     // type. Note that this is already done by non-compound assignments in
8104     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8105     // <1 x T> -> T. The result is also a vector type.
8106     } else if (OtherType->isExtVectorType() ||
8107                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8108       ExprResult *RHSExpr = &RHS;
8109       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8110       return VecType;
8111     }
8112   }
8113 
8114   // Okay, the expression is invalid.
8115 
8116   // If there's a non-vector, non-real operand, diagnose that.
8117   if ((!RHSVecType && !RHSType->isRealType()) ||
8118       (!LHSVecType && !LHSType->isRealType())) {
8119     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8120       << LHSType << RHSType
8121       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8122     return QualType();
8123   }
8124 
8125   // OpenCL V1.1 6.2.6.p1:
8126   // If the operands are of more than one vector type, then an error shall
8127   // occur. Implicit conversions between vector types are not permitted, per
8128   // section 6.2.1.
8129   if (getLangOpts().OpenCL &&
8130       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8131       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8132     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8133                                                            << RHSType;
8134     return QualType();
8135   }
8136 
8137   // Otherwise, use the generic diagnostic.
8138   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8139     << LHSType << RHSType
8140     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8141   return QualType();
8142 }
8143 
8144 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8145 // expression.  These are mainly cases where the null pointer is used as an
8146 // integer instead of a pointer.
8147 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8148                                 SourceLocation Loc, bool IsCompare) {
8149   // The canonical way to check for a GNU null is with isNullPointerConstant,
8150   // but we use a bit of a hack here for speed; this is a relatively
8151   // hot path, and isNullPointerConstant is slow.
8152   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8153   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8154 
8155   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8156 
8157   // Avoid analyzing cases where the result will either be invalid (and
8158   // diagnosed as such) or entirely valid and not something to warn about.
8159   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8160       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8161     return;
8162 
8163   // Comparison operations would not make sense with a null pointer no matter
8164   // what the other expression is.
8165   if (!IsCompare) {
8166     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8167         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8168         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8169     return;
8170   }
8171 
8172   // The rest of the operations only make sense with a null pointer
8173   // if the other expression is a pointer.
8174   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8175       NonNullType->canDecayToPointerType())
8176     return;
8177 
8178   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8179       << LHSNull /* LHS is NULL */ << NonNullType
8180       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8181 }
8182 
8183 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8184                                                ExprResult &RHS,
8185                                                SourceLocation Loc, bool IsDiv) {
8186   // Check for division/remainder by zero.
8187   llvm::APSInt RHSValue;
8188   if (!RHS.get()->isValueDependent() &&
8189       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8190     S.DiagRuntimeBehavior(Loc, RHS.get(),
8191                           S.PDiag(diag::warn_remainder_division_by_zero)
8192                             << IsDiv << RHS.get()->getSourceRange());
8193 }
8194 
8195 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8196                                            SourceLocation Loc,
8197                                            bool IsCompAssign, bool IsDiv) {
8198   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8199 
8200   if (LHS.get()->getType()->isVectorType() ||
8201       RHS.get()->getType()->isVectorType())
8202     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8203                                /*AllowBothBool*/getLangOpts().AltiVec,
8204                                /*AllowBoolConversions*/false);
8205 
8206   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8207   if (LHS.isInvalid() || RHS.isInvalid())
8208     return QualType();
8209 
8210 
8211   if (compType.isNull() || !compType->isArithmeticType())
8212     return InvalidOperands(Loc, LHS, RHS);
8213   if (IsDiv)
8214     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8215   return compType;
8216 }
8217 
8218 QualType Sema::CheckRemainderOperands(
8219   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8220   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8221 
8222   if (LHS.get()->getType()->isVectorType() ||
8223       RHS.get()->getType()->isVectorType()) {
8224     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8225         RHS.get()->getType()->hasIntegerRepresentation())
8226       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8227                                  /*AllowBothBool*/getLangOpts().AltiVec,
8228                                  /*AllowBoolConversions*/false);
8229     return InvalidOperands(Loc, LHS, RHS);
8230   }
8231 
8232   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8233   if (LHS.isInvalid() || RHS.isInvalid())
8234     return QualType();
8235 
8236   if (compType.isNull() || !compType->isIntegerType())
8237     return InvalidOperands(Loc, LHS, RHS);
8238   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8239   return compType;
8240 }
8241 
8242 /// \brief Diagnose invalid arithmetic on two void pointers.
8243 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8244                                                 Expr *LHSExpr, Expr *RHSExpr) {
8245   S.Diag(Loc, S.getLangOpts().CPlusPlus
8246                 ? diag::err_typecheck_pointer_arith_void_type
8247                 : diag::ext_gnu_void_ptr)
8248     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8249                             << RHSExpr->getSourceRange();
8250 }
8251 
8252 /// \brief Diagnose invalid arithmetic on a void pointer.
8253 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8254                                             Expr *Pointer) {
8255   S.Diag(Loc, S.getLangOpts().CPlusPlus
8256                 ? diag::err_typecheck_pointer_arith_void_type
8257                 : diag::ext_gnu_void_ptr)
8258     << 0 /* one pointer */ << Pointer->getSourceRange();
8259 }
8260 
8261 /// \brief Diagnose invalid arithmetic on two function pointers.
8262 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8263                                                     Expr *LHS, Expr *RHS) {
8264   assert(LHS->getType()->isAnyPointerType());
8265   assert(RHS->getType()->isAnyPointerType());
8266   S.Diag(Loc, S.getLangOpts().CPlusPlus
8267                 ? diag::err_typecheck_pointer_arith_function_type
8268                 : diag::ext_gnu_ptr_func_arith)
8269     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8270     // We only show the second type if it differs from the first.
8271     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8272                                                    RHS->getType())
8273     << RHS->getType()->getPointeeType()
8274     << LHS->getSourceRange() << RHS->getSourceRange();
8275 }
8276 
8277 /// \brief Diagnose invalid arithmetic on a function pointer.
8278 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8279                                                 Expr *Pointer) {
8280   assert(Pointer->getType()->isAnyPointerType());
8281   S.Diag(Loc, S.getLangOpts().CPlusPlus
8282                 ? diag::err_typecheck_pointer_arith_function_type
8283                 : diag::ext_gnu_ptr_func_arith)
8284     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8285     << 0 /* one pointer, so only one type */
8286     << Pointer->getSourceRange();
8287 }
8288 
8289 /// \brief Emit error if Operand is incomplete pointer type
8290 ///
8291 /// \returns True if pointer has incomplete type
8292 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8293                                                  Expr *Operand) {
8294   QualType ResType = Operand->getType();
8295   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8296     ResType = ResAtomicType->getValueType();
8297 
8298   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8299   QualType PointeeTy = ResType->getPointeeType();
8300   return S.RequireCompleteType(Loc, PointeeTy,
8301                                diag::err_typecheck_arithmetic_incomplete_type,
8302                                PointeeTy, Operand->getSourceRange());
8303 }
8304 
8305 /// \brief Check the validity of an arithmetic pointer operand.
8306 ///
8307 /// If the operand has pointer type, this code will check for pointer types
8308 /// which are invalid in arithmetic operations. These will be diagnosed
8309 /// appropriately, including whether or not the use is supported as an
8310 /// extension.
8311 ///
8312 /// \returns True when the operand is valid to use (even if as an extension).
8313 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8314                                             Expr *Operand) {
8315   QualType ResType = Operand->getType();
8316   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8317     ResType = ResAtomicType->getValueType();
8318 
8319   if (!ResType->isAnyPointerType()) return true;
8320 
8321   QualType PointeeTy = ResType->getPointeeType();
8322   if (PointeeTy->isVoidType()) {
8323     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8324     return !S.getLangOpts().CPlusPlus;
8325   }
8326   if (PointeeTy->isFunctionType()) {
8327     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8328     return !S.getLangOpts().CPlusPlus;
8329   }
8330 
8331   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8332 
8333   return true;
8334 }
8335 
8336 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8337 /// operands.
8338 ///
8339 /// This routine will diagnose any invalid arithmetic on pointer operands much
8340 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8341 /// for emitting a single diagnostic even for operations where both LHS and RHS
8342 /// are (potentially problematic) pointers.
8343 ///
8344 /// \returns True when the operand is valid to use (even if as an extension).
8345 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8346                                                 Expr *LHSExpr, Expr *RHSExpr) {
8347   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8348   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8349   if (!isLHSPointer && !isRHSPointer) return true;
8350 
8351   QualType LHSPointeeTy, RHSPointeeTy;
8352   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8353   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8354 
8355   // if both are pointers check if operation is valid wrt address spaces
8356   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8357     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8358     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8359     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8360       S.Diag(Loc,
8361              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8362           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8363           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8364       return false;
8365     }
8366   }
8367 
8368   // Check for arithmetic on pointers to incomplete types.
8369   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8370   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8371   if (isLHSVoidPtr || isRHSVoidPtr) {
8372     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8373     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8374     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8375 
8376     return !S.getLangOpts().CPlusPlus;
8377   }
8378 
8379   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8380   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8381   if (isLHSFuncPtr || isRHSFuncPtr) {
8382     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8383     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8384                                                                 RHSExpr);
8385     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8386 
8387     return !S.getLangOpts().CPlusPlus;
8388   }
8389 
8390   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8391     return false;
8392   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8393     return false;
8394 
8395   return true;
8396 }
8397 
8398 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8399 /// literal.
8400 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8401                                   Expr *LHSExpr, Expr *RHSExpr) {
8402   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8403   Expr* IndexExpr = RHSExpr;
8404   if (!StrExpr) {
8405     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8406     IndexExpr = LHSExpr;
8407   }
8408 
8409   bool IsStringPlusInt = StrExpr &&
8410       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8411   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8412     return;
8413 
8414   llvm::APSInt index;
8415   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8416     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8417     if (index.isNonNegative() &&
8418         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8419                               index.isUnsigned()))
8420       return;
8421   }
8422 
8423   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8424   Self.Diag(OpLoc, diag::warn_string_plus_int)
8425       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8426 
8427   // Only print a fixit for "str" + int, not for int + "str".
8428   if (IndexExpr == RHSExpr) {
8429     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8430     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8431         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8432         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8433         << FixItHint::CreateInsertion(EndLoc, "]");
8434   } else
8435     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8436 }
8437 
8438 /// \brief Emit a warning when adding a char literal to a string.
8439 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8440                                    Expr *LHSExpr, Expr *RHSExpr) {
8441   const Expr *StringRefExpr = LHSExpr;
8442   const CharacterLiteral *CharExpr =
8443       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8444 
8445   if (!CharExpr) {
8446     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8447     StringRefExpr = RHSExpr;
8448   }
8449 
8450   if (!CharExpr || !StringRefExpr)
8451     return;
8452 
8453   const QualType StringType = StringRefExpr->getType();
8454 
8455   // Return if not a PointerType.
8456   if (!StringType->isAnyPointerType())
8457     return;
8458 
8459   // Return if not a CharacterType.
8460   if (!StringType->getPointeeType()->isAnyCharacterType())
8461     return;
8462 
8463   ASTContext &Ctx = Self.getASTContext();
8464   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8465 
8466   const QualType CharType = CharExpr->getType();
8467   if (!CharType->isAnyCharacterType() &&
8468       CharType->isIntegerType() &&
8469       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8470     Self.Diag(OpLoc, diag::warn_string_plus_char)
8471         << DiagRange << Ctx.CharTy;
8472   } else {
8473     Self.Diag(OpLoc, diag::warn_string_plus_char)
8474         << DiagRange << CharExpr->getType();
8475   }
8476 
8477   // Only print a fixit for str + char, not for char + str.
8478   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8479     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8480     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8481         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8482         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8483         << FixItHint::CreateInsertion(EndLoc, "]");
8484   } else {
8485     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8486   }
8487 }
8488 
8489 /// \brief Emit error when two pointers are incompatible.
8490 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8491                                            Expr *LHSExpr, Expr *RHSExpr) {
8492   assert(LHSExpr->getType()->isAnyPointerType());
8493   assert(RHSExpr->getType()->isAnyPointerType());
8494   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8495     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8496     << RHSExpr->getSourceRange();
8497 }
8498 
8499 // C99 6.5.6
8500 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8501                                      SourceLocation Loc, BinaryOperatorKind Opc,
8502                                      QualType* CompLHSTy) {
8503   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8504 
8505   if (LHS.get()->getType()->isVectorType() ||
8506       RHS.get()->getType()->isVectorType()) {
8507     QualType compType = CheckVectorOperands(
8508         LHS, RHS, Loc, CompLHSTy,
8509         /*AllowBothBool*/getLangOpts().AltiVec,
8510         /*AllowBoolConversions*/getLangOpts().ZVector);
8511     if (CompLHSTy) *CompLHSTy = compType;
8512     return compType;
8513   }
8514 
8515   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8516   if (LHS.isInvalid() || RHS.isInvalid())
8517     return QualType();
8518 
8519   // Diagnose "string literal" '+' int and string '+' "char literal".
8520   if (Opc == BO_Add) {
8521     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8522     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8523   }
8524 
8525   // handle the common case first (both operands are arithmetic).
8526   if (!compType.isNull() && compType->isArithmeticType()) {
8527     if (CompLHSTy) *CompLHSTy = compType;
8528     return compType;
8529   }
8530 
8531   // Type-checking.  Ultimately the pointer's going to be in PExp;
8532   // note that we bias towards the LHS being the pointer.
8533   Expr *PExp = LHS.get(), *IExp = RHS.get();
8534 
8535   bool isObjCPointer;
8536   if (PExp->getType()->isPointerType()) {
8537     isObjCPointer = false;
8538   } else if (PExp->getType()->isObjCObjectPointerType()) {
8539     isObjCPointer = true;
8540   } else {
8541     std::swap(PExp, IExp);
8542     if (PExp->getType()->isPointerType()) {
8543       isObjCPointer = false;
8544     } else if (PExp->getType()->isObjCObjectPointerType()) {
8545       isObjCPointer = true;
8546     } else {
8547       return InvalidOperands(Loc, LHS, RHS);
8548     }
8549   }
8550   assert(PExp->getType()->isAnyPointerType());
8551 
8552   if (!IExp->getType()->isIntegerType())
8553     return InvalidOperands(Loc, LHS, RHS);
8554 
8555   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8556     return QualType();
8557 
8558   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8559     return QualType();
8560 
8561   // Check array bounds for pointer arithemtic
8562   CheckArrayAccess(PExp, IExp);
8563 
8564   if (CompLHSTy) {
8565     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8566     if (LHSTy.isNull()) {
8567       LHSTy = LHS.get()->getType();
8568       if (LHSTy->isPromotableIntegerType())
8569         LHSTy = Context.getPromotedIntegerType(LHSTy);
8570     }
8571     *CompLHSTy = LHSTy;
8572   }
8573 
8574   return PExp->getType();
8575 }
8576 
8577 // C99 6.5.6
8578 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8579                                         SourceLocation Loc,
8580                                         QualType* CompLHSTy) {
8581   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8582 
8583   if (LHS.get()->getType()->isVectorType() ||
8584       RHS.get()->getType()->isVectorType()) {
8585     QualType compType = CheckVectorOperands(
8586         LHS, RHS, Loc, CompLHSTy,
8587         /*AllowBothBool*/getLangOpts().AltiVec,
8588         /*AllowBoolConversions*/getLangOpts().ZVector);
8589     if (CompLHSTy) *CompLHSTy = compType;
8590     return compType;
8591   }
8592 
8593   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8594   if (LHS.isInvalid() || RHS.isInvalid())
8595     return QualType();
8596 
8597   // Enforce type constraints: C99 6.5.6p3.
8598 
8599   // Handle the common case first (both operands are arithmetic).
8600   if (!compType.isNull() && compType->isArithmeticType()) {
8601     if (CompLHSTy) *CompLHSTy = compType;
8602     return compType;
8603   }
8604 
8605   // Either ptr - int   or   ptr - ptr.
8606   if (LHS.get()->getType()->isAnyPointerType()) {
8607     QualType lpointee = LHS.get()->getType()->getPointeeType();
8608 
8609     // Diagnose bad cases where we step over interface counts.
8610     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8611         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8612       return QualType();
8613 
8614     // The result type of a pointer-int computation is the pointer type.
8615     if (RHS.get()->getType()->isIntegerType()) {
8616       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8617         return QualType();
8618 
8619       // Check array bounds for pointer arithemtic
8620       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8621                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8622 
8623       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8624       return LHS.get()->getType();
8625     }
8626 
8627     // Handle pointer-pointer subtractions.
8628     if (const PointerType *RHSPTy
8629           = RHS.get()->getType()->getAs<PointerType>()) {
8630       QualType rpointee = RHSPTy->getPointeeType();
8631 
8632       if (getLangOpts().CPlusPlus) {
8633         // Pointee types must be the same: C++ [expr.add]
8634         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8635           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8636         }
8637       } else {
8638         // Pointee types must be compatible C99 6.5.6p3
8639         if (!Context.typesAreCompatible(
8640                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8641                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8642           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8643           return QualType();
8644         }
8645       }
8646 
8647       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8648                                                LHS.get(), RHS.get()))
8649         return QualType();
8650 
8651       // The pointee type may have zero size.  As an extension, a structure or
8652       // union may have zero size or an array may have zero length.  In this
8653       // case subtraction does not make sense.
8654       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8655         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8656         if (ElementSize.isZero()) {
8657           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8658             << rpointee.getUnqualifiedType()
8659             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8660         }
8661       }
8662 
8663       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8664       return Context.getPointerDiffType();
8665     }
8666   }
8667 
8668   return InvalidOperands(Loc, LHS, RHS);
8669 }
8670 
8671 static bool isScopedEnumerationType(QualType T) {
8672   if (const EnumType *ET = T->getAs<EnumType>())
8673     return ET->getDecl()->isScoped();
8674   return false;
8675 }
8676 
8677 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8678                                    SourceLocation Loc, BinaryOperatorKind Opc,
8679                                    QualType LHSType) {
8680   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8681   // so skip remaining warnings as we don't want to modify values within Sema.
8682   if (S.getLangOpts().OpenCL)
8683     return;
8684 
8685   llvm::APSInt Right;
8686   // Check right/shifter operand
8687   if (RHS.get()->isValueDependent() ||
8688       !RHS.get()->EvaluateAsInt(Right, S.Context))
8689     return;
8690 
8691   if (Right.isNegative()) {
8692     S.DiagRuntimeBehavior(Loc, RHS.get(),
8693                           S.PDiag(diag::warn_shift_negative)
8694                             << RHS.get()->getSourceRange());
8695     return;
8696   }
8697   llvm::APInt LeftBits(Right.getBitWidth(),
8698                        S.Context.getTypeSize(LHS.get()->getType()));
8699   if (Right.uge(LeftBits)) {
8700     S.DiagRuntimeBehavior(Loc, RHS.get(),
8701                           S.PDiag(diag::warn_shift_gt_typewidth)
8702                             << RHS.get()->getSourceRange());
8703     return;
8704   }
8705   if (Opc != BO_Shl)
8706     return;
8707 
8708   // When left shifting an ICE which is signed, we can check for overflow which
8709   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8710   // integers have defined behavior modulo one more than the maximum value
8711   // representable in the result type, so never warn for those.
8712   llvm::APSInt Left;
8713   if (LHS.get()->isValueDependent() ||
8714       LHSType->hasUnsignedIntegerRepresentation() ||
8715       !LHS.get()->EvaluateAsInt(Left, S.Context))
8716     return;
8717 
8718   // If LHS does not have a signed type and non-negative value
8719   // then, the behavior is undefined. Warn about it.
8720   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8721     S.DiagRuntimeBehavior(Loc, LHS.get(),
8722                           S.PDiag(diag::warn_shift_lhs_negative)
8723                             << LHS.get()->getSourceRange());
8724     return;
8725   }
8726 
8727   llvm::APInt ResultBits =
8728       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8729   if (LeftBits.uge(ResultBits))
8730     return;
8731   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8732   Result = Result.shl(Right);
8733 
8734   // Print the bit representation of the signed integer as an unsigned
8735   // hexadecimal number.
8736   SmallString<40> HexResult;
8737   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8738 
8739   // If we are only missing a sign bit, this is less likely to result in actual
8740   // bugs -- if the result is cast back to an unsigned type, it will have the
8741   // expected value. Thus we place this behind a different warning that can be
8742   // turned off separately if needed.
8743   if (LeftBits == ResultBits - 1) {
8744     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8745         << HexResult << LHSType
8746         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8747     return;
8748   }
8749 
8750   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8751     << HexResult.str() << Result.getMinSignedBits() << LHSType
8752     << Left.getBitWidth() << LHS.get()->getSourceRange()
8753     << RHS.get()->getSourceRange();
8754 }
8755 
8756 /// \brief Return the resulting type when a vector is shifted
8757 ///        by a scalar or vector shift amount.
8758 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8759                                  SourceLocation Loc, bool IsCompAssign) {
8760   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8761   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8762       !LHS.get()->getType()->isVectorType()) {
8763     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8764       << RHS.get()->getType() << LHS.get()->getType()
8765       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8766     return QualType();
8767   }
8768 
8769   if (!IsCompAssign) {
8770     LHS = S.UsualUnaryConversions(LHS.get());
8771     if (LHS.isInvalid()) return QualType();
8772   }
8773 
8774   RHS = S.UsualUnaryConversions(RHS.get());
8775   if (RHS.isInvalid()) return QualType();
8776 
8777   QualType LHSType = LHS.get()->getType();
8778   // Note that LHS might be a scalar because the routine calls not only in
8779   // OpenCL case.
8780   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8781   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8782 
8783   // Note that RHS might not be a vector.
8784   QualType RHSType = RHS.get()->getType();
8785   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8786   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8787 
8788   // The operands need to be integers.
8789   if (!LHSEleType->isIntegerType()) {
8790     S.Diag(Loc, diag::err_typecheck_expect_int)
8791       << LHS.get()->getType() << LHS.get()->getSourceRange();
8792     return QualType();
8793   }
8794 
8795   if (!RHSEleType->isIntegerType()) {
8796     S.Diag(Loc, diag::err_typecheck_expect_int)
8797       << RHS.get()->getType() << RHS.get()->getSourceRange();
8798     return QualType();
8799   }
8800 
8801   if (!LHSVecTy) {
8802     assert(RHSVecTy);
8803     if (IsCompAssign)
8804       return RHSType;
8805     if (LHSEleType != RHSEleType) {
8806       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8807       LHSEleType = RHSEleType;
8808     }
8809     QualType VecTy =
8810         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8811     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8812     LHSType = VecTy;
8813   } else if (RHSVecTy) {
8814     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8815     // are applied component-wise. So if RHS is a vector, then ensure
8816     // that the number of elements is the same as LHS...
8817     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8818       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8819         << LHS.get()->getType() << RHS.get()->getType()
8820         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8821       return QualType();
8822     }
8823     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8824       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8825       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8826       if (LHSBT != RHSBT &&
8827           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8828         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8829             << LHS.get()->getType() << RHS.get()->getType()
8830             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8831       }
8832     }
8833   } else {
8834     // ...else expand RHS to match the number of elements in LHS.
8835     QualType VecTy =
8836       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8837     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8838   }
8839 
8840   return LHSType;
8841 }
8842 
8843 // C99 6.5.7
8844 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8845                                   SourceLocation Loc, BinaryOperatorKind Opc,
8846                                   bool IsCompAssign) {
8847   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8848 
8849   // Vector shifts promote their scalar inputs to vector type.
8850   if (LHS.get()->getType()->isVectorType() ||
8851       RHS.get()->getType()->isVectorType()) {
8852     if (LangOpts.ZVector) {
8853       // The shift operators for the z vector extensions work basically
8854       // like general shifts, except that neither the LHS nor the RHS is
8855       // allowed to be a "vector bool".
8856       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8857         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8858           return InvalidOperands(Loc, LHS, RHS);
8859       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8860         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8861           return InvalidOperands(Loc, LHS, RHS);
8862     }
8863     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8864   }
8865 
8866   // Shifts don't perform usual arithmetic conversions, they just do integer
8867   // promotions on each operand. C99 6.5.7p3
8868 
8869   // For the LHS, do usual unary conversions, but then reset them away
8870   // if this is a compound assignment.
8871   ExprResult OldLHS = LHS;
8872   LHS = UsualUnaryConversions(LHS.get());
8873   if (LHS.isInvalid())
8874     return QualType();
8875   QualType LHSType = LHS.get()->getType();
8876   if (IsCompAssign) LHS = OldLHS;
8877 
8878   // The RHS is simpler.
8879   RHS = UsualUnaryConversions(RHS.get());
8880   if (RHS.isInvalid())
8881     return QualType();
8882   QualType RHSType = RHS.get()->getType();
8883 
8884   // C99 6.5.7p2: Each of the operands shall have integer type.
8885   if (!LHSType->hasIntegerRepresentation() ||
8886       !RHSType->hasIntegerRepresentation())
8887     return InvalidOperands(Loc, LHS, RHS);
8888 
8889   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8890   // hasIntegerRepresentation() above instead of this.
8891   if (isScopedEnumerationType(LHSType) ||
8892       isScopedEnumerationType(RHSType)) {
8893     return InvalidOperands(Loc, LHS, RHS);
8894   }
8895   // Sanity-check shift operands
8896   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8897 
8898   // "The type of the result is that of the promoted left operand."
8899   return LHSType;
8900 }
8901 
8902 static bool IsWithinTemplateSpecialization(Decl *D) {
8903   if (DeclContext *DC = D->getDeclContext()) {
8904     if (isa<ClassTemplateSpecializationDecl>(DC))
8905       return true;
8906     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8907       return FD->isFunctionTemplateSpecialization();
8908   }
8909   return false;
8910 }
8911 
8912 /// If two different enums are compared, raise a warning.
8913 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8914                                 Expr *RHS) {
8915   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8916   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8917 
8918   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8919   if (!LHSEnumType)
8920     return;
8921   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8922   if (!RHSEnumType)
8923     return;
8924 
8925   // Ignore anonymous enums.
8926   if (!LHSEnumType->getDecl()->getIdentifier())
8927     return;
8928   if (!RHSEnumType->getDecl()->getIdentifier())
8929     return;
8930 
8931   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8932     return;
8933 
8934   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8935       << LHSStrippedType << RHSStrippedType
8936       << LHS->getSourceRange() << RHS->getSourceRange();
8937 }
8938 
8939 /// \brief Diagnose bad pointer comparisons.
8940 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8941                                               ExprResult &LHS, ExprResult &RHS,
8942                                               bool IsError) {
8943   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8944                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8945     << LHS.get()->getType() << RHS.get()->getType()
8946     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8947 }
8948 
8949 /// \brief Returns false if the pointers are converted to a composite type,
8950 /// true otherwise.
8951 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8952                                            ExprResult &LHS, ExprResult &RHS) {
8953   // C++ [expr.rel]p2:
8954   //   [...] Pointer conversions (4.10) and qualification
8955   //   conversions (4.4) are performed on pointer operands (or on
8956   //   a pointer operand and a null pointer constant) to bring
8957   //   them to their composite pointer type. [...]
8958   //
8959   // C++ [expr.eq]p1 uses the same notion for (in)equality
8960   // comparisons of pointers.
8961 
8962   QualType LHSType = LHS.get()->getType();
8963   QualType RHSType = RHS.get()->getType();
8964   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8965          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8966 
8967   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8968   if (T.isNull()) {
8969     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8970         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8971       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8972     else
8973       S.InvalidOperands(Loc, LHS, RHS);
8974     return true;
8975   }
8976 
8977   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8978   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8979   return false;
8980 }
8981 
8982 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8983                                                     ExprResult &LHS,
8984                                                     ExprResult &RHS,
8985                                                     bool IsError) {
8986   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8987                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8988     << LHS.get()->getType() << RHS.get()->getType()
8989     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8990 }
8991 
8992 static bool isObjCObjectLiteral(ExprResult &E) {
8993   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8994   case Stmt::ObjCArrayLiteralClass:
8995   case Stmt::ObjCDictionaryLiteralClass:
8996   case Stmt::ObjCStringLiteralClass:
8997   case Stmt::ObjCBoxedExprClass:
8998     return true;
8999   default:
9000     // Note that ObjCBoolLiteral is NOT an object literal!
9001     return false;
9002   }
9003 }
9004 
9005 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9006   const ObjCObjectPointerType *Type =
9007     LHS->getType()->getAs<ObjCObjectPointerType>();
9008 
9009   // If this is not actually an Objective-C object, bail out.
9010   if (!Type)
9011     return false;
9012 
9013   // Get the LHS object's interface type.
9014   QualType InterfaceType = Type->getPointeeType();
9015 
9016   // If the RHS isn't an Objective-C object, bail out.
9017   if (!RHS->getType()->isObjCObjectPointerType())
9018     return false;
9019 
9020   // Try to find the -isEqual: method.
9021   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9022   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9023                                                       InterfaceType,
9024                                                       /*instance=*/true);
9025   if (!Method) {
9026     if (Type->isObjCIdType()) {
9027       // For 'id', just check the global pool.
9028       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9029                                                   /*receiverId=*/true);
9030     } else {
9031       // Check protocols.
9032       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9033                                              /*instance=*/true);
9034     }
9035   }
9036 
9037   if (!Method)
9038     return false;
9039 
9040   QualType T = Method->parameters()[0]->getType();
9041   if (!T->isObjCObjectPointerType())
9042     return false;
9043 
9044   QualType R = Method->getReturnType();
9045   if (!R->isScalarType())
9046     return false;
9047 
9048   return true;
9049 }
9050 
9051 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9052   FromE = FromE->IgnoreParenImpCasts();
9053   switch (FromE->getStmtClass()) {
9054     default:
9055       break;
9056     case Stmt::ObjCStringLiteralClass:
9057       // "string literal"
9058       return LK_String;
9059     case Stmt::ObjCArrayLiteralClass:
9060       // "array literal"
9061       return LK_Array;
9062     case Stmt::ObjCDictionaryLiteralClass:
9063       // "dictionary literal"
9064       return LK_Dictionary;
9065     case Stmt::BlockExprClass:
9066       return LK_Block;
9067     case Stmt::ObjCBoxedExprClass: {
9068       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9069       switch (Inner->getStmtClass()) {
9070         case Stmt::IntegerLiteralClass:
9071         case Stmt::FloatingLiteralClass:
9072         case Stmt::CharacterLiteralClass:
9073         case Stmt::ObjCBoolLiteralExprClass:
9074         case Stmt::CXXBoolLiteralExprClass:
9075           // "numeric literal"
9076           return LK_Numeric;
9077         case Stmt::ImplicitCastExprClass: {
9078           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9079           // Boolean literals can be represented by implicit casts.
9080           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9081             return LK_Numeric;
9082           break;
9083         }
9084         default:
9085           break;
9086       }
9087       return LK_Boxed;
9088     }
9089   }
9090   return LK_None;
9091 }
9092 
9093 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9094                                           ExprResult &LHS, ExprResult &RHS,
9095                                           BinaryOperator::Opcode Opc){
9096   Expr *Literal;
9097   Expr *Other;
9098   if (isObjCObjectLiteral(LHS)) {
9099     Literal = LHS.get();
9100     Other = RHS.get();
9101   } else {
9102     Literal = RHS.get();
9103     Other = LHS.get();
9104   }
9105 
9106   // Don't warn on comparisons against nil.
9107   Other = Other->IgnoreParenCasts();
9108   if (Other->isNullPointerConstant(S.getASTContext(),
9109                                    Expr::NPC_ValueDependentIsNotNull))
9110     return;
9111 
9112   // This should be kept in sync with warn_objc_literal_comparison.
9113   // LK_String should always be after the other literals, since it has its own
9114   // warning flag.
9115   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9116   assert(LiteralKind != Sema::LK_Block);
9117   if (LiteralKind == Sema::LK_None) {
9118     llvm_unreachable("Unknown Objective-C object literal kind");
9119   }
9120 
9121   if (LiteralKind == Sema::LK_String)
9122     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9123       << Literal->getSourceRange();
9124   else
9125     S.Diag(Loc, diag::warn_objc_literal_comparison)
9126       << LiteralKind << Literal->getSourceRange();
9127 
9128   if (BinaryOperator::isEqualityOp(Opc) &&
9129       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9130     SourceLocation Start = LHS.get()->getLocStart();
9131     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9132     CharSourceRange OpRange =
9133       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9134 
9135     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9136       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9137       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9138       << FixItHint::CreateInsertion(End, "]");
9139   }
9140 }
9141 
9142 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9143 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9144                                            ExprResult &RHS, SourceLocation Loc,
9145                                            BinaryOperatorKind Opc) {
9146   // Check that left hand side is !something.
9147   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9148   if (!UO || UO->getOpcode() != UO_LNot) return;
9149 
9150   // Only check if the right hand side is non-bool arithmetic type.
9151   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9152 
9153   // Make sure that the something in !something is not bool.
9154   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9155   if (SubExpr->isKnownToHaveBooleanValue()) return;
9156 
9157   // Emit warning.
9158   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9159   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9160       << Loc << IsBitwiseOp;
9161 
9162   // First note suggest !(x < y)
9163   SourceLocation FirstOpen = SubExpr->getLocStart();
9164   SourceLocation FirstClose = RHS.get()->getLocEnd();
9165   FirstClose = S.getLocForEndOfToken(FirstClose);
9166   if (FirstClose.isInvalid())
9167     FirstOpen = SourceLocation();
9168   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9169       << IsBitwiseOp
9170       << FixItHint::CreateInsertion(FirstOpen, "(")
9171       << FixItHint::CreateInsertion(FirstClose, ")");
9172 
9173   // Second note suggests (!x) < y
9174   SourceLocation SecondOpen = LHS.get()->getLocStart();
9175   SourceLocation SecondClose = LHS.get()->getLocEnd();
9176   SecondClose = S.getLocForEndOfToken(SecondClose);
9177   if (SecondClose.isInvalid())
9178     SecondOpen = SourceLocation();
9179   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9180       << FixItHint::CreateInsertion(SecondOpen, "(")
9181       << FixItHint::CreateInsertion(SecondClose, ")");
9182 }
9183 
9184 // Get the decl for a simple expression: a reference to a variable,
9185 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9186 static ValueDecl *getCompareDecl(Expr *E) {
9187   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9188     return DR->getDecl();
9189   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9190     if (Ivar->isFreeIvar())
9191       return Ivar->getDecl();
9192   }
9193   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9194     if (Mem->isImplicitAccess())
9195       return Mem->getMemberDecl();
9196   }
9197   return nullptr;
9198 }
9199 
9200 // C99 6.5.8, C++ [expr.rel]
9201 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9202                                     SourceLocation Loc, BinaryOperatorKind Opc,
9203                                     bool IsRelational) {
9204   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9205 
9206   // Handle vector comparisons separately.
9207   if (LHS.get()->getType()->isVectorType() ||
9208       RHS.get()->getType()->isVectorType())
9209     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9210 
9211   QualType LHSType = LHS.get()->getType();
9212   QualType RHSType = RHS.get()->getType();
9213 
9214   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9215   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9216 
9217   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9218   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9219 
9220   if (!LHSType->hasFloatingRepresentation() &&
9221       !(LHSType->isBlockPointerType() && IsRelational) &&
9222       !LHS.get()->getLocStart().isMacroID() &&
9223       !RHS.get()->getLocStart().isMacroID() &&
9224       ActiveTemplateInstantiations.empty()) {
9225     // For non-floating point types, check for self-comparisons of the form
9226     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9227     // often indicate logic errors in the program.
9228     //
9229     // NOTE: Don't warn about comparison expressions resulting from macro
9230     // expansion. Also don't warn about comparisons which are only self
9231     // comparisons within a template specialization. The warnings should catch
9232     // obvious cases in the definition of the template anyways. The idea is to
9233     // warn when the typed comparison operator will always evaluate to the same
9234     // result.
9235     ValueDecl *DL = getCompareDecl(LHSStripped);
9236     ValueDecl *DR = getCompareDecl(RHSStripped);
9237     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9238       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9239                           << 0 // self-
9240                           << (Opc == BO_EQ
9241                               || Opc == BO_LE
9242                               || Opc == BO_GE));
9243     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9244                !DL->getType()->isReferenceType() &&
9245                !DR->getType()->isReferenceType()) {
9246         // what is it always going to eval to?
9247         char always_evals_to;
9248         switch(Opc) {
9249         case BO_EQ: // e.g. array1 == array2
9250           always_evals_to = 0; // false
9251           break;
9252         case BO_NE: // e.g. array1 != array2
9253           always_evals_to = 1; // true
9254           break;
9255         default:
9256           // best we can say is 'a constant'
9257           always_evals_to = 2; // e.g. array1 <= array2
9258           break;
9259         }
9260         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9261                             << 1 // array
9262                             << always_evals_to);
9263     }
9264 
9265     if (isa<CastExpr>(LHSStripped))
9266       LHSStripped = LHSStripped->IgnoreParenCasts();
9267     if (isa<CastExpr>(RHSStripped))
9268       RHSStripped = RHSStripped->IgnoreParenCasts();
9269 
9270     // Warn about comparisons against a string constant (unless the other
9271     // operand is null), the user probably wants strcmp.
9272     Expr *literalString = nullptr;
9273     Expr *literalStringStripped = nullptr;
9274     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9275         !RHSStripped->isNullPointerConstant(Context,
9276                                             Expr::NPC_ValueDependentIsNull)) {
9277       literalString = LHS.get();
9278       literalStringStripped = LHSStripped;
9279     } else if ((isa<StringLiteral>(RHSStripped) ||
9280                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9281                !LHSStripped->isNullPointerConstant(Context,
9282                                             Expr::NPC_ValueDependentIsNull)) {
9283       literalString = RHS.get();
9284       literalStringStripped = RHSStripped;
9285     }
9286 
9287     if (literalString) {
9288       DiagRuntimeBehavior(Loc, nullptr,
9289         PDiag(diag::warn_stringcompare)
9290           << isa<ObjCEncodeExpr>(literalStringStripped)
9291           << literalString->getSourceRange());
9292     }
9293   }
9294 
9295   // C99 6.5.8p3 / C99 6.5.9p4
9296   UsualArithmeticConversions(LHS, RHS);
9297   if (LHS.isInvalid() || RHS.isInvalid())
9298     return QualType();
9299 
9300   LHSType = LHS.get()->getType();
9301   RHSType = RHS.get()->getType();
9302 
9303   // The result of comparisons is 'bool' in C++, 'int' in C.
9304   QualType ResultTy = Context.getLogicalOperationType();
9305 
9306   if (IsRelational) {
9307     if (LHSType->isRealType() && RHSType->isRealType())
9308       return ResultTy;
9309   } else {
9310     // Check for comparisons of floating point operands using != and ==.
9311     if (LHSType->hasFloatingRepresentation())
9312       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9313 
9314     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9315       return ResultTy;
9316   }
9317 
9318   const Expr::NullPointerConstantKind LHSNullKind =
9319       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9320   const Expr::NullPointerConstantKind RHSNullKind =
9321       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9322   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9323   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9324 
9325   if (!IsRelational && LHSIsNull != RHSIsNull) {
9326     bool IsEquality = Opc == BO_EQ;
9327     if (RHSIsNull)
9328       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9329                                    RHS.get()->getSourceRange());
9330     else
9331       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9332                                    LHS.get()->getSourceRange());
9333   }
9334 
9335   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9336       (RHSType->isIntegerType() && !RHSIsNull)) {
9337     // Skip normal pointer conversion checks in this case; we have better
9338     // diagnostics for this below.
9339   } else if (getLangOpts().CPlusPlus) {
9340     // Equality comparison of a function pointer to a void pointer is invalid,
9341     // but we allow it as an extension.
9342     // FIXME: If we really want to allow this, should it be part of composite
9343     // pointer type computation so it works in conditionals too?
9344     if (!IsRelational &&
9345         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9346          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9347       // This is a gcc extension compatibility comparison.
9348       // In a SFINAE context, we treat this as a hard error to maintain
9349       // conformance with the C++ standard.
9350       diagnoseFunctionPointerToVoidComparison(
9351           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9352 
9353       if (isSFINAEContext())
9354         return QualType();
9355 
9356       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9357       return ResultTy;
9358     }
9359 
9360     // C++ [expr.eq]p2:
9361     //   If at least one operand is a pointer [...] bring them to their
9362     //   composite pointer type.
9363     // C++ [expr.rel]p2:
9364     //   If both operands are pointers, [...] bring them to their composite
9365     //   pointer type.
9366     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9367         (IsRelational ? 2 : 1)) {
9368       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9369         return QualType();
9370       else
9371         return ResultTy;
9372     }
9373   } else if (LHSType->isPointerType() &&
9374              RHSType->isPointerType()) { // C99 6.5.8p2
9375     // All of the following pointer-related warnings are GCC extensions, except
9376     // when handling null pointer constants.
9377     QualType LCanPointeeTy =
9378       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9379     QualType RCanPointeeTy =
9380       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9381 
9382     // C99 6.5.9p2 and C99 6.5.8p2
9383     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9384                                    RCanPointeeTy.getUnqualifiedType())) {
9385       // Valid unless a relational comparison of function pointers
9386       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9387         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9388           << LHSType << RHSType << LHS.get()->getSourceRange()
9389           << RHS.get()->getSourceRange();
9390       }
9391     } else if (!IsRelational &&
9392                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9393       // Valid unless comparison between non-null pointer and function pointer
9394       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9395           && !LHSIsNull && !RHSIsNull)
9396         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9397                                                 /*isError*/false);
9398     } else {
9399       // Invalid
9400       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9401     }
9402     if (LCanPointeeTy != RCanPointeeTy) {
9403       // Treat NULL constant as a special case in OpenCL.
9404       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9405         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9406         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9407           Diag(Loc,
9408                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9409               << LHSType << RHSType << 0 /* comparison */
9410               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9411         }
9412       }
9413       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9414       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9415       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9416                                                : CK_BitCast;
9417       if (LHSIsNull && !RHSIsNull)
9418         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9419       else
9420         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9421     }
9422     return ResultTy;
9423   }
9424 
9425   if (getLangOpts().CPlusPlus) {
9426     // C++ [expr.eq]p4:
9427     //   Two operands of type std::nullptr_t or one operand of type
9428     //   std::nullptr_t and the other a null pointer constant compare equal.
9429     if (!IsRelational && LHSIsNull && RHSIsNull) {
9430       if (LHSType->isNullPtrType()) {
9431         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9432         return ResultTy;
9433       }
9434       if (RHSType->isNullPtrType()) {
9435         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9436         return ResultTy;
9437       }
9438     }
9439 
9440     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9441     // These aren't covered by the composite pointer type rules.
9442     if (!IsRelational && RHSType->isNullPtrType() &&
9443         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9444       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9445       return ResultTy;
9446     }
9447     if (!IsRelational && LHSType->isNullPtrType() &&
9448         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9449       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9450       return ResultTy;
9451     }
9452 
9453     if (IsRelational &&
9454         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9455          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9456       // HACK: Relational comparison of nullptr_t against a pointer type is
9457       // invalid per DR583, but we allow it within std::less<> and friends,
9458       // since otherwise common uses of it break.
9459       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9460       // friends to have std::nullptr_t overload candidates.
9461       DeclContext *DC = CurContext;
9462       if (isa<FunctionDecl>(DC))
9463         DC = DC->getParent();
9464       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9465         if (CTSD->isInStdNamespace() &&
9466             llvm::StringSwitch<bool>(CTSD->getName())
9467                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9468                 .Default(false)) {
9469           if (RHSType->isNullPtrType())
9470             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9471           else
9472             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9473           return ResultTy;
9474         }
9475       }
9476     }
9477 
9478     // C++ [expr.eq]p2:
9479     //   If at least one operand is a pointer to member, [...] bring them to
9480     //   their composite pointer type.
9481     if (!IsRelational &&
9482         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9483       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9484         return QualType();
9485       else
9486         return ResultTy;
9487     }
9488 
9489     // Handle scoped enumeration types specifically, since they don't promote
9490     // to integers.
9491     if (LHS.get()->getType()->isEnumeralType() &&
9492         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9493                                        RHS.get()->getType()))
9494       return ResultTy;
9495   }
9496 
9497   // Handle block pointer types.
9498   if (!IsRelational && LHSType->isBlockPointerType() &&
9499       RHSType->isBlockPointerType()) {
9500     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9501     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9502 
9503     if (!LHSIsNull && !RHSIsNull &&
9504         !Context.typesAreCompatible(lpointee, rpointee)) {
9505       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9506         << LHSType << RHSType << LHS.get()->getSourceRange()
9507         << RHS.get()->getSourceRange();
9508     }
9509     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9510     return ResultTy;
9511   }
9512 
9513   // Allow block pointers to be compared with null pointer constants.
9514   if (!IsRelational
9515       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9516           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9517     if (!LHSIsNull && !RHSIsNull) {
9518       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9519              ->getPointeeType()->isVoidType())
9520             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9521                 ->getPointeeType()->isVoidType())))
9522         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9523           << LHSType << RHSType << LHS.get()->getSourceRange()
9524           << RHS.get()->getSourceRange();
9525     }
9526     if (LHSIsNull && !RHSIsNull)
9527       LHS = ImpCastExprToType(LHS.get(), RHSType,
9528                               RHSType->isPointerType() ? CK_BitCast
9529                                 : CK_AnyPointerToBlockPointerCast);
9530     else
9531       RHS = ImpCastExprToType(RHS.get(), LHSType,
9532                               LHSType->isPointerType() ? CK_BitCast
9533                                 : CK_AnyPointerToBlockPointerCast);
9534     return ResultTy;
9535   }
9536 
9537   if (LHSType->isObjCObjectPointerType() ||
9538       RHSType->isObjCObjectPointerType()) {
9539     const PointerType *LPT = LHSType->getAs<PointerType>();
9540     const PointerType *RPT = RHSType->getAs<PointerType>();
9541     if (LPT || RPT) {
9542       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9543       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9544 
9545       if (!LPtrToVoid && !RPtrToVoid &&
9546           !Context.typesAreCompatible(LHSType, RHSType)) {
9547         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9548                                           /*isError*/false);
9549       }
9550       if (LHSIsNull && !RHSIsNull) {
9551         Expr *E = LHS.get();
9552         if (getLangOpts().ObjCAutoRefCount)
9553           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9554         LHS = ImpCastExprToType(E, RHSType,
9555                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9556       }
9557       else {
9558         Expr *E = RHS.get();
9559         if (getLangOpts().ObjCAutoRefCount)
9560           CheckObjCARCConversion(SourceRange(), LHSType, E,
9561                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9562                                  /*DiagnoseCFAudited=*/false, Opc);
9563         RHS = ImpCastExprToType(E, LHSType,
9564                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9565       }
9566       return ResultTy;
9567     }
9568     if (LHSType->isObjCObjectPointerType() &&
9569         RHSType->isObjCObjectPointerType()) {
9570       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9571         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9572                                           /*isError*/false);
9573       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9574         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9575 
9576       if (LHSIsNull && !RHSIsNull)
9577         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9578       else
9579         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9580       return ResultTy;
9581     }
9582   }
9583   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9584       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9585     unsigned DiagID = 0;
9586     bool isError = false;
9587     if (LangOpts.DebuggerSupport) {
9588       // Under a debugger, allow the comparison of pointers to integers,
9589       // since users tend to want to compare addresses.
9590     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9591                (RHSIsNull && RHSType->isIntegerType())) {
9592       if (IsRelational) {
9593         isError = getLangOpts().CPlusPlus;
9594         DiagID =
9595           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9596                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9597       }
9598     } else if (getLangOpts().CPlusPlus) {
9599       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9600       isError = true;
9601     } else if (IsRelational)
9602       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9603     else
9604       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9605 
9606     if (DiagID) {
9607       Diag(Loc, DiagID)
9608         << LHSType << RHSType << LHS.get()->getSourceRange()
9609         << RHS.get()->getSourceRange();
9610       if (isError)
9611         return QualType();
9612     }
9613 
9614     if (LHSType->isIntegerType())
9615       LHS = ImpCastExprToType(LHS.get(), RHSType,
9616                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9617     else
9618       RHS = ImpCastExprToType(RHS.get(), LHSType,
9619                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9620     return ResultTy;
9621   }
9622 
9623   // Handle block pointers.
9624   if (!IsRelational && RHSIsNull
9625       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9626     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9627     return ResultTy;
9628   }
9629   if (!IsRelational && LHSIsNull
9630       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9631     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9632     return ResultTy;
9633   }
9634 
9635   return InvalidOperands(Loc, LHS, RHS);
9636 }
9637 
9638 
9639 // Return a signed type that is of identical size and number of elements.
9640 // For floating point vectors, return an integer type of identical size
9641 // and number of elements.
9642 QualType Sema::GetSignedVectorType(QualType V) {
9643   const VectorType *VTy = V->getAs<VectorType>();
9644   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9645   if (TypeSize == Context.getTypeSize(Context.CharTy))
9646     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9647   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9648     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9649   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9650     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9651   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9652     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9653   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9654          "Unhandled vector element size in vector compare");
9655   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9656 }
9657 
9658 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9659 /// operates on extended vector types.  Instead of producing an IntTy result,
9660 /// like a scalar comparison, a vector comparison produces a vector of integer
9661 /// types.
9662 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9663                                           SourceLocation Loc,
9664                                           bool IsRelational) {
9665   // Check to make sure we're operating on vectors of the same type and width,
9666   // Allowing one side to be a scalar of element type.
9667   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9668                               /*AllowBothBool*/true,
9669                               /*AllowBoolConversions*/getLangOpts().ZVector);
9670   if (vType.isNull())
9671     return vType;
9672 
9673   QualType LHSType = LHS.get()->getType();
9674 
9675   // If AltiVec, the comparison results in a numeric type, i.e.
9676   // bool for C++, int for C
9677   if (getLangOpts().AltiVec &&
9678       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9679     return Context.getLogicalOperationType();
9680 
9681   // For non-floating point types, check for self-comparisons of the form
9682   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9683   // often indicate logic errors in the program.
9684   if (!LHSType->hasFloatingRepresentation() &&
9685       ActiveTemplateInstantiations.empty()) {
9686     if (DeclRefExpr* DRL
9687           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9688       if (DeclRefExpr* DRR
9689             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9690         if (DRL->getDecl() == DRR->getDecl())
9691           DiagRuntimeBehavior(Loc, nullptr,
9692                               PDiag(diag::warn_comparison_always)
9693                                 << 0 // self-
9694                                 << 2 // "a constant"
9695                               );
9696   }
9697 
9698   // Check for comparisons of floating point operands using != and ==.
9699   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9700     assert (RHS.get()->getType()->hasFloatingRepresentation());
9701     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9702   }
9703 
9704   // Return a signed type for the vector.
9705   return GetSignedVectorType(vType);
9706 }
9707 
9708 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9709                                           SourceLocation Loc) {
9710   // Ensure that either both operands are of the same vector type, or
9711   // one operand is of a vector type and the other is of its element type.
9712   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9713                                        /*AllowBothBool*/true,
9714                                        /*AllowBoolConversions*/false);
9715   if (vType.isNull())
9716     return InvalidOperands(Loc, LHS, RHS);
9717   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9718       vType->hasFloatingRepresentation())
9719     return InvalidOperands(Loc, LHS, RHS);
9720 
9721   return GetSignedVectorType(LHS.get()->getType());
9722 }
9723 
9724 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9725                                            SourceLocation Loc,
9726                                            BinaryOperatorKind Opc) {
9727   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9728 
9729   bool IsCompAssign =
9730       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9731 
9732   if (LHS.get()->getType()->isVectorType() ||
9733       RHS.get()->getType()->isVectorType()) {
9734     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9735         RHS.get()->getType()->hasIntegerRepresentation())
9736       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9737                         /*AllowBothBool*/true,
9738                         /*AllowBoolConversions*/getLangOpts().ZVector);
9739     return InvalidOperands(Loc, LHS, RHS);
9740   }
9741 
9742   if (Opc == BO_And)
9743     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9744 
9745   ExprResult LHSResult = LHS, RHSResult = RHS;
9746   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9747                                                  IsCompAssign);
9748   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9749     return QualType();
9750   LHS = LHSResult.get();
9751   RHS = RHSResult.get();
9752 
9753   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9754     return compType;
9755   return InvalidOperands(Loc, LHS, RHS);
9756 }
9757 
9758 // C99 6.5.[13,14]
9759 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9760                                            SourceLocation Loc,
9761                                            BinaryOperatorKind Opc) {
9762   // Check vector operands differently.
9763   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9764     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9765 
9766   // Diagnose cases where the user write a logical and/or but probably meant a
9767   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9768   // is a constant.
9769   if (LHS.get()->getType()->isIntegerType() &&
9770       !LHS.get()->getType()->isBooleanType() &&
9771       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9772       // Don't warn in macros or template instantiations.
9773       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9774     // If the RHS can be constant folded, and if it constant folds to something
9775     // that isn't 0 or 1 (which indicate a potential logical operation that
9776     // happened to fold to true/false) then warn.
9777     // Parens on the RHS are ignored.
9778     llvm::APSInt Result;
9779     if (RHS.get()->EvaluateAsInt(Result, Context))
9780       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9781            !RHS.get()->getExprLoc().isMacroID()) ||
9782           (Result != 0 && Result != 1)) {
9783         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9784           << RHS.get()->getSourceRange()
9785           << (Opc == BO_LAnd ? "&&" : "||");
9786         // Suggest replacing the logical operator with the bitwise version
9787         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9788             << (Opc == BO_LAnd ? "&" : "|")
9789             << FixItHint::CreateReplacement(SourceRange(
9790                                                  Loc, getLocForEndOfToken(Loc)),
9791                                             Opc == BO_LAnd ? "&" : "|");
9792         if (Opc == BO_LAnd)
9793           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9794           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9795               << FixItHint::CreateRemoval(
9796                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9797                               RHS.get()->getLocEnd()));
9798       }
9799   }
9800 
9801   if (!Context.getLangOpts().CPlusPlus) {
9802     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9803     // not operate on the built-in scalar and vector float types.
9804     if (Context.getLangOpts().OpenCL &&
9805         Context.getLangOpts().OpenCLVersion < 120) {
9806       if (LHS.get()->getType()->isFloatingType() ||
9807           RHS.get()->getType()->isFloatingType())
9808         return InvalidOperands(Loc, LHS, RHS);
9809     }
9810 
9811     LHS = UsualUnaryConversions(LHS.get());
9812     if (LHS.isInvalid())
9813       return QualType();
9814 
9815     RHS = UsualUnaryConversions(RHS.get());
9816     if (RHS.isInvalid())
9817       return QualType();
9818 
9819     if (!LHS.get()->getType()->isScalarType() ||
9820         !RHS.get()->getType()->isScalarType())
9821       return InvalidOperands(Loc, LHS, RHS);
9822 
9823     return Context.IntTy;
9824   }
9825 
9826   // The following is safe because we only use this method for
9827   // non-overloadable operands.
9828 
9829   // C++ [expr.log.and]p1
9830   // C++ [expr.log.or]p1
9831   // The operands are both contextually converted to type bool.
9832   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9833   if (LHSRes.isInvalid())
9834     return InvalidOperands(Loc, LHS, RHS);
9835   LHS = LHSRes;
9836 
9837   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9838   if (RHSRes.isInvalid())
9839     return InvalidOperands(Loc, LHS, RHS);
9840   RHS = RHSRes;
9841 
9842   // C++ [expr.log.and]p2
9843   // C++ [expr.log.or]p2
9844   // The result is a bool.
9845   return Context.BoolTy;
9846 }
9847 
9848 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9849   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9850   if (!ME) return false;
9851   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9852   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9853       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9854   if (!Base) return false;
9855   return Base->getMethodDecl() != nullptr;
9856 }
9857 
9858 /// Is the given expression (which must be 'const') a reference to a
9859 /// variable which was originally non-const, but which has become
9860 /// 'const' due to being captured within a block?
9861 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9862 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9863   assert(E->isLValue() && E->getType().isConstQualified());
9864   E = E->IgnoreParens();
9865 
9866   // Must be a reference to a declaration from an enclosing scope.
9867   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9868   if (!DRE) return NCCK_None;
9869   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9870 
9871   // The declaration must be a variable which is not declared 'const'.
9872   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9873   if (!var) return NCCK_None;
9874   if (var->getType().isConstQualified()) return NCCK_None;
9875   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9876 
9877   // Decide whether the first capture was for a block or a lambda.
9878   DeclContext *DC = S.CurContext, *Prev = nullptr;
9879   // Decide whether the first capture was for a block or a lambda.
9880   while (DC) {
9881     // For init-capture, it is possible that the variable belongs to the
9882     // template pattern of the current context.
9883     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9884       if (var->isInitCapture() &&
9885           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9886         break;
9887     if (DC == var->getDeclContext())
9888       break;
9889     Prev = DC;
9890     DC = DC->getParent();
9891   }
9892   // Unless we have an init-capture, we've gone one step too far.
9893   if (!var->isInitCapture())
9894     DC = Prev;
9895   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9896 }
9897 
9898 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9899   Ty = Ty.getNonReferenceType();
9900   if (IsDereference && Ty->isPointerType())
9901     Ty = Ty->getPointeeType();
9902   return !Ty.isConstQualified();
9903 }
9904 
9905 /// Emit the "read-only variable not assignable" error and print notes to give
9906 /// more information about why the variable is not assignable, such as pointing
9907 /// to the declaration of a const variable, showing that a method is const, or
9908 /// that the function is returning a const reference.
9909 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9910                                     SourceLocation Loc) {
9911   // Update err_typecheck_assign_const and note_typecheck_assign_const
9912   // when this enum is changed.
9913   enum {
9914     ConstFunction,
9915     ConstVariable,
9916     ConstMember,
9917     ConstMethod,
9918     ConstUnknown,  // Keep as last element
9919   };
9920 
9921   SourceRange ExprRange = E->getSourceRange();
9922 
9923   // Only emit one error on the first const found.  All other consts will emit
9924   // a note to the error.
9925   bool DiagnosticEmitted = false;
9926 
9927   // Track if the current expression is the result of a dereference, and if the
9928   // next checked expression is the result of a dereference.
9929   bool IsDereference = false;
9930   bool NextIsDereference = false;
9931 
9932   // Loop to process MemberExpr chains.
9933   while (true) {
9934     IsDereference = NextIsDereference;
9935 
9936     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9937     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9938       NextIsDereference = ME->isArrow();
9939       const ValueDecl *VD = ME->getMemberDecl();
9940       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9941         // Mutable fields can be modified even if the class is const.
9942         if (Field->isMutable()) {
9943           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9944           break;
9945         }
9946 
9947         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9948           if (!DiagnosticEmitted) {
9949             S.Diag(Loc, diag::err_typecheck_assign_const)
9950                 << ExprRange << ConstMember << false /*static*/ << Field
9951                 << Field->getType();
9952             DiagnosticEmitted = true;
9953           }
9954           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9955               << ConstMember << false /*static*/ << Field << Field->getType()
9956               << Field->getSourceRange();
9957         }
9958         E = ME->getBase();
9959         continue;
9960       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9961         if (VDecl->getType().isConstQualified()) {
9962           if (!DiagnosticEmitted) {
9963             S.Diag(Loc, diag::err_typecheck_assign_const)
9964                 << ExprRange << ConstMember << true /*static*/ << VDecl
9965                 << VDecl->getType();
9966             DiagnosticEmitted = true;
9967           }
9968           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9969               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9970               << VDecl->getSourceRange();
9971         }
9972         // Static fields do not inherit constness from parents.
9973         break;
9974       }
9975       break;
9976     } // End MemberExpr
9977     break;
9978   }
9979 
9980   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9981     // Function calls
9982     const FunctionDecl *FD = CE->getDirectCallee();
9983     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9984       if (!DiagnosticEmitted) {
9985         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9986                                                       << ConstFunction << FD;
9987         DiagnosticEmitted = true;
9988       }
9989       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9990              diag::note_typecheck_assign_const)
9991           << ConstFunction << FD << FD->getReturnType()
9992           << FD->getReturnTypeSourceRange();
9993     }
9994   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9995     // Point to variable declaration.
9996     if (const ValueDecl *VD = DRE->getDecl()) {
9997       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9998         if (!DiagnosticEmitted) {
9999           S.Diag(Loc, diag::err_typecheck_assign_const)
10000               << ExprRange << ConstVariable << VD << VD->getType();
10001           DiagnosticEmitted = true;
10002         }
10003         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10004             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10005       }
10006     }
10007   } else if (isa<CXXThisExpr>(E)) {
10008     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10009       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10010         if (MD->isConst()) {
10011           if (!DiagnosticEmitted) {
10012             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10013                                                           << ConstMethod << MD;
10014             DiagnosticEmitted = true;
10015           }
10016           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10017               << ConstMethod << MD << MD->getSourceRange();
10018         }
10019       }
10020     }
10021   }
10022 
10023   if (DiagnosticEmitted)
10024     return;
10025 
10026   // Can't determine a more specific message, so display the generic error.
10027   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10028 }
10029 
10030 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10031 /// emit an error and return true.  If so, return false.
10032 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10033   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10034 
10035   S.CheckShadowingDeclModification(E, Loc);
10036 
10037   SourceLocation OrigLoc = Loc;
10038   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10039                                                               &Loc);
10040   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10041     IsLV = Expr::MLV_InvalidMessageExpression;
10042   if (IsLV == Expr::MLV_Valid)
10043     return false;
10044 
10045   unsigned DiagID = 0;
10046   bool NeedType = false;
10047   switch (IsLV) { // C99 6.5.16p2
10048   case Expr::MLV_ConstQualified:
10049     // Use a specialized diagnostic when we're assigning to an object
10050     // from an enclosing function or block.
10051     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10052       if (NCCK == NCCK_Block)
10053         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10054       else
10055         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10056       break;
10057     }
10058 
10059     // In ARC, use some specialized diagnostics for occasions where we
10060     // infer 'const'.  These are always pseudo-strong variables.
10061     if (S.getLangOpts().ObjCAutoRefCount) {
10062       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10063       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10064         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10065 
10066         // Use the normal diagnostic if it's pseudo-__strong but the
10067         // user actually wrote 'const'.
10068         if (var->isARCPseudoStrong() &&
10069             (!var->getTypeSourceInfo() ||
10070              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10071           // There are two pseudo-strong cases:
10072           //  - self
10073           ObjCMethodDecl *method = S.getCurMethodDecl();
10074           if (method && var == method->getSelfDecl())
10075             DiagID = method->isClassMethod()
10076               ? diag::err_typecheck_arc_assign_self_class_method
10077               : diag::err_typecheck_arc_assign_self;
10078 
10079           //  - fast enumeration variables
10080           else
10081             DiagID = diag::err_typecheck_arr_assign_enumeration;
10082 
10083           SourceRange Assign;
10084           if (Loc != OrigLoc)
10085             Assign = SourceRange(OrigLoc, OrigLoc);
10086           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10087           // We need to preserve the AST regardless, so migration tool
10088           // can do its job.
10089           return false;
10090         }
10091       }
10092     }
10093 
10094     // If none of the special cases above are triggered, then this is a
10095     // simple const assignment.
10096     if (DiagID == 0) {
10097       DiagnoseConstAssignment(S, E, Loc);
10098       return true;
10099     }
10100 
10101     break;
10102   case Expr::MLV_ConstAddrSpace:
10103     DiagnoseConstAssignment(S, E, Loc);
10104     return true;
10105   case Expr::MLV_ArrayType:
10106   case Expr::MLV_ArrayTemporary:
10107     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10108     NeedType = true;
10109     break;
10110   case Expr::MLV_NotObjectType:
10111     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10112     NeedType = true;
10113     break;
10114   case Expr::MLV_LValueCast:
10115     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10116     break;
10117   case Expr::MLV_Valid:
10118     llvm_unreachable("did not take early return for MLV_Valid");
10119   case Expr::MLV_InvalidExpression:
10120   case Expr::MLV_MemberFunction:
10121   case Expr::MLV_ClassTemporary:
10122     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10123     break;
10124   case Expr::MLV_IncompleteType:
10125   case Expr::MLV_IncompleteVoidType:
10126     return S.RequireCompleteType(Loc, E->getType(),
10127              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10128   case Expr::MLV_DuplicateVectorComponents:
10129     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10130     break;
10131   case Expr::MLV_NoSetterProperty:
10132     llvm_unreachable("readonly properties should be processed differently");
10133   case Expr::MLV_InvalidMessageExpression:
10134     DiagID = diag::err_readonly_message_assignment;
10135     break;
10136   case Expr::MLV_SubObjCPropertySetting:
10137     DiagID = diag::err_no_subobject_property_setting;
10138     break;
10139   }
10140 
10141   SourceRange Assign;
10142   if (Loc != OrigLoc)
10143     Assign = SourceRange(OrigLoc, OrigLoc);
10144   if (NeedType)
10145     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10146   else
10147     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10148   return true;
10149 }
10150 
10151 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10152                                          SourceLocation Loc,
10153                                          Sema &Sema) {
10154   // C / C++ fields
10155   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10156   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10157   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10158     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10159       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10160   }
10161 
10162   // Objective-C instance variables
10163   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10164   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10165   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10166     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10167     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10168     if (RL && RR && RL->getDecl() == RR->getDecl())
10169       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10170   }
10171 }
10172 
10173 // C99 6.5.16.1
10174 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10175                                        SourceLocation Loc,
10176                                        QualType CompoundType) {
10177   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10178 
10179   // Verify that LHS is a modifiable lvalue, and emit error if not.
10180   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10181     return QualType();
10182 
10183   QualType LHSType = LHSExpr->getType();
10184   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10185                                              CompoundType;
10186   // OpenCL v1.2 s6.1.1.1 p2:
10187   // The half data type can only be used to declare a pointer to a buffer that
10188   // contains half values
10189   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
10190     LHSType->isHalfType()) {
10191     Diag(Loc, diag::err_opencl_half_load_store) << 1
10192         << LHSType.getUnqualifiedType();
10193     return QualType();
10194   }
10195 
10196   AssignConvertType ConvTy;
10197   if (CompoundType.isNull()) {
10198     Expr *RHSCheck = RHS.get();
10199 
10200     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10201 
10202     QualType LHSTy(LHSType);
10203     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10204     if (RHS.isInvalid())
10205       return QualType();
10206     // Special case of NSObject attributes on c-style pointer types.
10207     if (ConvTy == IncompatiblePointer &&
10208         ((Context.isObjCNSObjectType(LHSType) &&
10209           RHSType->isObjCObjectPointerType()) ||
10210          (Context.isObjCNSObjectType(RHSType) &&
10211           LHSType->isObjCObjectPointerType())))
10212       ConvTy = Compatible;
10213 
10214     if (ConvTy == Compatible &&
10215         LHSType->isObjCObjectType())
10216         Diag(Loc, diag::err_objc_object_assignment)
10217           << LHSType;
10218 
10219     // If the RHS is a unary plus or minus, check to see if they = and + are
10220     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10221     // instead of "x += 4".
10222     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10223       RHSCheck = ICE->getSubExpr();
10224     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10225       if ((UO->getOpcode() == UO_Plus ||
10226            UO->getOpcode() == UO_Minus) &&
10227           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10228           // Only if the two operators are exactly adjacent.
10229           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10230           // And there is a space or other character before the subexpr of the
10231           // unary +/-.  We don't want to warn on "x=-1".
10232           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10233           UO->getSubExpr()->getLocStart().isFileID()) {
10234         Diag(Loc, diag::warn_not_compound_assign)
10235           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10236           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10237       }
10238     }
10239 
10240     if (ConvTy == Compatible) {
10241       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10242         // Warn about retain cycles where a block captures the LHS, but
10243         // not if the LHS is a simple variable into which the block is
10244         // being stored...unless that variable can be captured by reference!
10245         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10246         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10247         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10248           checkRetainCycles(LHSExpr, RHS.get());
10249 
10250         // It is safe to assign a weak reference into a strong variable.
10251         // Although this code can still have problems:
10252         //   id x = self.weakProp;
10253         //   id y = self.weakProp;
10254         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10255         // paths through the function. This should be revisited if
10256         // -Wrepeated-use-of-weak is made flow-sensitive.
10257         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10258                              RHS.get()->getLocStart()))
10259           getCurFunction()->markSafeWeakUse(RHS.get());
10260 
10261       } else if (getLangOpts().ObjCAutoRefCount) {
10262         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10263       }
10264     }
10265   } else {
10266     // Compound assignment "x += y"
10267     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10268   }
10269 
10270   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10271                                RHS.get(), AA_Assigning))
10272     return QualType();
10273 
10274   CheckForNullPointerDereference(*this, LHSExpr);
10275 
10276   // C99 6.5.16p3: The type of an assignment expression is the type of the
10277   // left operand unless the left operand has qualified type, in which case
10278   // it is the unqualified version of the type of the left operand.
10279   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10280   // is converted to the type of the assignment expression (above).
10281   // C++ 5.17p1: the type of the assignment expression is that of its left
10282   // operand.
10283   return (getLangOpts().CPlusPlus
10284           ? LHSType : LHSType.getUnqualifiedType());
10285 }
10286 
10287 // Only ignore explicit casts to void.
10288 static bool IgnoreCommaOperand(const Expr *E) {
10289   E = E->IgnoreParens();
10290 
10291   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10292     if (CE->getCastKind() == CK_ToVoid) {
10293       return true;
10294     }
10295   }
10296 
10297   return false;
10298 }
10299 
10300 // Look for instances where it is likely the comma operator is confused with
10301 // another operator.  There is a whitelist of acceptable expressions for the
10302 // left hand side of the comma operator, otherwise emit a warning.
10303 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10304   // No warnings in macros
10305   if (Loc.isMacroID())
10306     return;
10307 
10308   // Don't warn in template instantiations.
10309   if (!ActiveTemplateInstantiations.empty())
10310     return;
10311 
10312   // Scope isn't fine-grained enough to whitelist the specific cases, so
10313   // instead, skip more than needed, then call back into here with the
10314   // CommaVisitor in SemaStmt.cpp.
10315   // The whitelisted locations are the initialization and increment portions
10316   // of a for loop.  The additional checks are on the condition of
10317   // if statements, do/while loops, and for loops.
10318   const unsigned ForIncrementFlags =
10319       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10320   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10321   const unsigned ScopeFlags = getCurScope()->getFlags();
10322   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10323       (ScopeFlags & ForInitFlags) == ForInitFlags)
10324     return;
10325 
10326   // If there are multiple comma operators used together, get the RHS of the
10327   // of the comma operator as the LHS.
10328   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10329     if (BO->getOpcode() != BO_Comma)
10330       break;
10331     LHS = BO->getRHS();
10332   }
10333 
10334   // Only allow some expressions on LHS to not warn.
10335   if (IgnoreCommaOperand(LHS))
10336     return;
10337 
10338   Diag(Loc, diag::warn_comma_operator);
10339   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10340       << LHS->getSourceRange()
10341       << FixItHint::CreateInsertion(LHS->getLocStart(),
10342                                     LangOpts.CPlusPlus ? "static_cast<void>("
10343                                                        : "(void)(")
10344       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10345                                     ")");
10346 }
10347 
10348 // C99 6.5.17
10349 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10350                                    SourceLocation Loc) {
10351   LHS = S.CheckPlaceholderExpr(LHS.get());
10352   RHS = S.CheckPlaceholderExpr(RHS.get());
10353   if (LHS.isInvalid() || RHS.isInvalid())
10354     return QualType();
10355 
10356   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10357   // operands, but not unary promotions.
10358   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10359 
10360   // So we treat the LHS as a ignored value, and in C++ we allow the
10361   // containing site to determine what should be done with the RHS.
10362   LHS = S.IgnoredValueConversions(LHS.get());
10363   if (LHS.isInvalid())
10364     return QualType();
10365 
10366   S.DiagnoseUnusedExprResult(LHS.get());
10367 
10368   if (!S.getLangOpts().CPlusPlus) {
10369     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10370     if (RHS.isInvalid())
10371       return QualType();
10372     if (!RHS.get()->getType()->isVoidType())
10373       S.RequireCompleteType(Loc, RHS.get()->getType(),
10374                             diag::err_incomplete_type);
10375   }
10376 
10377   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10378     S.DiagnoseCommaOperator(LHS.get(), Loc);
10379 
10380   return RHS.get()->getType();
10381 }
10382 
10383 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10384 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10385 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10386                                                ExprValueKind &VK,
10387                                                ExprObjectKind &OK,
10388                                                SourceLocation OpLoc,
10389                                                bool IsInc, bool IsPrefix) {
10390   if (Op->isTypeDependent())
10391     return S.Context.DependentTy;
10392 
10393   QualType ResType = Op->getType();
10394   // Atomic types can be used for increment / decrement where the non-atomic
10395   // versions can, so ignore the _Atomic() specifier for the purpose of
10396   // checking.
10397   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10398     ResType = ResAtomicType->getValueType();
10399 
10400   assert(!ResType.isNull() && "no type for increment/decrement expression");
10401 
10402   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10403     // Decrement of bool is not allowed.
10404     if (!IsInc) {
10405       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10406       return QualType();
10407     }
10408     // Increment of bool sets it to true, but is deprecated.
10409     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10410                                               : diag::warn_increment_bool)
10411       << Op->getSourceRange();
10412   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10413     // Error on enum increments and decrements in C++ mode
10414     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10415     return QualType();
10416   } else if (ResType->isRealType()) {
10417     // OK!
10418   } else if (ResType->isPointerType()) {
10419     // C99 6.5.2.4p2, 6.5.6p2
10420     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10421       return QualType();
10422   } else if (ResType->isObjCObjectPointerType()) {
10423     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10424     // Otherwise, we just need a complete type.
10425     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10426         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10427       return QualType();
10428   } else if (ResType->isAnyComplexType()) {
10429     // C99 does not support ++/-- on complex types, we allow as an extension.
10430     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10431       << ResType << Op->getSourceRange();
10432   } else if (ResType->isPlaceholderType()) {
10433     ExprResult PR = S.CheckPlaceholderExpr(Op);
10434     if (PR.isInvalid()) return QualType();
10435     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10436                                           IsInc, IsPrefix);
10437   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10438     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10439   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10440              (ResType->getAs<VectorType>()->getVectorKind() !=
10441               VectorType::AltiVecBool)) {
10442     // The z vector extensions allow ++ and -- for non-bool vectors.
10443   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10444             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10445     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10446   } else {
10447     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10448       << ResType << int(IsInc) << Op->getSourceRange();
10449     return QualType();
10450   }
10451   // At this point, we know we have a real, complex or pointer type.
10452   // Now make sure the operand is a modifiable lvalue.
10453   if (CheckForModifiableLvalue(Op, OpLoc, S))
10454     return QualType();
10455   // In C++, a prefix increment is the same type as the operand. Otherwise
10456   // (in C or with postfix), the increment is the unqualified type of the
10457   // operand.
10458   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10459     VK = VK_LValue;
10460     OK = Op->getObjectKind();
10461     return ResType;
10462   } else {
10463     VK = VK_RValue;
10464     return ResType.getUnqualifiedType();
10465   }
10466 }
10467 
10468 
10469 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10470 /// This routine allows us to typecheck complex/recursive expressions
10471 /// where the declaration is needed for type checking. We only need to
10472 /// handle cases when the expression references a function designator
10473 /// or is an lvalue. Here are some examples:
10474 ///  - &(x) => x
10475 ///  - &*****f => f for f a function designator.
10476 ///  - &s.xx => s
10477 ///  - &s.zz[1].yy -> s, if zz is an array
10478 ///  - *(x + 1) -> x, if x is an array
10479 ///  - &"123"[2] -> 0
10480 ///  - & __real__ x -> x
10481 static ValueDecl *getPrimaryDecl(Expr *E) {
10482   switch (E->getStmtClass()) {
10483   case Stmt::DeclRefExprClass:
10484     return cast<DeclRefExpr>(E)->getDecl();
10485   case Stmt::MemberExprClass:
10486     // If this is an arrow operator, the address is an offset from
10487     // the base's value, so the object the base refers to is
10488     // irrelevant.
10489     if (cast<MemberExpr>(E)->isArrow())
10490       return nullptr;
10491     // Otherwise, the expression refers to a part of the base
10492     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10493   case Stmt::ArraySubscriptExprClass: {
10494     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10495     // promotion of register arrays earlier.
10496     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10497     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10498       if (ICE->getSubExpr()->getType()->isArrayType())
10499         return getPrimaryDecl(ICE->getSubExpr());
10500     }
10501     return nullptr;
10502   }
10503   case Stmt::UnaryOperatorClass: {
10504     UnaryOperator *UO = cast<UnaryOperator>(E);
10505 
10506     switch(UO->getOpcode()) {
10507     case UO_Real:
10508     case UO_Imag:
10509     case UO_Extension:
10510       return getPrimaryDecl(UO->getSubExpr());
10511     default:
10512       return nullptr;
10513     }
10514   }
10515   case Stmt::ParenExprClass:
10516     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10517   case Stmt::ImplicitCastExprClass:
10518     // If the result of an implicit cast is an l-value, we care about
10519     // the sub-expression; otherwise, the result here doesn't matter.
10520     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10521   default:
10522     return nullptr;
10523   }
10524 }
10525 
10526 namespace {
10527   enum {
10528     AO_Bit_Field = 0,
10529     AO_Vector_Element = 1,
10530     AO_Property_Expansion = 2,
10531     AO_Register_Variable = 3,
10532     AO_No_Error = 4
10533   };
10534 }
10535 /// \brief Diagnose invalid operand for address of operations.
10536 ///
10537 /// \param Type The type of operand which cannot have its address taken.
10538 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10539                                          Expr *E, unsigned Type) {
10540   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10541 }
10542 
10543 /// CheckAddressOfOperand - The operand of & must be either a function
10544 /// designator or an lvalue designating an object. If it is an lvalue, the
10545 /// object cannot be declared with storage class register or be a bit field.
10546 /// Note: The usual conversions are *not* applied to the operand of the &
10547 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10548 /// In C++, the operand might be an overloaded function name, in which case
10549 /// we allow the '&' but retain the overloaded-function type.
10550 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10551   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10552     if (PTy->getKind() == BuiltinType::Overload) {
10553       Expr *E = OrigOp.get()->IgnoreParens();
10554       if (!isa<OverloadExpr>(E)) {
10555         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10556         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10557           << OrigOp.get()->getSourceRange();
10558         return QualType();
10559       }
10560 
10561       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10562       if (isa<UnresolvedMemberExpr>(Ovl))
10563         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10564           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10565             << OrigOp.get()->getSourceRange();
10566           return QualType();
10567         }
10568 
10569       return Context.OverloadTy;
10570     }
10571 
10572     if (PTy->getKind() == BuiltinType::UnknownAny)
10573       return Context.UnknownAnyTy;
10574 
10575     if (PTy->getKind() == BuiltinType::BoundMember) {
10576       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10577         << OrigOp.get()->getSourceRange();
10578       return QualType();
10579     }
10580 
10581     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10582     if (OrigOp.isInvalid()) return QualType();
10583   }
10584 
10585   if (OrigOp.get()->isTypeDependent())
10586     return Context.DependentTy;
10587 
10588   assert(!OrigOp.get()->getType()->isPlaceholderType());
10589 
10590   // Make sure to ignore parentheses in subsequent checks
10591   Expr *op = OrigOp.get()->IgnoreParens();
10592 
10593   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10594   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10595     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10596     return QualType();
10597   }
10598 
10599   if (getLangOpts().C99) {
10600     // Implement C99-only parts of addressof rules.
10601     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10602       if (uOp->getOpcode() == UO_Deref)
10603         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10604         // (assuming the deref expression is valid).
10605         return uOp->getSubExpr()->getType();
10606     }
10607     // Technically, there should be a check for array subscript
10608     // expressions here, but the result of one is always an lvalue anyway.
10609   }
10610   ValueDecl *dcl = getPrimaryDecl(op);
10611 
10612   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10613     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10614                                            op->getLocStart()))
10615       return QualType();
10616 
10617   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10618   unsigned AddressOfError = AO_No_Error;
10619 
10620   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10621     bool sfinae = (bool)isSFINAEContext();
10622     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10623                                   : diag::ext_typecheck_addrof_temporary)
10624       << op->getType() << op->getSourceRange();
10625     if (sfinae)
10626       return QualType();
10627     // Materialize the temporary as an lvalue so that we can take its address.
10628     OrigOp = op =
10629         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10630   } else if (isa<ObjCSelectorExpr>(op)) {
10631     return Context.getPointerType(op->getType());
10632   } else if (lval == Expr::LV_MemberFunction) {
10633     // If it's an instance method, make a member pointer.
10634     // The expression must have exactly the form &A::foo.
10635 
10636     // If the underlying expression isn't a decl ref, give up.
10637     if (!isa<DeclRefExpr>(op)) {
10638       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10639         << OrigOp.get()->getSourceRange();
10640       return QualType();
10641     }
10642     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10643     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10644 
10645     // The id-expression was parenthesized.
10646     if (OrigOp.get() != DRE) {
10647       Diag(OpLoc, diag::err_parens_pointer_member_function)
10648         << OrigOp.get()->getSourceRange();
10649 
10650     // The method was named without a qualifier.
10651     } else if (!DRE->getQualifier()) {
10652       if (MD->getParent()->getName().empty())
10653         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10654           << op->getSourceRange();
10655       else {
10656         SmallString<32> Str;
10657         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10658         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10659           << op->getSourceRange()
10660           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10661       }
10662     }
10663 
10664     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10665     if (isa<CXXDestructorDecl>(MD))
10666       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10667 
10668     QualType MPTy = Context.getMemberPointerType(
10669         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10670     // Under the MS ABI, lock down the inheritance model now.
10671     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10672       (void)isCompleteType(OpLoc, MPTy);
10673     return MPTy;
10674   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10675     // C99 6.5.3.2p1
10676     // The operand must be either an l-value or a function designator
10677     if (!op->getType()->isFunctionType()) {
10678       // Use a special diagnostic for loads from property references.
10679       if (isa<PseudoObjectExpr>(op)) {
10680         AddressOfError = AO_Property_Expansion;
10681       } else {
10682         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10683           << op->getType() << op->getSourceRange();
10684         return QualType();
10685       }
10686     }
10687   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10688     // The operand cannot be a bit-field
10689     AddressOfError = AO_Bit_Field;
10690   } else if (op->getObjectKind() == OK_VectorComponent) {
10691     // The operand cannot be an element of a vector
10692     AddressOfError = AO_Vector_Element;
10693   } else if (dcl) { // C99 6.5.3.2p1
10694     // We have an lvalue with a decl. Make sure the decl is not declared
10695     // with the register storage-class specifier.
10696     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10697       // in C++ it is not error to take address of a register
10698       // variable (c++03 7.1.1P3)
10699       if (vd->getStorageClass() == SC_Register &&
10700           !getLangOpts().CPlusPlus) {
10701         AddressOfError = AO_Register_Variable;
10702       }
10703     } else if (isa<MSPropertyDecl>(dcl)) {
10704       AddressOfError = AO_Property_Expansion;
10705     } else if (isa<FunctionTemplateDecl>(dcl)) {
10706       return Context.OverloadTy;
10707     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10708       // Okay: we can take the address of a field.
10709       // Could be a pointer to member, though, if there is an explicit
10710       // scope qualifier for the class.
10711       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10712         DeclContext *Ctx = dcl->getDeclContext();
10713         if (Ctx && Ctx->isRecord()) {
10714           if (dcl->getType()->isReferenceType()) {
10715             Diag(OpLoc,
10716                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10717               << dcl->getDeclName() << dcl->getType();
10718             return QualType();
10719           }
10720 
10721           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10722             Ctx = Ctx->getParent();
10723 
10724           QualType MPTy = Context.getMemberPointerType(
10725               op->getType(),
10726               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10727           // Under the MS ABI, lock down the inheritance model now.
10728           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10729             (void)isCompleteType(OpLoc, MPTy);
10730           return MPTy;
10731         }
10732       }
10733     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10734                !isa<BindingDecl>(dcl))
10735       llvm_unreachable("Unknown/unexpected decl type");
10736   }
10737 
10738   if (AddressOfError != AO_No_Error) {
10739     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10740     return QualType();
10741   }
10742 
10743   if (lval == Expr::LV_IncompleteVoidType) {
10744     // Taking the address of a void variable is technically illegal, but we
10745     // allow it in cases which are otherwise valid.
10746     // Example: "extern void x; void* y = &x;".
10747     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10748   }
10749 
10750   // If the operand has type "type", the result has type "pointer to type".
10751   if (op->getType()->isObjCObjectType())
10752     return Context.getObjCObjectPointerType(op->getType());
10753 
10754   CheckAddressOfPackedMember(op);
10755 
10756   return Context.getPointerType(op->getType());
10757 }
10758 
10759 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10760   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10761   if (!DRE)
10762     return;
10763   const Decl *D = DRE->getDecl();
10764   if (!D)
10765     return;
10766   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10767   if (!Param)
10768     return;
10769   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10770     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10771       return;
10772   if (FunctionScopeInfo *FD = S.getCurFunction())
10773     if (!FD->ModifiedNonNullParams.count(Param))
10774       FD->ModifiedNonNullParams.insert(Param);
10775 }
10776 
10777 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10778 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10779                                         SourceLocation OpLoc) {
10780   if (Op->isTypeDependent())
10781     return S.Context.DependentTy;
10782 
10783   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10784   if (ConvResult.isInvalid())
10785     return QualType();
10786   Op = ConvResult.get();
10787   QualType OpTy = Op->getType();
10788   QualType Result;
10789 
10790   if (isa<CXXReinterpretCastExpr>(Op)) {
10791     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10792     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10793                                      Op->getSourceRange());
10794   }
10795 
10796   if (const PointerType *PT = OpTy->getAs<PointerType>())
10797   {
10798     Result = PT->getPointeeType();
10799   }
10800   else if (const ObjCObjectPointerType *OPT =
10801              OpTy->getAs<ObjCObjectPointerType>())
10802     Result = OPT->getPointeeType();
10803   else {
10804     ExprResult PR = S.CheckPlaceholderExpr(Op);
10805     if (PR.isInvalid()) return QualType();
10806     if (PR.get() != Op)
10807       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10808   }
10809 
10810   if (Result.isNull()) {
10811     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10812       << OpTy << Op->getSourceRange();
10813     return QualType();
10814   }
10815 
10816   // Note that per both C89 and C99, indirection is always legal, even if Result
10817   // is an incomplete type or void.  It would be possible to warn about
10818   // dereferencing a void pointer, but it's completely well-defined, and such a
10819   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10820   // for pointers to 'void' but is fine for any other pointer type:
10821   //
10822   // C++ [expr.unary.op]p1:
10823   //   [...] the expression to which [the unary * operator] is applied shall
10824   //   be a pointer to an object type, or a pointer to a function type
10825   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10826     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10827       << OpTy << Op->getSourceRange();
10828 
10829   // Dereferences are usually l-values...
10830   VK = VK_LValue;
10831 
10832   // ...except that certain expressions are never l-values in C.
10833   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10834     VK = VK_RValue;
10835 
10836   return Result;
10837 }
10838 
10839 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10840   BinaryOperatorKind Opc;
10841   switch (Kind) {
10842   default: llvm_unreachable("Unknown binop!");
10843   case tok::periodstar:           Opc = BO_PtrMemD; break;
10844   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10845   case tok::star:                 Opc = BO_Mul; break;
10846   case tok::slash:                Opc = BO_Div; break;
10847   case tok::percent:              Opc = BO_Rem; break;
10848   case tok::plus:                 Opc = BO_Add; break;
10849   case tok::minus:                Opc = BO_Sub; break;
10850   case tok::lessless:             Opc = BO_Shl; break;
10851   case tok::greatergreater:       Opc = BO_Shr; break;
10852   case tok::lessequal:            Opc = BO_LE; break;
10853   case tok::less:                 Opc = BO_LT; break;
10854   case tok::greaterequal:         Opc = BO_GE; break;
10855   case tok::greater:              Opc = BO_GT; break;
10856   case tok::exclaimequal:         Opc = BO_NE; break;
10857   case tok::equalequal:           Opc = BO_EQ; break;
10858   case tok::amp:                  Opc = BO_And; break;
10859   case tok::caret:                Opc = BO_Xor; break;
10860   case tok::pipe:                 Opc = BO_Or; break;
10861   case tok::ampamp:               Opc = BO_LAnd; break;
10862   case tok::pipepipe:             Opc = BO_LOr; break;
10863   case tok::equal:                Opc = BO_Assign; break;
10864   case tok::starequal:            Opc = BO_MulAssign; break;
10865   case tok::slashequal:           Opc = BO_DivAssign; break;
10866   case tok::percentequal:         Opc = BO_RemAssign; break;
10867   case tok::plusequal:            Opc = BO_AddAssign; break;
10868   case tok::minusequal:           Opc = BO_SubAssign; break;
10869   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10870   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10871   case tok::ampequal:             Opc = BO_AndAssign; break;
10872   case tok::caretequal:           Opc = BO_XorAssign; break;
10873   case tok::pipeequal:            Opc = BO_OrAssign; break;
10874   case tok::comma:                Opc = BO_Comma; break;
10875   }
10876   return Opc;
10877 }
10878 
10879 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10880   tok::TokenKind Kind) {
10881   UnaryOperatorKind Opc;
10882   switch (Kind) {
10883   default: llvm_unreachable("Unknown unary op!");
10884   case tok::plusplus:     Opc = UO_PreInc; break;
10885   case tok::minusminus:   Opc = UO_PreDec; break;
10886   case tok::amp:          Opc = UO_AddrOf; break;
10887   case tok::star:         Opc = UO_Deref; break;
10888   case tok::plus:         Opc = UO_Plus; break;
10889   case tok::minus:        Opc = UO_Minus; break;
10890   case tok::tilde:        Opc = UO_Not; break;
10891   case tok::exclaim:      Opc = UO_LNot; break;
10892   case tok::kw___real:    Opc = UO_Real; break;
10893   case tok::kw___imag:    Opc = UO_Imag; break;
10894   case tok::kw___extension__: Opc = UO_Extension; break;
10895   }
10896   return Opc;
10897 }
10898 
10899 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10900 /// This warning is only emitted for builtin assignment operations. It is also
10901 /// suppressed in the event of macro expansions.
10902 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10903                                    SourceLocation OpLoc) {
10904   if (!S.ActiveTemplateInstantiations.empty())
10905     return;
10906   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10907     return;
10908   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10909   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10910   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10911   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10912   if (!LHSDeclRef || !RHSDeclRef ||
10913       LHSDeclRef->getLocation().isMacroID() ||
10914       RHSDeclRef->getLocation().isMacroID())
10915     return;
10916   const ValueDecl *LHSDecl =
10917     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10918   const ValueDecl *RHSDecl =
10919     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10920   if (LHSDecl != RHSDecl)
10921     return;
10922   if (LHSDecl->getType().isVolatileQualified())
10923     return;
10924   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10925     if (RefTy->getPointeeType().isVolatileQualified())
10926       return;
10927 
10928   S.Diag(OpLoc, diag::warn_self_assignment)
10929       << LHSDeclRef->getType()
10930       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10931 }
10932 
10933 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10934 /// is usually indicative of introspection within the Objective-C pointer.
10935 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10936                                           SourceLocation OpLoc) {
10937   if (!S.getLangOpts().ObjC1)
10938     return;
10939 
10940   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10941   const Expr *LHS = L.get();
10942   const Expr *RHS = R.get();
10943 
10944   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10945     ObjCPointerExpr = LHS;
10946     OtherExpr = RHS;
10947   }
10948   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10949     ObjCPointerExpr = RHS;
10950     OtherExpr = LHS;
10951   }
10952 
10953   // This warning is deliberately made very specific to reduce false
10954   // positives with logic that uses '&' for hashing.  This logic mainly
10955   // looks for code trying to introspect into tagged pointers, which
10956   // code should generally never do.
10957   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10958     unsigned Diag = diag::warn_objc_pointer_masking;
10959     // Determine if we are introspecting the result of performSelectorXXX.
10960     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10961     // Special case messages to -performSelector and friends, which
10962     // can return non-pointer values boxed in a pointer value.
10963     // Some clients may wish to silence warnings in this subcase.
10964     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10965       Selector S = ME->getSelector();
10966       StringRef SelArg0 = S.getNameForSlot(0);
10967       if (SelArg0.startswith("performSelector"))
10968         Diag = diag::warn_objc_pointer_masking_performSelector;
10969     }
10970 
10971     S.Diag(OpLoc, Diag)
10972       << ObjCPointerExpr->getSourceRange();
10973   }
10974 }
10975 
10976 static NamedDecl *getDeclFromExpr(Expr *E) {
10977   if (!E)
10978     return nullptr;
10979   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10980     return DRE->getDecl();
10981   if (auto *ME = dyn_cast<MemberExpr>(E))
10982     return ME->getMemberDecl();
10983   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10984     return IRE->getDecl();
10985   return nullptr;
10986 }
10987 
10988 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10989 /// operator @p Opc at location @c TokLoc. This routine only supports
10990 /// built-in operations; ActOnBinOp handles overloaded operators.
10991 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10992                                     BinaryOperatorKind Opc,
10993                                     Expr *LHSExpr, Expr *RHSExpr) {
10994   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10995     // The syntax only allows initializer lists on the RHS of assignment,
10996     // so we don't need to worry about accepting invalid code for
10997     // non-assignment operators.
10998     // C++11 5.17p9:
10999     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11000     //   of x = {} is x = T().
11001     InitializationKind Kind =
11002         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11003     InitializedEntity Entity =
11004         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11005     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11006     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11007     if (Init.isInvalid())
11008       return Init;
11009     RHSExpr = Init.get();
11010   }
11011 
11012   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11013   QualType ResultTy;     // Result type of the binary operator.
11014   // The following two variables are used for compound assignment operators
11015   QualType CompLHSTy;    // Type of LHS after promotions for computation
11016   QualType CompResultTy; // Type of computation result
11017   ExprValueKind VK = VK_RValue;
11018   ExprObjectKind OK = OK_Ordinary;
11019 
11020   if (!getLangOpts().CPlusPlus) {
11021     // C cannot handle TypoExpr nodes on either side of a binop because it
11022     // doesn't handle dependent types properly, so make sure any TypoExprs have
11023     // been dealt with before checking the operands.
11024     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11025     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11026       if (Opc != BO_Assign)
11027         return ExprResult(E);
11028       // Avoid correcting the RHS to the same Expr as the LHS.
11029       Decl *D = getDeclFromExpr(E);
11030       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11031     });
11032     if (!LHS.isUsable() || !RHS.isUsable())
11033       return ExprError();
11034   }
11035 
11036   if (getLangOpts().OpenCL) {
11037     QualType LHSTy = LHSExpr->getType();
11038     QualType RHSTy = RHSExpr->getType();
11039     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11040     // the ATOMIC_VAR_INIT macro.
11041     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11042       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11043       if (BO_Assign == Opc)
11044         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11045       else
11046         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11047       return ExprError();
11048     }
11049 
11050     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11051     // only with a builtin functions and therefore should be disallowed here.
11052     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11053         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11054         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11055         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11056       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11057       return ExprError();
11058     }
11059   }
11060 
11061   switch (Opc) {
11062   case BO_Assign:
11063     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11064     if (getLangOpts().CPlusPlus &&
11065         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11066       VK = LHS.get()->getValueKind();
11067       OK = LHS.get()->getObjectKind();
11068     }
11069     if (!ResultTy.isNull()) {
11070       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11071       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11072     }
11073     RecordModifiableNonNullParam(*this, LHS.get());
11074     break;
11075   case BO_PtrMemD:
11076   case BO_PtrMemI:
11077     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11078                                             Opc == BO_PtrMemI);
11079     break;
11080   case BO_Mul:
11081   case BO_Div:
11082     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11083                                            Opc == BO_Div);
11084     break;
11085   case BO_Rem:
11086     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11087     break;
11088   case BO_Add:
11089     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11090     break;
11091   case BO_Sub:
11092     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11093     break;
11094   case BO_Shl:
11095   case BO_Shr:
11096     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11097     break;
11098   case BO_LE:
11099   case BO_LT:
11100   case BO_GE:
11101   case BO_GT:
11102     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11103     break;
11104   case BO_EQ:
11105   case BO_NE:
11106     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11107     break;
11108   case BO_And:
11109     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11110   case BO_Xor:
11111   case BO_Or:
11112     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11113     break;
11114   case BO_LAnd:
11115   case BO_LOr:
11116     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11117     break;
11118   case BO_MulAssign:
11119   case BO_DivAssign:
11120     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11121                                                Opc == BO_DivAssign);
11122     CompLHSTy = CompResultTy;
11123     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11124       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11125     break;
11126   case BO_RemAssign:
11127     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11128     CompLHSTy = CompResultTy;
11129     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11130       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11131     break;
11132   case BO_AddAssign:
11133     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11134     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11135       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11136     break;
11137   case BO_SubAssign:
11138     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11139     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11140       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11141     break;
11142   case BO_ShlAssign:
11143   case BO_ShrAssign:
11144     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11145     CompLHSTy = CompResultTy;
11146     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11147       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11148     break;
11149   case BO_AndAssign:
11150   case BO_OrAssign: // fallthrough
11151     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11152   case BO_XorAssign:
11153     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11154     CompLHSTy = CompResultTy;
11155     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11156       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11157     break;
11158   case BO_Comma:
11159     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11160     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11161       VK = RHS.get()->getValueKind();
11162       OK = RHS.get()->getObjectKind();
11163     }
11164     break;
11165   }
11166   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11167     return ExprError();
11168 
11169   // Check for array bounds violations for both sides of the BinaryOperator
11170   CheckArrayAccess(LHS.get());
11171   CheckArrayAccess(RHS.get());
11172 
11173   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11174     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11175                                                  &Context.Idents.get("object_setClass"),
11176                                                  SourceLocation(), LookupOrdinaryName);
11177     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11178       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11179       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11180       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11181       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11182       FixItHint::CreateInsertion(RHSLocEnd, ")");
11183     }
11184     else
11185       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11186   }
11187   else if (const ObjCIvarRefExpr *OIRE =
11188            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11189     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11190 
11191   if (CompResultTy.isNull())
11192     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11193                                         OK, OpLoc, FPFeatures.fp_contract);
11194   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11195       OK_ObjCProperty) {
11196     VK = VK_LValue;
11197     OK = LHS.get()->getObjectKind();
11198   }
11199   return new (Context) CompoundAssignOperator(
11200       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11201       OpLoc, FPFeatures.fp_contract);
11202 }
11203 
11204 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11205 /// operators are mixed in a way that suggests that the programmer forgot that
11206 /// comparison operators have higher precedence. The most typical example of
11207 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11208 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11209                                       SourceLocation OpLoc, Expr *LHSExpr,
11210                                       Expr *RHSExpr) {
11211   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11212   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11213 
11214   // Check that one of the sides is a comparison operator and the other isn't.
11215   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11216   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11217   if (isLeftComp == isRightComp)
11218     return;
11219 
11220   // Bitwise operations are sometimes used as eager logical ops.
11221   // Don't diagnose this.
11222   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11223   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11224   if (isLeftBitwise || isRightBitwise)
11225     return;
11226 
11227   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11228                                                    OpLoc)
11229                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11230   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11231   SourceRange ParensRange = isLeftComp ?
11232       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11233     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11234 
11235   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11236     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11237   SuggestParentheses(Self, OpLoc,
11238     Self.PDiag(diag::note_precedence_silence) << OpStr,
11239     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11240   SuggestParentheses(Self, OpLoc,
11241     Self.PDiag(diag::note_precedence_bitwise_first)
11242       << BinaryOperator::getOpcodeStr(Opc),
11243     ParensRange);
11244 }
11245 
11246 /// \brief It accepts a '&&' expr that is inside a '||' one.
11247 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11248 /// in parentheses.
11249 static void
11250 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11251                                        BinaryOperator *Bop) {
11252   assert(Bop->getOpcode() == BO_LAnd);
11253   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11254       << Bop->getSourceRange() << OpLoc;
11255   SuggestParentheses(Self, Bop->getOperatorLoc(),
11256     Self.PDiag(diag::note_precedence_silence)
11257       << Bop->getOpcodeStr(),
11258     Bop->getSourceRange());
11259 }
11260 
11261 /// \brief Returns true if the given expression can be evaluated as a constant
11262 /// 'true'.
11263 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11264   bool Res;
11265   return !E->isValueDependent() &&
11266          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11267 }
11268 
11269 /// \brief Returns true if the given expression can be evaluated as a constant
11270 /// 'false'.
11271 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11272   bool Res;
11273   return !E->isValueDependent() &&
11274          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11275 }
11276 
11277 /// \brief Look for '&&' in the left hand of a '||' expr.
11278 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11279                                              Expr *LHSExpr, Expr *RHSExpr) {
11280   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11281     if (Bop->getOpcode() == BO_LAnd) {
11282       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11283       if (EvaluatesAsFalse(S, RHSExpr))
11284         return;
11285       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11286       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11287         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11288     } else if (Bop->getOpcode() == BO_LOr) {
11289       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11290         // If it's "a || b && 1 || c" we didn't warn earlier for
11291         // "a || b && 1", but warn now.
11292         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11293           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11294       }
11295     }
11296   }
11297 }
11298 
11299 /// \brief Look for '&&' in the right hand of a '||' expr.
11300 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11301                                              Expr *LHSExpr, Expr *RHSExpr) {
11302   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11303     if (Bop->getOpcode() == BO_LAnd) {
11304       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11305       if (EvaluatesAsFalse(S, LHSExpr))
11306         return;
11307       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11308       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11309         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11310     }
11311   }
11312 }
11313 
11314 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11315 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11316 /// the '&' expression in parentheses.
11317 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11318                                          SourceLocation OpLoc, Expr *SubExpr) {
11319   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11320     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11321       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11322         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11323         << Bop->getSourceRange() << OpLoc;
11324       SuggestParentheses(S, Bop->getOperatorLoc(),
11325         S.PDiag(diag::note_precedence_silence)
11326           << Bop->getOpcodeStr(),
11327         Bop->getSourceRange());
11328     }
11329   }
11330 }
11331 
11332 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11333                                     Expr *SubExpr, StringRef Shift) {
11334   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11335     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11336       StringRef Op = Bop->getOpcodeStr();
11337       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11338           << Bop->getSourceRange() << OpLoc << Shift << Op;
11339       SuggestParentheses(S, Bop->getOperatorLoc(),
11340           S.PDiag(diag::note_precedence_silence) << Op,
11341           Bop->getSourceRange());
11342     }
11343   }
11344 }
11345 
11346 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11347                                  Expr *LHSExpr, Expr *RHSExpr) {
11348   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11349   if (!OCE)
11350     return;
11351 
11352   FunctionDecl *FD = OCE->getDirectCallee();
11353   if (!FD || !FD->isOverloadedOperator())
11354     return;
11355 
11356   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11357   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11358     return;
11359 
11360   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11361       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11362       << (Kind == OO_LessLess);
11363   SuggestParentheses(S, OCE->getOperatorLoc(),
11364                      S.PDiag(diag::note_precedence_silence)
11365                          << (Kind == OO_LessLess ? "<<" : ">>"),
11366                      OCE->getSourceRange());
11367   SuggestParentheses(S, OpLoc,
11368                      S.PDiag(diag::note_evaluate_comparison_first),
11369                      SourceRange(OCE->getArg(1)->getLocStart(),
11370                                  RHSExpr->getLocEnd()));
11371 }
11372 
11373 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11374 /// precedence.
11375 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11376                                     SourceLocation OpLoc, Expr *LHSExpr,
11377                                     Expr *RHSExpr){
11378   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11379   if (BinaryOperator::isBitwiseOp(Opc))
11380     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11381 
11382   // Diagnose "arg1 & arg2 | arg3"
11383   if ((Opc == BO_Or || Opc == BO_Xor) &&
11384       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11385     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11386     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11387   }
11388 
11389   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11390   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11391   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11392     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11393     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11394   }
11395 
11396   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11397       || Opc == BO_Shr) {
11398     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11399     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11400     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11401   }
11402 
11403   // Warn on overloaded shift operators and comparisons, such as:
11404   // cout << 5 == 4;
11405   if (BinaryOperator::isComparisonOp(Opc))
11406     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11407 }
11408 
11409 // Binary Operators.  'Tok' is the token for the operator.
11410 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11411                             tok::TokenKind Kind,
11412                             Expr *LHSExpr, Expr *RHSExpr) {
11413   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11414   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11415   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11416 
11417   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11418   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11419 
11420   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11421 }
11422 
11423 /// Build an overloaded binary operator expression in the given scope.
11424 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11425                                        BinaryOperatorKind Opc,
11426                                        Expr *LHS, Expr *RHS) {
11427   // Find all of the overloaded operators visible from this
11428   // point. We perform both an operator-name lookup from the local
11429   // scope and an argument-dependent lookup based on the types of
11430   // the arguments.
11431   UnresolvedSet<16> Functions;
11432   OverloadedOperatorKind OverOp
11433     = BinaryOperator::getOverloadedOperator(Opc);
11434   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11435     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11436                                    RHS->getType(), Functions);
11437 
11438   // Build the (potentially-overloaded, potentially-dependent)
11439   // binary operation.
11440   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11441 }
11442 
11443 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11444                             BinaryOperatorKind Opc,
11445                             Expr *LHSExpr, Expr *RHSExpr) {
11446   // We want to end up calling one of checkPseudoObjectAssignment
11447   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11448   // both expressions are overloadable or either is type-dependent),
11449   // or CreateBuiltinBinOp (in any other case).  We also want to get
11450   // any placeholder types out of the way.
11451 
11452   // Handle pseudo-objects in the LHS.
11453   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11454     // Assignments with a pseudo-object l-value need special analysis.
11455     if (pty->getKind() == BuiltinType::PseudoObject &&
11456         BinaryOperator::isAssignmentOp(Opc))
11457       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11458 
11459     // Don't resolve overloads if the other type is overloadable.
11460     if (pty->getKind() == BuiltinType::Overload) {
11461       // We can't actually test that if we still have a placeholder,
11462       // though.  Fortunately, none of the exceptions we see in that
11463       // code below are valid when the LHS is an overload set.  Note
11464       // that an overload set can be dependently-typed, but it never
11465       // instantiates to having an overloadable type.
11466       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11467       if (resolvedRHS.isInvalid()) return ExprError();
11468       RHSExpr = resolvedRHS.get();
11469 
11470       if (RHSExpr->isTypeDependent() ||
11471           RHSExpr->getType()->isOverloadableType())
11472         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11473     }
11474 
11475     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11476     if (LHS.isInvalid()) return ExprError();
11477     LHSExpr = LHS.get();
11478   }
11479 
11480   // Handle pseudo-objects in the RHS.
11481   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11482     // An overload in the RHS can potentially be resolved by the type
11483     // being assigned to.
11484     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11485       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11486         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11487 
11488       if (LHSExpr->getType()->isOverloadableType())
11489         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11490 
11491       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11492     }
11493 
11494     // Don't resolve overloads if the other type is overloadable.
11495     if (pty->getKind() == BuiltinType::Overload &&
11496         LHSExpr->getType()->isOverloadableType())
11497       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11498 
11499     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11500     if (!resolvedRHS.isUsable()) return ExprError();
11501     RHSExpr = resolvedRHS.get();
11502   }
11503 
11504   if (getLangOpts().CPlusPlus) {
11505     // If either expression is type-dependent, always build an
11506     // overloaded op.
11507     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11508       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11509 
11510     // Otherwise, build an overloaded op if either expression has an
11511     // overloadable type.
11512     if (LHSExpr->getType()->isOverloadableType() ||
11513         RHSExpr->getType()->isOverloadableType())
11514       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11515   }
11516 
11517   // Build a built-in binary operation.
11518   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11519 }
11520 
11521 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11522                                       UnaryOperatorKind Opc,
11523                                       Expr *InputExpr) {
11524   ExprResult Input = InputExpr;
11525   ExprValueKind VK = VK_RValue;
11526   ExprObjectKind OK = OK_Ordinary;
11527   QualType resultType;
11528   if (getLangOpts().OpenCL) {
11529     QualType Ty = InputExpr->getType();
11530     // The only legal unary operation for atomics is '&'.
11531     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11532     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11533     // only with a builtin functions and therefore should be disallowed here.
11534         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11535         || Ty->isBlockPointerType())) {
11536       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11537                        << InputExpr->getType()
11538                        << Input.get()->getSourceRange());
11539     }
11540   }
11541   switch (Opc) {
11542   case UO_PreInc:
11543   case UO_PreDec:
11544   case UO_PostInc:
11545   case UO_PostDec:
11546     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11547                                                 OpLoc,
11548                                                 Opc == UO_PreInc ||
11549                                                 Opc == UO_PostInc,
11550                                                 Opc == UO_PreInc ||
11551                                                 Opc == UO_PreDec);
11552     break;
11553   case UO_AddrOf:
11554     resultType = CheckAddressOfOperand(Input, OpLoc);
11555     RecordModifiableNonNullParam(*this, InputExpr);
11556     break;
11557   case UO_Deref: {
11558     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11559     if (Input.isInvalid()) return ExprError();
11560     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11561     break;
11562   }
11563   case UO_Plus:
11564   case UO_Minus:
11565     Input = UsualUnaryConversions(Input.get());
11566     if (Input.isInvalid()) return ExprError();
11567     resultType = Input.get()->getType();
11568     if (resultType->isDependentType())
11569       break;
11570     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11571       break;
11572     else if (resultType->isVectorType() &&
11573              // The z vector extensions don't allow + or - with bool vectors.
11574              (!Context.getLangOpts().ZVector ||
11575               resultType->getAs<VectorType>()->getVectorKind() !=
11576               VectorType::AltiVecBool))
11577       break;
11578     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11579              Opc == UO_Plus &&
11580              resultType->isPointerType())
11581       break;
11582 
11583     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11584       << resultType << Input.get()->getSourceRange());
11585 
11586   case UO_Not: // bitwise complement
11587     Input = UsualUnaryConversions(Input.get());
11588     if (Input.isInvalid())
11589       return ExprError();
11590     resultType = Input.get()->getType();
11591     if (resultType->isDependentType())
11592       break;
11593     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11594     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11595       // C99 does not support '~' for complex conjugation.
11596       Diag(OpLoc, diag::ext_integer_complement_complex)
11597           << resultType << Input.get()->getSourceRange();
11598     else if (resultType->hasIntegerRepresentation())
11599       break;
11600     else if (resultType->isExtVectorType()) {
11601       if (Context.getLangOpts().OpenCL) {
11602         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11603         // on vector float types.
11604         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11605         if (!T->isIntegerType())
11606           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11607                            << resultType << Input.get()->getSourceRange());
11608       }
11609       break;
11610     } else {
11611       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11612                        << resultType << Input.get()->getSourceRange());
11613     }
11614     break;
11615 
11616   case UO_LNot: // logical negation
11617     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11618     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11619     if (Input.isInvalid()) return ExprError();
11620     resultType = Input.get()->getType();
11621 
11622     // Though we still have to promote half FP to float...
11623     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11624       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11625       resultType = Context.FloatTy;
11626     }
11627 
11628     if (resultType->isDependentType())
11629       break;
11630     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11631       // C99 6.5.3.3p1: ok, fallthrough;
11632       if (Context.getLangOpts().CPlusPlus) {
11633         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11634         // operand contextually converted to bool.
11635         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11636                                   ScalarTypeToBooleanCastKind(resultType));
11637       } else if (Context.getLangOpts().OpenCL &&
11638                  Context.getLangOpts().OpenCLVersion < 120) {
11639         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11640         // operate on scalar float types.
11641         if (!resultType->isIntegerType())
11642           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11643                            << resultType << Input.get()->getSourceRange());
11644       }
11645     } else if (resultType->isExtVectorType()) {
11646       if (Context.getLangOpts().OpenCL &&
11647           Context.getLangOpts().OpenCLVersion < 120) {
11648         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11649         // operate on vector float types.
11650         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11651         if (!T->isIntegerType())
11652           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11653                            << resultType << Input.get()->getSourceRange());
11654       }
11655       // Vector logical not returns the signed variant of the operand type.
11656       resultType = GetSignedVectorType(resultType);
11657       break;
11658     } else {
11659       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11660         << resultType << Input.get()->getSourceRange());
11661     }
11662 
11663     // LNot always has type int. C99 6.5.3.3p5.
11664     // In C++, it's bool. C++ 5.3.1p8
11665     resultType = Context.getLogicalOperationType();
11666     break;
11667   case UO_Real:
11668   case UO_Imag:
11669     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11670     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11671     // complex l-values to ordinary l-values and all other values to r-values.
11672     if (Input.isInvalid()) return ExprError();
11673     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11674       if (Input.get()->getValueKind() != VK_RValue &&
11675           Input.get()->getObjectKind() == OK_Ordinary)
11676         VK = Input.get()->getValueKind();
11677     } else if (!getLangOpts().CPlusPlus) {
11678       // In C, a volatile scalar is read by __imag. In C++, it is not.
11679       Input = DefaultLvalueConversion(Input.get());
11680     }
11681     break;
11682   case UO_Extension:
11683   case UO_Coawait:
11684     resultType = Input.get()->getType();
11685     VK = Input.get()->getValueKind();
11686     OK = Input.get()->getObjectKind();
11687     break;
11688   }
11689   if (resultType.isNull() || Input.isInvalid())
11690     return ExprError();
11691 
11692   // Check for array bounds violations in the operand of the UnaryOperator,
11693   // except for the '*' and '&' operators that have to be handled specially
11694   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11695   // that are explicitly defined as valid by the standard).
11696   if (Opc != UO_AddrOf && Opc != UO_Deref)
11697     CheckArrayAccess(Input.get());
11698 
11699   return new (Context)
11700       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11701 }
11702 
11703 /// \brief Determine whether the given expression is a qualified member
11704 /// access expression, of a form that could be turned into a pointer to member
11705 /// with the address-of operator.
11706 static bool isQualifiedMemberAccess(Expr *E) {
11707   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11708     if (!DRE->getQualifier())
11709       return false;
11710 
11711     ValueDecl *VD = DRE->getDecl();
11712     if (!VD->isCXXClassMember())
11713       return false;
11714 
11715     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11716       return true;
11717     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11718       return Method->isInstance();
11719 
11720     return false;
11721   }
11722 
11723   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11724     if (!ULE->getQualifier())
11725       return false;
11726 
11727     for (NamedDecl *D : ULE->decls()) {
11728       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11729         if (Method->isInstance())
11730           return true;
11731       } else {
11732         // Overload set does not contain methods.
11733         break;
11734       }
11735     }
11736 
11737     return false;
11738   }
11739 
11740   return false;
11741 }
11742 
11743 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11744                               UnaryOperatorKind Opc, Expr *Input) {
11745   // First things first: handle placeholders so that the
11746   // overloaded-operator check considers the right type.
11747   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11748     // Increment and decrement of pseudo-object references.
11749     if (pty->getKind() == BuiltinType::PseudoObject &&
11750         UnaryOperator::isIncrementDecrementOp(Opc))
11751       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11752 
11753     // extension is always a builtin operator.
11754     if (Opc == UO_Extension)
11755       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11756 
11757     // & gets special logic for several kinds of placeholder.
11758     // The builtin code knows what to do.
11759     if (Opc == UO_AddrOf &&
11760         (pty->getKind() == BuiltinType::Overload ||
11761          pty->getKind() == BuiltinType::UnknownAny ||
11762          pty->getKind() == BuiltinType::BoundMember))
11763       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11764 
11765     // Anything else needs to be handled now.
11766     ExprResult Result = CheckPlaceholderExpr(Input);
11767     if (Result.isInvalid()) return ExprError();
11768     Input = Result.get();
11769   }
11770 
11771   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11772       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11773       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11774     // Find all of the overloaded operators visible from this
11775     // point. We perform both an operator-name lookup from the local
11776     // scope and an argument-dependent lookup based on the types of
11777     // the arguments.
11778     UnresolvedSet<16> Functions;
11779     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11780     if (S && OverOp != OO_None)
11781       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11782                                    Functions);
11783 
11784     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11785   }
11786 
11787   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11788 }
11789 
11790 // Unary Operators.  'Tok' is the token for the operator.
11791 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11792                               tok::TokenKind Op, Expr *Input) {
11793   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11794 }
11795 
11796 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11797 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11798                                 LabelDecl *TheDecl) {
11799   TheDecl->markUsed(Context);
11800   // Create the AST node.  The address of a label always has type 'void*'.
11801   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11802                                      Context.getPointerType(Context.VoidTy));
11803 }
11804 
11805 /// Given the last statement in a statement-expression, check whether
11806 /// the result is a producing expression (like a call to an
11807 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11808 /// release out of the full-expression.  Otherwise, return null.
11809 /// Cannot fail.
11810 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11811   // Should always be wrapped with one of these.
11812   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11813   if (!cleanups) return nullptr;
11814 
11815   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11816   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11817     return nullptr;
11818 
11819   // Splice out the cast.  This shouldn't modify any interesting
11820   // features of the statement.
11821   Expr *producer = cast->getSubExpr();
11822   assert(producer->getType() == cast->getType());
11823   assert(producer->getValueKind() == cast->getValueKind());
11824   cleanups->setSubExpr(producer);
11825   return cleanups;
11826 }
11827 
11828 void Sema::ActOnStartStmtExpr() {
11829   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11830 }
11831 
11832 void Sema::ActOnStmtExprError() {
11833   // Note that function is also called by TreeTransform when leaving a
11834   // StmtExpr scope without rebuilding anything.
11835 
11836   DiscardCleanupsInEvaluationContext();
11837   PopExpressionEvaluationContext();
11838 }
11839 
11840 ExprResult
11841 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11842                     SourceLocation RPLoc) { // "({..})"
11843   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11844   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11845 
11846   if (hasAnyUnrecoverableErrorsInThisFunction())
11847     DiscardCleanupsInEvaluationContext();
11848   assert(!Cleanup.exprNeedsCleanups() &&
11849          "cleanups within StmtExpr not correctly bound!");
11850   PopExpressionEvaluationContext();
11851 
11852   // FIXME: there are a variety of strange constraints to enforce here, for
11853   // example, it is not possible to goto into a stmt expression apparently.
11854   // More semantic analysis is needed.
11855 
11856   // If there are sub-stmts in the compound stmt, take the type of the last one
11857   // as the type of the stmtexpr.
11858   QualType Ty = Context.VoidTy;
11859   bool StmtExprMayBindToTemp = false;
11860   if (!Compound->body_empty()) {
11861     Stmt *LastStmt = Compound->body_back();
11862     LabelStmt *LastLabelStmt = nullptr;
11863     // If LastStmt is a label, skip down through into the body.
11864     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11865       LastLabelStmt = Label;
11866       LastStmt = Label->getSubStmt();
11867     }
11868 
11869     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11870       // Do function/array conversion on the last expression, but not
11871       // lvalue-to-rvalue.  However, initialize an unqualified type.
11872       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11873       if (LastExpr.isInvalid())
11874         return ExprError();
11875       Ty = LastExpr.get()->getType().getUnqualifiedType();
11876 
11877       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11878         // In ARC, if the final expression ends in a consume, splice
11879         // the consume out and bind it later.  In the alternate case
11880         // (when dealing with a retainable type), the result
11881         // initialization will create a produce.  In both cases the
11882         // result will be +1, and we'll need to balance that out with
11883         // a bind.
11884         if (Expr *rebuiltLastStmt
11885               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11886           LastExpr = rebuiltLastStmt;
11887         } else {
11888           LastExpr = PerformCopyInitialization(
11889                             InitializedEntity::InitializeResult(LPLoc,
11890                                                                 Ty,
11891                                                                 false),
11892                                                    SourceLocation(),
11893                                                LastExpr);
11894         }
11895 
11896         if (LastExpr.isInvalid())
11897           return ExprError();
11898         if (LastExpr.get() != nullptr) {
11899           if (!LastLabelStmt)
11900             Compound->setLastStmt(LastExpr.get());
11901           else
11902             LastLabelStmt->setSubStmt(LastExpr.get());
11903           StmtExprMayBindToTemp = true;
11904         }
11905       }
11906     }
11907   }
11908 
11909   // FIXME: Check that expression type is complete/non-abstract; statement
11910   // expressions are not lvalues.
11911   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11912   if (StmtExprMayBindToTemp)
11913     return MaybeBindToTemporary(ResStmtExpr);
11914   return ResStmtExpr;
11915 }
11916 
11917 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11918                                       TypeSourceInfo *TInfo,
11919                                       ArrayRef<OffsetOfComponent> Components,
11920                                       SourceLocation RParenLoc) {
11921   QualType ArgTy = TInfo->getType();
11922   bool Dependent = ArgTy->isDependentType();
11923   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11924 
11925   // We must have at least one component that refers to the type, and the first
11926   // one is known to be a field designator.  Verify that the ArgTy represents
11927   // a struct/union/class.
11928   if (!Dependent && !ArgTy->isRecordType())
11929     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11930                        << ArgTy << TypeRange);
11931 
11932   // Type must be complete per C99 7.17p3 because a declaring a variable
11933   // with an incomplete type would be ill-formed.
11934   if (!Dependent
11935       && RequireCompleteType(BuiltinLoc, ArgTy,
11936                              diag::err_offsetof_incomplete_type, TypeRange))
11937     return ExprError();
11938 
11939   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11940   // GCC extension, diagnose them.
11941   // FIXME: This diagnostic isn't actually visible because the location is in
11942   // a system header!
11943   if (Components.size() != 1)
11944     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11945       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11946 
11947   bool DidWarnAboutNonPOD = false;
11948   QualType CurrentType = ArgTy;
11949   SmallVector<OffsetOfNode, 4> Comps;
11950   SmallVector<Expr*, 4> Exprs;
11951   for (const OffsetOfComponent &OC : Components) {
11952     if (OC.isBrackets) {
11953       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11954       if (!CurrentType->isDependentType()) {
11955         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11956         if(!AT)
11957           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11958                            << CurrentType);
11959         CurrentType = AT->getElementType();
11960       } else
11961         CurrentType = Context.DependentTy;
11962 
11963       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11964       if (IdxRval.isInvalid())
11965         return ExprError();
11966       Expr *Idx = IdxRval.get();
11967 
11968       // The expression must be an integral expression.
11969       // FIXME: An integral constant expression?
11970       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11971           !Idx->getType()->isIntegerType())
11972         return ExprError(Diag(Idx->getLocStart(),
11973                               diag::err_typecheck_subscript_not_integer)
11974                          << Idx->getSourceRange());
11975 
11976       // Record this array index.
11977       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11978       Exprs.push_back(Idx);
11979       continue;
11980     }
11981 
11982     // Offset of a field.
11983     if (CurrentType->isDependentType()) {
11984       // We have the offset of a field, but we can't look into the dependent
11985       // type. Just record the identifier of the field.
11986       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11987       CurrentType = Context.DependentTy;
11988       continue;
11989     }
11990 
11991     // We need to have a complete type to look into.
11992     if (RequireCompleteType(OC.LocStart, CurrentType,
11993                             diag::err_offsetof_incomplete_type))
11994       return ExprError();
11995 
11996     // Look for the designated field.
11997     const RecordType *RC = CurrentType->getAs<RecordType>();
11998     if (!RC)
11999       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12000                        << CurrentType);
12001     RecordDecl *RD = RC->getDecl();
12002 
12003     // C++ [lib.support.types]p5:
12004     //   The macro offsetof accepts a restricted set of type arguments in this
12005     //   International Standard. type shall be a POD structure or a POD union
12006     //   (clause 9).
12007     // C++11 [support.types]p4:
12008     //   If type is not a standard-layout class (Clause 9), the results are
12009     //   undefined.
12010     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12011       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12012       unsigned DiagID =
12013         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12014                             : diag::ext_offsetof_non_pod_type;
12015 
12016       if (!IsSafe && !DidWarnAboutNonPOD &&
12017           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12018                               PDiag(DiagID)
12019                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12020                               << CurrentType))
12021         DidWarnAboutNonPOD = true;
12022     }
12023 
12024     // Look for the field.
12025     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12026     LookupQualifiedName(R, RD);
12027     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12028     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12029     if (!MemberDecl) {
12030       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12031         MemberDecl = IndirectMemberDecl->getAnonField();
12032     }
12033 
12034     if (!MemberDecl)
12035       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12036                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12037                                                               OC.LocEnd));
12038 
12039     // C99 7.17p3:
12040     //   (If the specified member is a bit-field, the behavior is undefined.)
12041     //
12042     // We diagnose this as an error.
12043     if (MemberDecl->isBitField()) {
12044       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12045         << MemberDecl->getDeclName()
12046         << SourceRange(BuiltinLoc, RParenLoc);
12047       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12048       return ExprError();
12049     }
12050 
12051     RecordDecl *Parent = MemberDecl->getParent();
12052     if (IndirectMemberDecl)
12053       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12054 
12055     // If the member was found in a base class, introduce OffsetOfNodes for
12056     // the base class indirections.
12057     CXXBasePaths Paths;
12058     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12059                       Paths)) {
12060       if (Paths.getDetectedVirtual()) {
12061         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12062           << MemberDecl->getDeclName()
12063           << SourceRange(BuiltinLoc, RParenLoc);
12064         return ExprError();
12065       }
12066 
12067       CXXBasePath &Path = Paths.front();
12068       for (const CXXBasePathElement &B : Path)
12069         Comps.push_back(OffsetOfNode(B.Base));
12070     }
12071 
12072     if (IndirectMemberDecl) {
12073       for (auto *FI : IndirectMemberDecl->chain()) {
12074         assert(isa<FieldDecl>(FI));
12075         Comps.push_back(OffsetOfNode(OC.LocStart,
12076                                      cast<FieldDecl>(FI), OC.LocEnd));
12077       }
12078     } else
12079       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12080 
12081     CurrentType = MemberDecl->getType().getNonReferenceType();
12082   }
12083 
12084   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12085                               Comps, Exprs, RParenLoc);
12086 }
12087 
12088 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12089                                       SourceLocation BuiltinLoc,
12090                                       SourceLocation TypeLoc,
12091                                       ParsedType ParsedArgTy,
12092                                       ArrayRef<OffsetOfComponent> Components,
12093                                       SourceLocation RParenLoc) {
12094 
12095   TypeSourceInfo *ArgTInfo;
12096   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12097   if (ArgTy.isNull())
12098     return ExprError();
12099 
12100   if (!ArgTInfo)
12101     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12102 
12103   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12104 }
12105 
12106 
12107 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12108                                  Expr *CondExpr,
12109                                  Expr *LHSExpr, Expr *RHSExpr,
12110                                  SourceLocation RPLoc) {
12111   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12112 
12113   ExprValueKind VK = VK_RValue;
12114   ExprObjectKind OK = OK_Ordinary;
12115   QualType resType;
12116   bool ValueDependent = false;
12117   bool CondIsTrue = false;
12118   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12119     resType = Context.DependentTy;
12120     ValueDependent = true;
12121   } else {
12122     // The conditional expression is required to be a constant expression.
12123     llvm::APSInt condEval(32);
12124     ExprResult CondICE
12125       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12126           diag::err_typecheck_choose_expr_requires_constant, false);
12127     if (CondICE.isInvalid())
12128       return ExprError();
12129     CondExpr = CondICE.get();
12130     CondIsTrue = condEval.getZExtValue();
12131 
12132     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12133     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12134 
12135     resType = ActiveExpr->getType();
12136     ValueDependent = ActiveExpr->isValueDependent();
12137     VK = ActiveExpr->getValueKind();
12138     OK = ActiveExpr->getObjectKind();
12139   }
12140 
12141   return new (Context)
12142       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12143                  CondIsTrue, resType->isDependentType(), ValueDependent);
12144 }
12145 
12146 //===----------------------------------------------------------------------===//
12147 // Clang Extensions.
12148 //===----------------------------------------------------------------------===//
12149 
12150 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12151 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12152   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12153 
12154   if (LangOpts.CPlusPlus) {
12155     Decl *ManglingContextDecl;
12156     if (MangleNumberingContext *MCtx =
12157             getCurrentMangleNumberContext(Block->getDeclContext(),
12158                                           ManglingContextDecl)) {
12159       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12160       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12161     }
12162   }
12163 
12164   PushBlockScope(CurScope, Block);
12165   CurContext->addDecl(Block);
12166   if (CurScope)
12167     PushDeclContext(CurScope, Block);
12168   else
12169     CurContext = Block;
12170 
12171   getCurBlock()->HasImplicitReturnType = true;
12172 
12173   // Enter a new evaluation context to insulate the block from any
12174   // cleanups from the enclosing full-expression.
12175   PushExpressionEvaluationContext(PotentiallyEvaluated);
12176 }
12177 
12178 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12179                                Scope *CurScope) {
12180   assert(ParamInfo.getIdentifier() == nullptr &&
12181          "block-id should have no identifier!");
12182   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12183   BlockScopeInfo *CurBlock = getCurBlock();
12184 
12185   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12186   QualType T = Sig->getType();
12187 
12188   // FIXME: We should allow unexpanded parameter packs here, but that would,
12189   // in turn, make the block expression contain unexpanded parameter packs.
12190   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12191     // Drop the parameters.
12192     FunctionProtoType::ExtProtoInfo EPI;
12193     EPI.HasTrailingReturn = false;
12194     EPI.TypeQuals |= DeclSpec::TQ_const;
12195     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12196     Sig = Context.getTrivialTypeSourceInfo(T);
12197   }
12198 
12199   // GetTypeForDeclarator always produces a function type for a block
12200   // literal signature.  Furthermore, it is always a FunctionProtoType
12201   // unless the function was written with a typedef.
12202   assert(T->isFunctionType() &&
12203          "GetTypeForDeclarator made a non-function block signature");
12204 
12205   // Look for an explicit signature in that function type.
12206   FunctionProtoTypeLoc ExplicitSignature;
12207 
12208   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12209   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12210 
12211     // Check whether that explicit signature was synthesized by
12212     // GetTypeForDeclarator.  If so, don't save that as part of the
12213     // written signature.
12214     if (ExplicitSignature.getLocalRangeBegin() ==
12215         ExplicitSignature.getLocalRangeEnd()) {
12216       // This would be much cheaper if we stored TypeLocs instead of
12217       // TypeSourceInfos.
12218       TypeLoc Result = ExplicitSignature.getReturnLoc();
12219       unsigned Size = Result.getFullDataSize();
12220       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12221       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12222 
12223       ExplicitSignature = FunctionProtoTypeLoc();
12224     }
12225   }
12226 
12227   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12228   CurBlock->FunctionType = T;
12229 
12230   const FunctionType *Fn = T->getAs<FunctionType>();
12231   QualType RetTy = Fn->getReturnType();
12232   bool isVariadic =
12233     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12234 
12235   CurBlock->TheDecl->setIsVariadic(isVariadic);
12236 
12237   // Context.DependentTy is used as a placeholder for a missing block
12238   // return type.  TODO:  what should we do with declarators like:
12239   //   ^ * { ... }
12240   // If the answer is "apply template argument deduction"....
12241   if (RetTy != Context.DependentTy) {
12242     CurBlock->ReturnType = RetTy;
12243     CurBlock->TheDecl->setBlockMissingReturnType(false);
12244     CurBlock->HasImplicitReturnType = false;
12245   }
12246 
12247   // Push block parameters from the declarator if we had them.
12248   SmallVector<ParmVarDecl*, 8> Params;
12249   if (ExplicitSignature) {
12250     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12251       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12252       if (Param->getIdentifier() == nullptr &&
12253           !Param->isImplicit() &&
12254           !Param->isInvalidDecl() &&
12255           !getLangOpts().CPlusPlus)
12256         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12257       Params.push_back(Param);
12258     }
12259 
12260   // Fake up parameter variables if we have a typedef, like
12261   //   ^ fntype { ... }
12262   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12263     for (const auto &I : Fn->param_types()) {
12264       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12265           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12266       Params.push_back(Param);
12267     }
12268   }
12269 
12270   // Set the parameters on the block decl.
12271   if (!Params.empty()) {
12272     CurBlock->TheDecl->setParams(Params);
12273     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12274                              /*CheckParameterNames=*/false);
12275   }
12276 
12277   // Finally we can process decl attributes.
12278   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12279 
12280   // Put the parameter variables in scope.
12281   for (auto AI : CurBlock->TheDecl->parameters()) {
12282     AI->setOwningFunction(CurBlock->TheDecl);
12283 
12284     // If this has an identifier, add it to the scope stack.
12285     if (AI->getIdentifier()) {
12286       CheckShadow(CurBlock->TheScope, AI);
12287 
12288       PushOnScopeChains(AI, CurBlock->TheScope);
12289     }
12290   }
12291 }
12292 
12293 /// ActOnBlockError - If there is an error parsing a block, this callback
12294 /// is invoked to pop the information about the block from the action impl.
12295 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12296   // Leave the expression-evaluation context.
12297   DiscardCleanupsInEvaluationContext();
12298   PopExpressionEvaluationContext();
12299 
12300   // Pop off CurBlock, handle nested blocks.
12301   PopDeclContext();
12302   PopFunctionScopeInfo();
12303 }
12304 
12305 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12306 /// literal was successfully completed.  ^(int x){...}
12307 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12308                                     Stmt *Body, Scope *CurScope) {
12309   // If blocks are disabled, emit an error.
12310   if (!LangOpts.Blocks)
12311     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12312 
12313   // Leave the expression-evaluation context.
12314   if (hasAnyUnrecoverableErrorsInThisFunction())
12315     DiscardCleanupsInEvaluationContext();
12316   assert(!Cleanup.exprNeedsCleanups() &&
12317          "cleanups within block not correctly bound!");
12318   PopExpressionEvaluationContext();
12319 
12320   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12321 
12322   if (BSI->HasImplicitReturnType)
12323     deduceClosureReturnType(*BSI);
12324 
12325   PopDeclContext();
12326 
12327   QualType RetTy = Context.VoidTy;
12328   if (!BSI->ReturnType.isNull())
12329     RetTy = BSI->ReturnType;
12330 
12331   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12332   QualType BlockTy;
12333 
12334   // Set the captured variables on the block.
12335   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12336   SmallVector<BlockDecl::Capture, 4> Captures;
12337   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12338     if (Cap.isThisCapture())
12339       continue;
12340     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12341                               Cap.isNested(), Cap.getInitExpr());
12342     Captures.push_back(NewCap);
12343   }
12344   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12345 
12346   // If the user wrote a function type in some form, try to use that.
12347   if (!BSI->FunctionType.isNull()) {
12348     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12349 
12350     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12351     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12352 
12353     // Turn protoless block types into nullary block types.
12354     if (isa<FunctionNoProtoType>(FTy)) {
12355       FunctionProtoType::ExtProtoInfo EPI;
12356       EPI.ExtInfo = Ext;
12357       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12358 
12359     // Otherwise, if we don't need to change anything about the function type,
12360     // preserve its sugar structure.
12361     } else if (FTy->getReturnType() == RetTy &&
12362                (!NoReturn || FTy->getNoReturnAttr())) {
12363       BlockTy = BSI->FunctionType;
12364 
12365     // Otherwise, make the minimal modifications to the function type.
12366     } else {
12367       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12368       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12369       EPI.TypeQuals = 0; // FIXME: silently?
12370       EPI.ExtInfo = Ext;
12371       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12372     }
12373 
12374   // If we don't have a function type, just build one from nothing.
12375   } else {
12376     FunctionProtoType::ExtProtoInfo EPI;
12377     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12378     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12379   }
12380 
12381   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12382   BlockTy = Context.getBlockPointerType(BlockTy);
12383 
12384   // If needed, diagnose invalid gotos and switches in the block.
12385   if (getCurFunction()->NeedsScopeChecking() &&
12386       !PP.isCodeCompletionEnabled())
12387     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12388 
12389   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12390 
12391   // Try to apply the named return value optimization. We have to check again
12392   // if we can do this, though, because blocks keep return statements around
12393   // to deduce an implicit return type.
12394   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12395       !BSI->TheDecl->isDependentContext())
12396     computeNRVO(Body, BSI);
12397 
12398   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12399   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12400   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12401 
12402   // If the block isn't obviously global, i.e. it captures anything at
12403   // all, then we need to do a few things in the surrounding context:
12404   if (Result->getBlockDecl()->hasCaptures()) {
12405     // First, this expression has a new cleanup object.
12406     ExprCleanupObjects.push_back(Result->getBlockDecl());
12407     Cleanup.setExprNeedsCleanups(true);
12408 
12409     // It also gets a branch-protected scope if any of the captured
12410     // variables needs destruction.
12411     for (const auto &CI : Result->getBlockDecl()->captures()) {
12412       const VarDecl *var = CI.getVariable();
12413       if (var->getType().isDestructedType() != QualType::DK_none) {
12414         getCurFunction()->setHasBranchProtectedScope();
12415         break;
12416       }
12417     }
12418   }
12419 
12420   return Result;
12421 }
12422 
12423 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12424                             SourceLocation RPLoc) {
12425   TypeSourceInfo *TInfo;
12426   GetTypeFromParser(Ty, &TInfo);
12427   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12428 }
12429 
12430 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12431                                 Expr *E, TypeSourceInfo *TInfo,
12432                                 SourceLocation RPLoc) {
12433   Expr *OrigExpr = E;
12434   bool IsMS = false;
12435 
12436   // CUDA device code does not support varargs.
12437   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12438     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12439       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12440       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12441         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12442     }
12443   }
12444 
12445   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12446   // as Microsoft ABI on an actual Microsoft platform, where
12447   // __builtin_ms_va_list and __builtin_va_list are the same.)
12448   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12449       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12450     QualType MSVaListType = Context.getBuiltinMSVaListType();
12451     if (Context.hasSameType(MSVaListType, E->getType())) {
12452       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12453         return ExprError();
12454       IsMS = true;
12455     }
12456   }
12457 
12458   // Get the va_list type
12459   QualType VaListType = Context.getBuiltinVaListType();
12460   if (!IsMS) {
12461     if (VaListType->isArrayType()) {
12462       // Deal with implicit array decay; for example, on x86-64,
12463       // va_list is an array, but it's supposed to decay to
12464       // a pointer for va_arg.
12465       VaListType = Context.getArrayDecayedType(VaListType);
12466       // Make sure the input expression also decays appropriately.
12467       ExprResult Result = UsualUnaryConversions(E);
12468       if (Result.isInvalid())
12469         return ExprError();
12470       E = Result.get();
12471     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12472       // If va_list is a record type and we are compiling in C++ mode,
12473       // check the argument using reference binding.
12474       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12475           Context, Context.getLValueReferenceType(VaListType), false);
12476       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12477       if (Init.isInvalid())
12478         return ExprError();
12479       E = Init.getAs<Expr>();
12480     } else {
12481       // Otherwise, the va_list argument must be an l-value because
12482       // it is modified by va_arg.
12483       if (!E->isTypeDependent() &&
12484           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12485         return ExprError();
12486     }
12487   }
12488 
12489   if (!IsMS && !E->isTypeDependent() &&
12490       !Context.hasSameType(VaListType, E->getType()))
12491     return ExprError(Diag(E->getLocStart(),
12492                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12493       << OrigExpr->getType() << E->getSourceRange());
12494 
12495   if (!TInfo->getType()->isDependentType()) {
12496     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12497                             diag::err_second_parameter_to_va_arg_incomplete,
12498                             TInfo->getTypeLoc()))
12499       return ExprError();
12500 
12501     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12502                                TInfo->getType(),
12503                                diag::err_second_parameter_to_va_arg_abstract,
12504                                TInfo->getTypeLoc()))
12505       return ExprError();
12506 
12507     if (!TInfo->getType().isPODType(Context)) {
12508       Diag(TInfo->getTypeLoc().getBeginLoc(),
12509            TInfo->getType()->isObjCLifetimeType()
12510              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12511              : diag::warn_second_parameter_to_va_arg_not_pod)
12512         << TInfo->getType()
12513         << TInfo->getTypeLoc().getSourceRange();
12514     }
12515 
12516     // Check for va_arg where arguments of the given type will be promoted
12517     // (i.e. this va_arg is guaranteed to have undefined behavior).
12518     QualType PromoteType;
12519     if (TInfo->getType()->isPromotableIntegerType()) {
12520       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12521       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12522         PromoteType = QualType();
12523     }
12524     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12525       PromoteType = Context.DoubleTy;
12526     if (!PromoteType.isNull())
12527       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12528                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12529                           << TInfo->getType()
12530                           << PromoteType
12531                           << TInfo->getTypeLoc().getSourceRange());
12532   }
12533 
12534   QualType T = TInfo->getType().getNonLValueExprType(Context);
12535   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12536 }
12537 
12538 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12539   // The type of __null will be int or long, depending on the size of
12540   // pointers on the target.
12541   QualType Ty;
12542   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12543   if (pw == Context.getTargetInfo().getIntWidth())
12544     Ty = Context.IntTy;
12545   else if (pw == Context.getTargetInfo().getLongWidth())
12546     Ty = Context.LongTy;
12547   else if (pw == Context.getTargetInfo().getLongLongWidth())
12548     Ty = Context.LongLongTy;
12549   else {
12550     llvm_unreachable("I don't know size of pointer!");
12551   }
12552 
12553   return new (Context) GNUNullExpr(Ty, TokenLoc);
12554 }
12555 
12556 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12557                                               bool Diagnose) {
12558   if (!getLangOpts().ObjC1)
12559     return false;
12560 
12561   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12562   if (!PT)
12563     return false;
12564 
12565   if (!PT->isObjCIdType()) {
12566     // Check if the destination is the 'NSString' interface.
12567     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12568     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12569       return false;
12570   }
12571 
12572   // Ignore any parens, implicit casts (should only be
12573   // array-to-pointer decays), and not-so-opaque values.  The last is
12574   // important for making this trigger for property assignments.
12575   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12576   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12577     if (OV->getSourceExpr())
12578       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12579 
12580   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12581   if (!SL || !SL->isAscii())
12582     return false;
12583   if (Diagnose) {
12584     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12585       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12586     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12587   }
12588   return true;
12589 }
12590 
12591 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12592                                               const Expr *SrcExpr) {
12593   if (!DstType->isFunctionPointerType() ||
12594       !SrcExpr->getType()->isFunctionType())
12595     return false;
12596 
12597   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12598   if (!DRE)
12599     return false;
12600 
12601   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12602   if (!FD)
12603     return false;
12604 
12605   return !S.checkAddressOfFunctionIsAvailable(FD,
12606                                               /*Complain=*/true,
12607                                               SrcExpr->getLocStart());
12608 }
12609 
12610 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12611                                     SourceLocation Loc,
12612                                     QualType DstType, QualType SrcType,
12613                                     Expr *SrcExpr, AssignmentAction Action,
12614                                     bool *Complained) {
12615   if (Complained)
12616     *Complained = false;
12617 
12618   // Decode the result (notice that AST's are still created for extensions).
12619   bool CheckInferredResultType = false;
12620   bool isInvalid = false;
12621   unsigned DiagKind = 0;
12622   FixItHint Hint;
12623   ConversionFixItGenerator ConvHints;
12624   bool MayHaveConvFixit = false;
12625   bool MayHaveFunctionDiff = false;
12626   const ObjCInterfaceDecl *IFace = nullptr;
12627   const ObjCProtocolDecl *PDecl = nullptr;
12628 
12629   switch (ConvTy) {
12630   case Compatible:
12631       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12632       return false;
12633 
12634   case PointerToInt:
12635     DiagKind = diag::ext_typecheck_convert_pointer_int;
12636     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12637     MayHaveConvFixit = true;
12638     break;
12639   case IntToPointer:
12640     DiagKind = diag::ext_typecheck_convert_int_pointer;
12641     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12642     MayHaveConvFixit = true;
12643     break;
12644   case IncompatiblePointer:
12645     if (Action == AA_Passing_CFAudited)
12646       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12647     else if (SrcType->isFunctionPointerType() &&
12648              DstType->isFunctionPointerType())
12649       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12650     else
12651       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12652 
12653     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12654       SrcType->isObjCObjectPointerType();
12655     if (Hint.isNull() && !CheckInferredResultType) {
12656       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12657     }
12658     else if (CheckInferredResultType) {
12659       SrcType = SrcType.getUnqualifiedType();
12660       DstType = DstType.getUnqualifiedType();
12661     }
12662     MayHaveConvFixit = true;
12663     break;
12664   case IncompatiblePointerSign:
12665     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12666     break;
12667   case FunctionVoidPointer:
12668     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12669     break;
12670   case IncompatiblePointerDiscardsQualifiers: {
12671     // Perform array-to-pointer decay if necessary.
12672     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12673 
12674     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12675     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12676     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12677       DiagKind = diag::err_typecheck_incompatible_address_space;
12678       break;
12679 
12680 
12681     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12682       DiagKind = diag::err_typecheck_incompatible_ownership;
12683       break;
12684     }
12685 
12686     llvm_unreachable("unknown error case for discarding qualifiers!");
12687     // fallthrough
12688   }
12689   case CompatiblePointerDiscardsQualifiers:
12690     // If the qualifiers lost were because we were applying the
12691     // (deprecated) C++ conversion from a string literal to a char*
12692     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12693     // Ideally, this check would be performed in
12694     // checkPointerTypesForAssignment. However, that would require a
12695     // bit of refactoring (so that the second argument is an
12696     // expression, rather than a type), which should be done as part
12697     // of a larger effort to fix checkPointerTypesForAssignment for
12698     // C++ semantics.
12699     if (getLangOpts().CPlusPlus &&
12700         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12701       return false;
12702     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12703     break;
12704   case IncompatibleNestedPointerQualifiers:
12705     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12706     break;
12707   case IntToBlockPointer:
12708     DiagKind = diag::err_int_to_block_pointer;
12709     break;
12710   case IncompatibleBlockPointer:
12711     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12712     break;
12713   case IncompatibleObjCQualifiedId: {
12714     if (SrcType->isObjCQualifiedIdType()) {
12715       const ObjCObjectPointerType *srcOPT =
12716                 SrcType->getAs<ObjCObjectPointerType>();
12717       for (auto *srcProto : srcOPT->quals()) {
12718         PDecl = srcProto;
12719         break;
12720       }
12721       if (const ObjCInterfaceType *IFaceT =
12722             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12723         IFace = IFaceT->getDecl();
12724     }
12725     else if (DstType->isObjCQualifiedIdType()) {
12726       const ObjCObjectPointerType *dstOPT =
12727         DstType->getAs<ObjCObjectPointerType>();
12728       for (auto *dstProto : dstOPT->quals()) {
12729         PDecl = dstProto;
12730         break;
12731       }
12732       if (const ObjCInterfaceType *IFaceT =
12733             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12734         IFace = IFaceT->getDecl();
12735     }
12736     DiagKind = diag::warn_incompatible_qualified_id;
12737     break;
12738   }
12739   case IncompatibleVectors:
12740     DiagKind = diag::warn_incompatible_vectors;
12741     break;
12742   case IncompatibleObjCWeakRef:
12743     DiagKind = diag::err_arc_weak_unavailable_assign;
12744     break;
12745   case Incompatible:
12746     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12747       if (Complained)
12748         *Complained = true;
12749       return true;
12750     }
12751 
12752     DiagKind = diag::err_typecheck_convert_incompatible;
12753     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12754     MayHaveConvFixit = true;
12755     isInvalid = true;
12756     MayHaveFunctionDiff = true;
12757     break;
12758   }
12759 
12760   QualType FirstType, SecondType;
12761   switch (Action) {
12762   case AA_Assigning:
12763   case AA_Initializing:
12764     // The destination type comes first.
12765     FirstType = DstType;
12766     SecondType = SrcType;
12767     break;
12768 
12769   case AA_Returning:
12770   case AA_Passing:
12771   case AA_Passing_CFAudited:
12772   case AA_Converting:
12773   case AA_Sending:
12774   case AA_Casting:
12775     // The source type comes first.
12776     FirstType = SrcType;
12777     SecondType = DstType;
12778     break;
12779   }
12780 
12781   PartialDiagnostic FDiag = PDiag(DiagKind);
12782   if (Action == AA_Passing_CFAudited)
12783     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12784   else
12785     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12786 
12787   // If we can fix the conversion, suggest the FixIts.
12788   assert(ConvHints.isNull() || Hint.isNull());
12789   if (!ConvHints.isNull()) {
12790     for (FixItHint &H : ConvHints.Hints)
12791       FDiag << H;
12792   } else {
12793     FDiag << Hint;
12794   }
12795   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12796 
12797   if (MayHaveFunctionDiff)
12798     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12799 
12800   Diag(Loc, FDiag);
12801   if (DiagKind == diag::warn_incompatible_qualified_id &&
12802       PDecl && IFace && !IFace->hasDefinition())
12803       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12804         << IFace->getName() << PDecl->getName();
12805 
12806   if (SecondType == Context.OverloadTy)
12807     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12808                               FirstType, /*TakingAddress=*/true);
12809 
12810   if (CheckInferredResultType)
12811     EmitRelatedResultTypeNote(SrcExpr);
12812 
12813   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12814     EmitRelatedResultTypeNoteForReturn(DstType);
12815 
12816   if (Complained)
12817     *Complained = true;
12818   return isInvalid;
12819 }
12820 
12821 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12822                                                  llvm::APSInt *Result) {
12823   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12824   public:
12825     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12826       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12827     }
12828   } Diagnoser;
12829 
12830   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12831 }
12832 
12833 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12834                                                  llvm::APSInt *Result,
12835                                                  unsigned DiagID,
12836                                                  bool AllowFold) {
12837   class IDDiagnoser : public VerifyICEDiagnoser {
12838     unsigned DiagID;
12839 
12840   public:
12841     IDDiagnoser(unsigned DiagID)
12842       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12843 
12844     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12845       S.Diag(Loc, DiagID) << SR;
12846     }
12847   } Diagnoser(DiagID);
12848 
12849   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12850 }
12851 
12852 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12853                                             SourceRange SR) {
12854   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12855 }
12856 
12857 ExprResult
12858 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12859                                       VerifyICEDiagnoser &Diagnoser,
12860                                       bool AllowFold) {
12861   SourceLocation DiagLoc = E->getLocStart();
12862 
12863   if (getLangOpts().CPlusPlus11) {
12864     // C++11 [expr.const]p5:
12865     //   If an expression of literal class type is used in a context where an
12866     //   integral constant expression is required, then that class type shall
12867     //   have a single non-explicit conversion function to an integral or
12868     //   unscoped enumeration type
12869     ExprResult Converted;
12870     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12871     public:
12872       CXX11ConvertDiagnoser(bool Silent)
12873           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12874                                 Silent, true) {}
12875 
12876       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12877                                            QualType T) override {
12878         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12879       }
12880 
12881       SemaDiagnosticBuilder diagnoseIncomplete(
12882           Sema &S, SourceLocation Loc, QualType T) override {
12883         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12884       }
12885 
12886       SemaDiagnosticBuilder diagnoseExplicitConv(
12887           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12888         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12889       }
12890 
12891       SemaDiagnosticBuilder noteExplicitConv(
12892           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12893         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12894                  << ConvTy->isEnumeralType() << ConvTy;
12895       }
12896 
12897       SemaDiagnosticBuilder diagnoseAmbiguous(
12898           Sema &S, SourceLocation Loc, QualType T) override {
12899         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12900       }
12901 
12902       SemaDiagnosticBuilder noteAmbiguous(
12903           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12904         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12905                  << ConvTy->isEnumeralType() << ConvTy;
12906       }
12907 
12908       SemaDiagnosticBuilder diagnoseConversion(
12909           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12910         llvm_unreachable("conversion functions are permitted");
12911       }
12912     } ConvertDiagnoser(Diagnoser.Suppress);
12913 
12914     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12915                                                     ConvertDiagnoser);
12916     if (Converted.isInvalid())
12917       return Converted;
12918     E = Converted.get();
12919     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12920       return ExprError();
12921   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12922     // An ICE must be of integral or unscoped enumeration type.
12923     if (!Diagnoser.Suppress)
12924       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12925     return ExprError();
12926   }
12927 
12928   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12929   // in the non-ICE case.
12930   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12931     if (Result)
12932       *Result = E->EvaluateKnownConstInt(Context);
12933     return E;
12934   }
12935 
12936   Expr::EvalResult EvalResult;
12937   SmallVector<PartialDiagnosticAt, 8> Notes;
12938   EvalResult.Diag = &Notes;
12939 
12940   // Try to evaluate the expression, and produce diagnostics explaining why it's
12941   // not a constant expression as a side-effect.
12942   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12943                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12944 
12945   // In C++11, we can rely on diagnostics being produced for any expression
12946   // which is not a constant expression. If no diagnostics were produced, then
12947   // this is a constant expression.
12948   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12949     if (Result)
12950       *Result = EvalResult.Val.getInt();
12951     return E;
12952   }
12953 
12954   // If our only note is the usual "invalid subexpression" note, just point
12955   // the caret at its location rather than producing an essentially
12956   // redundant note.
12957   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12958         diag::note_invalid_subexpr_in_const_expr) {
12959     DiagLoc = Notes[0].first;
12960     Notes.clear();
12961   }
12962 
12963   if (!Folded || !AllowFold) {
12964     if (!Diagnoser.Suppress) {
12965       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12966       for (const PartialDiagnosticAt &Note : Notes)
12967         Diag(Note.first, Note.second);
12968     }
12969 
12970     return ExprError();
12971   }
12972 
12973   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12974   for (const PartialDiagnosticAt &Note : Notes)
12975     Diag(Note.first, Note.second);
12976 
12977   if (Result)
12978     *Result = EvalResult.Val.getInt();
12979   return E;
12980 }
12981 
12982 namespace {
12983   // Handle the case where we conclude a expression which we speculatively
12984   // considered to be unevaluated is actually evaluated.
12985   class TransformToPE : public TreeTransform<TransformToPE> {
12986     typedef TreeTransform<TransformToPE> BaseTransform;
12987 
12988   public:
12989     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12990 
12991     // Make sure we redo semantic analysis
12992     bool AlwaysRebuild() { return true; }
12993 
12994     // Make sure we handle LabelStmts correctly.
12995     // FIXME: This does the right thing, but maybe we need a more general
12996     // fix to TreeTransform?
12997     StmtResult TransformLabelStmt(LabelStmt *S) {
12998       S->getDecl()->setStmt(nullptr);
12999       return BaseTransform::TransformLabelStmt(S);
13000     }
13001 
13002     // We need to special-case DeclRefExprs referring to FieldDecls which
13003     // are not part of a member pointer formation; normal TreeTransforming
13004     // doesn't catch this case because of the way we represent them in the AST.
13005     // FIXME: This is a bit ugly; is it really the best way to handle this
13006     // case?
13007     //
13008     // Error on DeclRefExprs referring to FieldDecls.
13009     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13010       if (isa<FieldDecl>(E->getDecl()) &&
13011           !SemaRef.isUnevaluatedContext())
13012         return SemaRef.Diag(E->getLocation(),
13013                             diag::err_invalid_non_static_member_use)
13014             << E->getDecl() << E->getSourceRange();
13015 
13016       return BaseTransform::TransformDeclRefExpr(E);
13017     }
13018 
13019     // Exception: filter out member pointer formation
13020     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13021       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13022         return E;
13023 
13024       return BaseTransform::TransformUnaryOperator(E);
13025     }
13026 
13027     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13028       // Lambdas never need to be transformed.
13029       return E;
13030     }
13031   };
13032 }
13033 
13034 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13035   assert(isUnevaluatedContext() &&
13036          "Should only transform unevaluated expressions");
13037   ExprEvalContexts.back().Context =
13038       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13039   if (isUnevaluatedContext())
13040     return E;
13041   return TransformToPE(*this).TransformExpr(E);
13042 }
13043 
13044 void
13045 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13046                                       Decl *LambdaContextDecl,
13047                                       bool IsDecltype) {
13048   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13049                                 LambdaContextDecl, IsDecltype);
13050   Cleanup.reset();
13051   if (!MaybeODRUseExprs.empty())
13052     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13053 }
13054 
13055 void
13056 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13057                                       ReuseLambdaContextDecl_t,
13058                                       bool IsDecltype) {
13059   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13060   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13061 }
13062 
13063 void Sema::PopExpressionEvaluationContext() {
13064   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13065   unsigned NumTypos = Rec.NumTypos;
13066 
13067   if (!Rec.Lambdas.empty()) {
13068     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13069       unsigned D;
13070       if (Rec.isUnevaluated()) {
13071         // C++11 [expr.prim.lambda]p2:
13072         //   A lambda-expression shall not appear in an unevaluated operand
13073         //   (Clause 5).
13074         D = diag::err_lambda_unevaluated_operand;
13075       } else {
13076         // C++1y [expr.const]p2:
13077         //   A conditional-expression e is a core constant expression unless the
13078         //   evaluation of e, following the rules of the abstract machine, would
13079         //   evaluate [...] a lambda-expression.
13080         D = diag::err_lambda_in_constant_expression;
13081       }
13082       for (const auto *L : Rec.Lambdas)
13083         Diag(L->getLocStart(), D);
13084     } else {
13085       // Mark the capture expressions odr-used. This was deferred
13086       // during lambda expression creation.
13087       for (auto *Lambda : Rec.Lambdas) {
13088         for (auto *C : Lambda->capture_inits())
13089           MarkDeclarationsReferencedInExpr(C);
13090       }
13091     }
13092   }
13093 
13094   // When are coming out of an unevaluated context, clear out any
13095   // temporaries that we may have created as part of the evaluation of
13096   // the expression in that context: they aren't relevant because they
13097   // will never be constructed.
13098   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13099     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13100                              ExprCleanupObjects.end());
13101     Cleanup = Rec.ParentCleanup;
13102     CleanupVarDeclMarking();
13103     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13104   // Otherwise, merge the contexts together.
13105   } else {
13106     Cleanup.mergeFrom(Rec.ParentCleanup);
13107     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13108                             Rec.SavedMaybeODRUseExprs.end());
13109   }
13110 
13111   // Pop the current expression evaluation context off the stack.
13112   ExprEvalContexts.pop_back();
13113 
13114   if (!ExprEvalContexts.empty())
13115     ExprEvalContexts.back().NumTypos += NumTypos;
13116   else
13117     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13118                             "last ExpressionEvaluationContextRecord");
13119 }
13120 
13121 void Sema::DiscardCleanupsInEvaluationContext() {
13122   ExprCleanupObjects.erase(
13123          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13124          ExprCleanupObjects.end());
13125   Cleanup.reset();
13126   MaybeODRUseExprs.clear();
13127 }
13128 
13129 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13130   if (!E->getType()->isVariablyModifiedType())
13131     return E;
13132   return TransformToPotentiallyEvaluated(E);
13133 }
13134 
13135 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13136   // Do not mark anything as "used" within a dependent context; wait for
13137   // an instantiation.
13138   if (SemaRef.CurContext->isDependentContext())
13139     return false;
13140 
13141   switch (SemaRef.ExprEvalContexts.back().Context) {
13142     case Sema::Unevaluated:
13143     case Sema::UnevaluatedAbstract:
13144       // We are in an expression that is not potentially evaluated; do nothing.
13145       // (Depending on how you read the standard, we actually do need to do
13146       // something here for null pointer constants, but the standard's
13147       // definition of a null pointer constant is completely crazy.)
13148       return false;
13149 
13150     case Sema::DiscardedStatement:
13151       // These are technically a potentially evaluated but they have the effect
13152       // of suppressing use marking.
13153       return false;
13154 
13155     case Sema::ConstantEvaluated:
13156     case Sema::PotentiallyEvaluated:
13157       // We are in a potentially evaluated expression (or a constant-expression
13158       // in C++03); we need to do implicit template instantiation, implicitly
13159       // define class members, and mark most declarations as used.
13160       return true;
13161 
13162     case Sema::PotentiallyEvaluatedIfUsed:
13163       // Referenced declarations will only be used if the construct in the
13164       // containing expression is used.
13165       return false;
13166   }
13167   llvm_unreachable("Invalid context");
13168 }
13169 
13170 /// \brief Mark a function referenced, and check whether it is odr-used
13171 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13172 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13173                                   bool MightBeOdrUse) {
13174   assert(Func && "No function?");
13175 
13176   Func->setReferenced();
13177 
13178   // C++11 [basic.def.odr]p3:
13179   //   A function whose name appears as a potentially-evaluated expression is
13180   //   odr-used if it is the unique lookup result or the selected member of a
13181   //   set of overloaded functions [...].
13182   //
13183   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13184   // can just check that here.
13185   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13186 
13187   // Determine whether we require a function definition to exist, per
13188   // C++11 [temp.inst]p3:
13189   //   Unless a function template specialization has been explicitly
13190   //   instantiated or explicitly specialized, the function template
13191   //   specialization is implicitly instantiated when the specialization is
13192   //   referenced in a context that requires a function definition to exist.
13193   //
13194   // We consider constexpr function templates to be referenced in a context
13195   // that requires a definition to exist whenever they are referenced.
13196   //
13197   // FIXME: This instantiates constexpr functions too frequently. If this is
13198   // really an unevaluated context (and we're not just in the definition of a
13199   // function template or overload resolution or other cases which we
13200   // incorrectly consider to be unevaluated contexts), and we're not in a
13201   // subexpression which we actually need to evaluate (for instance, a
13202   // template argument, array bound or an expression in a braced-init-list),
13203   // we are not permitted to instantiate this constexpr function definition.
13204   //
13205   // FIXME: This also implicitly defines special members too frequently. They
13206   // are only supposed to be implicitly defined if they are odr-used, but they
13207   // are not odr-used from constant expressions in unevaluated contexts.
13208   // However, they cannot be referenced if they are deleted, and they are
13209   // deleted whenever the implicit definition of the special member would
13210   // fail (with very few exceptions).
13211   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13212   bool NeedDefinition =
13213       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13214                                          (MD && !MD->isUserProvided())));
13215 
13216   // C++14 [temp.expl.spec]p6:
13217   //   If a template [...] is explicitly specialized then that specialization
13218   //   shall be declared before the first use of that specialization that would
13219   //   cause an implicit instantiation to take place, in every translation unit
13220   //   in which such a use occurs
13221   if (NeedDefinition &&
13222       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13223        Func->getMemberSpecializationInfo()))
13224     checkSpecializationVisibility(Loc, Func);
13225 
13226   // C++14 [except.spec]p17:
13227   //   An exception-specification is considered to be needed when:
13228   //   - the function is odr-used or, if it appears in an unevaluated operand,
13229   //     would be odr-used if the expression were potentially-evaluated;
13230   //
13231   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13232   // function is a pure virtual function we're calling, and in that case the
13233   // function was selected by overload resolution and we need to resolve its
13234   // exception specification for a different reason.
13235   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13236   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13237     ResolveExceptionSpec(Loc, FPT);
13238 
13239   // If we don't need to mark the function as used, and we don't need to
13240   // try to provide a definition, there's nothing more to do.
13241   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13242       (!NeedDefinition || Func->getBody()))
13243     return;
13244 
13245   // Note that this declaration has been used.
13246   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13247     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13248     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13249       if (Constructor->isDefaultConstructor()) {
13250         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13251           return;
13252         DefineImplicitDefaultConstructor(Loc, Constructor);
13253       } else if (Constructor->isCopyConstructor()) {
13254         DefineImplicitCopyConstructor(Loc, Constructor);
13255       } else if (Constructor->isMoveConstructor()) {
13256         DefineImplicitMoveConstructor(Loc, Constructor);
13257       }
13258     } else if (Constructor->getInheritedConstructor()) {
13259       DefineInheritingConstructor(Loc, Constructor);
13260     }
13261   } else if (CXXDestructorDecl *Destructor =
13262                  dyn_cast<CXXDestructorDecl>(Func)) {
13263     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13264     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13265       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13266         return;
13267       DefineImplicitDestructor(Loc, Destructor);
13268     }
13269     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13270       MarkVTableUsed(Loc, Destructor->getParent());
13271   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13272     if (MethodDecl->isOverloadedOperator() &&
13273         MethodDecl->getOverloadedOperator() == OO_Equal) {
13274       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13275       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13276         if (MethodDecl->isCopyAssignmentOperator())
13277           DefineImplicitCopyAssignment(Loc, MethodDecl);
13278         else if (MethodDecl->isMoveAssignmentOperator())
13279           DefineImplicitMoveAssignment(Loc, MethodDecl);
13280       }
13281     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13282                MethodDecl->getParent()->isLambda()) {
13283       CXXConversionDecl *Conversion =
13284           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13285       if (Conversion->isLambdaToBlockPointerConversion())
13286         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13287       else
13288         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13289     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13290       MarkVTableUsed(Loc, MethodDecl->getParent());
13291   }
13292 
13293   // Recursive functions should be marked when used from another function.
13294   // FIXME: Is this really right?
13295   if (CurContext == Func) return;
13296 
13297   // Implicit instantiation of function templates and member functions of
13298   // class templates.
13299   if (Func->isImplicitlyInstantiable()) {
13300     bool AlreadyInstantiated = false;
13301     SourceLocation PointOfInstantiation = Loc;
13302     if (FunctionTemplateSpecializationInfo *SpecInfo
13303                               = Func->getTemplateSpecializationInfo()) {
13304       if (SpecInfo->getPointOfInstantiation().isInvalid())
13305         SpecInfo->setPointOfInstantiation(Loc);
13306       else if (SpecInfo->getTemplateSpecializationKind()
13307                  == TSK_ImplicitInstantiation) {
13308         AlreadyInstantiated = true;
13309         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13310       }
13311     } else if (MemberSpecializationInfo *MSInfo
13312                                 = Func->getMemberSpecializationInfo()) {
13313       if (MSInfo->getPointOfInstantiation().isInvalid())
13314         MSInfo->setPointOfInstantiation(Loc);
13315       else if (MSInfo->getTemplateSpecializationKind()
13316                  == TSK_ImplicitInstantiation) {
13317         AlreadyInstantiated = true;
13318         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13319       }
13320     }
13321 
13322     if (!AlreadyInstantiated || Func->isConstexpr()) {
13323       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13324           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13325           ActiveTemplateInstantiations.size())
13326         PendingLocalImplicitInstantiations.push_back(
13327             std::make_pair(Func, PointOfInstantiation));
13328       else if (Func->isConstexpr())
13329         // Do not defer instantiations of constexpr functions, to avoid the
13330         // expression evaluator needing to call back into Sema if it sees a
13331         // call to such a function.
13332         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13333       else {
13334         PendingInstantiations.push_back(std::make_pair(Func,
13335                                                        PointOfInstantiation));
13336         // Notify the consumer that a function was implicitly instantiated.
13337         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13338       }
13339     }
13340   } else {
13341     // Walk redefinitions, as some of them may be instantiable.
13342     for (auto i : Func->redecls()) {
13343       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13344         MarkFunctionReferenced(Loc, i, OdrUse);
13345     }
13346   }
13347 
13348   if (!OdrUse) return;
13349 
13350   // Keep track of used but undefined functions.
13351   if (!Func->isDefined()) {
13352     if (mightHaveNonExternalLinkage(Func))
13353       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13354     else if (Func->getMostRecentDecl()->isInlined() &&
13355              !LangOpts.GNUInline &&
13356              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13357       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13358   }
13359 
13360   Func->markUsed(Context);
13361 }
13362 
13363 static void
13364 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13365                                    ValueDecl *var, DeclContext *DC) {
13366   DeclContext *VarDC = var->getDeclContext();
13367 
13368   //  If the parameter still belongs to the translation unit, then
13369   //  we're actually just using one parameter in the declaration of
13370   //  the next.
13371   if (isa<ParmVarDecl>(var) &&
13372       isa<TranslationUnitDecl>(VarDC))
13373     return;
13374 
13375   // For C code, don't diagnose about capture if we're not actually in code
13376   // right now; it's impossible to write a non-constant expression outside of
13377   // function context, so we'll get other (more useful) diagnostics later.
13378   //
13379   // For C++, things get a bit more nasty... it would be nice to suppress this
13380   // diagnostic for certain cases like using a local variable in an array bound
13381   // for a member of a local class, but the correct predicate is not obvious.
13382   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13383     return;
13384 
13385   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13386   unsigned ContextKind = 3; // unknown
13387   if (isa<CXXMethodDecl>(VarDC) &&
13388       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13389     ContextKind = 2;
13390   } else if (isa<FunctionDecl>(VarDC)) {
13391     ContextKind = 0;
13392   } else if (isa<BlockDecl>(VarDC)) {
13393     ContextKind = 1;
13394   }
13395 
13396   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13397     << var << ValueKind << ContextKind << VarDC;
13398   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13399       << var;
13400 
13401   // FIXME: Add additional diagnostic info about class etc. which prevents
13402   // capture.
13403 }
13404 
13405 
13406 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13407                                       bool &SubCapturesAreNested,
13408                                       QualType &CaptureType,
13409                                       QualType &DeclRefType) {
13410    // Check whether we've already captured it.
13411   if (CSI->CaptureMap.count(Var)) {
13412     // If we found a capture, any subcaptures are nested.
13413     SubCapturesAreNested = true;
13414 
13415     // Retrieve the capture type for this variable.
13416     CaptureType = CSI->getCapture(Var).getCaptureType();
13417 
13418     // Compute the type of an expression that refers to this variable.
13419     DeclRefType = CaptureType.getNonReferenceType();
13420 
13421     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13422     // are mutable in the sense that user can change their value - they are
13423     // private instances of the captured declarations.
13424     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13425     if (Cap.isCopyCapture() &&
13426         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13427         !(isa<CapturedRegionScopeInfo>(CSI) &&
13428           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13429       DeclRefType.addConst();
13430     return true;
13431   }
13432   return false;
13433 }
13434 
13435 // Only block literals, captured statements, and lambda expressions can
13436 // capture; other scopes don't work.
13437 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13438                                  SourceLocation Loc,
13439                                  const bool Diagnose, Sema &S) {
13440   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13441     return getLambdaAwareParentOfDeclContext(DC);
13442   else if (Var->hasLocalStorage()) {
13443     if (Diagnose)
13444        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13445   }
13446   return nullptr;
13447 }
13448 
13449 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13450 // certain types of variables (unnamed, variably modified types etc.)
13451 // so check for eligibility.
13452 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13453                                  SourceLocation Loc,
13454                                  const bool Diagnose, Sema &S) {
13455 
13456   bool IsBlock = isa<BlockScopeInfo>(CSI);
13457   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13458 
13459   // Lambdas are not allowed to capture unnamed variables
13460   // (e.g. anonymous unions).
13461   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13462   // assuming that's the intent.
13463   if (IsLambda && !Var->getDeclName()) {
13464     if (Diagnose) {
13465       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13466       S.Diag(Var->getLocation(), diag::note_declared_at);
13467     }
13468     return false;
13469   }
13470 
13471   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13472   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13473     if (Diagnose) {
13474       S.Diag(Loc, diag::err_ref_vm_type);
13475       S.Diag(Var->getLocation(), diag::note_previous_decl)
13476         << Var->getDeclName();
13477     }
13478     return false;
13479   }
13480   // Prohibit structs with flexible array members too.
13481   // We cannot capture what is in the tail end of the struct.
13482   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13483     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13484       if (Diagnose) {
13485         if (IsBlock)
13486           S.Diag(Loc, diag::err_ref_flexarray_type);
13487         else
13488           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13489             << Var->getDeclName();
13490         S.Diag(Var->getLocation(), diag::note_previous_decl)
13491           << Var->getDeclName();
13492       }
13493       return false;
13494     }
13495   }
13496   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13497   // Lambdas and captured statements are not allowed to capture __block
13498   // variables; they don't support the expected semantics.
13499   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13500     if (Diagnose) {
13501       S.Diag(Loc, diag::err_capture_block_variable)
13502         << Var->getDeclName() << !IsLambda;
13503       S.Diag(Var->getLocation(), diag::note_previous_decl)
13504         << Var->getDeclName();
13505     }
13506     return false;
13507   }
13508 
13509   return true;
13510 }
13511 
13512 // Returns true if the capture by block was successful.
13513 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13514                                  SourceLocation Loc,
13515                                  const bool BuildAndDiagnose,
13516                                  QualType &CaptureType,
13517                                  QualType &DeclRefType,
13518                                  const bool Nested,
13519                                  Sema &S) {
13520   Expr *CopyExpr = nullptr;
13521   bool ByRef = false;
13522 
13523   // Blocks are not allowed to capture arrays.
13524   if (CaptureType->isArrayType()) {
13525     if (BuildAndDiagnose) {
13526       S.Diag(Loc, diag::err_ref_array_type);
13527       S.Diag(Var->getLocation(), diag::note_previous_decl)
13528       << Var->getDeclName();
13529     }
13530     return false;
13531   }
13532 
13533   // Forbid the block-capture of autoreleasing variables.
13534   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13535     if (BuildAndDiagnose) {
13536       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13537         << /*block*/ 0;
13538       S.Diag(Var->getLocation(), diag::note_previous_decl)
13539         << Var->getDeclName();
13540     }
13541     return false;
13542   }
13543 
13544   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13545   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13546     QualType PointeeTy = PT->getPointeeType();
13547     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13548         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13549         !isa<AttributedType>(PointeeTy)) {
13550       if (BuildAndDiagnose) {
13551         SourceLocation VarLoc = Var->getLocation();
13552         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13553         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13554             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13555         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13556       }
13557     }
13558   }
13559 
13560   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13561   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13562       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13563     // Block capture by reference does not change the capture or
13564     // declaration reference types.
13565     ByRef = true;
13566   } else {
13567     // Block capture by copy introduces 'const'.
13568     CaptureType = CaptureType.getNonReferenceType().withConst();
13569     DeclRefType = CaptureType;
13570 
13571     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13572       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13573         // The capture logic needs the destructor, so make sure we mark it.
13574         // Usually this is unnecessary because most local variables have
13575         // their destructors marked at declaration time, but parameters are
13576         // an exception because it's technically only the call site that
13577         // actually requires the destructor.
13578         if (isa<ParmVarDecl>(Var))
13579           S.FinalizeVarWithDestructor(Var, Record);
13580 
13581         // Enter a new evaluation context to insulate the copy
13582         // full-expression.
13583         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13584 
13585         // According to the blocks spec, the capture of a variable from
13586         // the stack requires a const copy constructor.  This is not true
13587         // of the copy/move done to move a __block variable to the heap.
13588         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13589                                                   DeclRefType.withConst(),
13590                                                   VK_LValue, Loc);
13591 
13592         ExprResult Result
13593           = S.PerformCopyInitialization(
13594               InitializedEntity::InitializeBlock(Var->getLocation(),
13595                                                   CaptureType, false),
13596               Loc, DeclRef);
13597 
13598         // Build a full-expression copy expression if initialization
13599         // succeeded and used a non-trivial constructor.  Recover from
13600         // errors by pretending that the copy isn't necessary.
13601         if (!Result.isInvalid() &&
13602             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13603                 ->isTrivial()) {
13604           Result = S.MaybeCreateExprWithCleanups(Result);
13605           CopyExpr = Result.get();
13606         }
13607       }
13608     }
13609   }
13610 
13611   // Actually capture the variable.
13612   if (BuildAndDiagnose)
13613     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13614                     SourceLocation(), CaptureType, CopyExpr);
13615 
13616   return true;
13617 
13618 }
13619 
13620 
13621 /// \brief Capture the given variable in the captured region.
13622 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13623                                     VarDecl *Var,
13624                                     SourceLocation Loc,
13625                                     const bool BuildAndDiagnose,
13626                                     QualType &CaptureType,
13627                                     QualType &DeclRefType,
13628                                     const bool RefersToCapturedVariable,
13629                                     Sema &S) {
13630   // By default, capture variables by reference.
13631   bool ByRef = true;
13632   // Using an LValue reference type is consistent with Lambdas (see below).
13633   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13634     if (S.IsOpenMPCapturedDecl(Var))
13635       DeclRefType = DeclRefType.getUnqualifiedType();
13636     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13637   }
13638 
13639   if (ByRef)
13640     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13641   else
13642     CaptureType = DeclRefType;
13643 
13644   Expr *CopyExpr = nullptr;
13645   if (BuildAndDiagnose) {
13646     // The current implementation assumes that all variables are captured
13647     // by references. Since there is no capture by copy, no expression
13648     // evaluation will be needed.
13649     RecordDecl *RD = RSI->TheRecordDecl;
13650 
13651     FieldDecl *Field
13652       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13653                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13654                           nullptr, false, ICIS_NoInit);
13655     Field->setImplicit(true);
13656     Field->setAccess(AS_private);
13657     RD->addDecl(Field);
13658 
13659     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13660                                             DeclRefType, VK_LValue, Loc);
13661     Var->setReferenced(true);
13662     Var->markUsed(S.Context);
13663   }
13664 
13665   // Actually capture the variable.
13666   if (BuildAndDiagnose)
13667     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13668                     SourceLocation(), CaptureType, CopyExpr);
13669 
13670 
13671   return true;
13672 }
13673 
13674 /// \brief Create a field within the lambda class for the variable
13675 /// being captured.
13676 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13677                                     QualType FieldType, QualType DeclRefType,
13678                                     SourceLocation Loc,
13679                                     bool RefersToCapturedVariable) {
13680   CXXRecordDecl *Lambda = LSI->Lambda;
13681 
13682   // Build the non-static data member.
13683   FieldDecl *Field
13684     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13685                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13686                         nullptr, false, ICIS_NoInit);
13687   Field->setImplicit(true);
13688   Field->setAccess(AS_private);
13689   Lambda->addDecl(Field);
13690 }
13691 
13692 /// \brief Capture the given variable in the lambda.
13693 static bool captureInLambda(LambdaScopeInfo *LSI,
13694                             VarDecl *Var,
13695                             SourceLocation Loc,
13696                             const bool BuildAndDiagnose,
13697                             QualType &CaptureType,
13698                             QualType &DeclRefType,
13699                             const bool RefersToCapturedVariable,
13700                             const Sema::TryCaptureKind Kind,
13701                             SourceLocation EllipsisLoc,
13702                             const bool IsTopScope,
13703                             Sema &S) {
13704 
13705   // Determine whether we are capturing by reference or by value.
13706   bool ByRef = false;
13707   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13708     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13709   } else {
13710     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13711   }
13712 
13713   // Compute the type of the field that will capture this variable.
13714   if (ByRef) {
13715     // C++11 [expr.prim.lambda]p15:
13716     //   An entity is captured by reference if it is implicitly or
13717     //   explicitly captured but not captured by copy. It is
13718     //   unspecified whether additional unnamed non-static data
13719     //   members are declared in the closure type for entities
13720     //   captured by reference.
13721     //
13722     // FIXME: It is not clear whether we want to build an lvalue reference
13723     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13724     // to do the former, while EDG does the latter. Core issue 1249 will
13725     // clarify, but for now we follow GCC because it's a more permissive and
13726     // easily defensible position.
13727     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13728   } else {
13729     // C++11 [expr.prim.lambda]p14:
13730     //   For each entity captured by copy, an unnamed non-static
13731     //   data member is declared in the closure type. The
13732     //   declaration order of these members is unspecified. The type
13733     //   of such a data member is the type of the corresponding
13734     //   captured entity if the entity is not a reference to an
13735     //   object, or the referenced type otherwise. [Note: If the
13736     //   captured entity is a reference to a function, the
13737     //   corresponding data member is also a reference to a
13738     //   function. - end note ]
13739     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13740       if (!RefType->getPointeeType()->isFunctionType())
13741         CaptureType = RefType->getPointeeType();
13742     }
13743 
13744     // Forbid the lambda copy-capture of autoreleasing variables.
13745     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13746       if (BuildAndDiagnose) {
13747         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13748         S.Diag(Var->getLocation(), diag::note_previous_decl)
13749           << Var->getDeclName();
13750       }
13751       return false;
13752     }
13753 
13754     // Make sure that by-copy captures are of a complete and non-abstract type.
13755     if (BuildAndDiagnose) {
13756       if (!CaptureType->isDependentType() &&
13757           S.RequireCompleteType(Loc, CaptureType,
13758                                 diag::err_capture_of_incomplete_type,
13759                                 Var->getDeclName()))
13760         return false;
13761 
13762       if (S.RequireNonAbstractType(Loc, CaptureType,
13763                                    diag::err_capture_of_abstract_type))
13764         return false;
13765     }
13766   }
13767 
13768   // Capture this variable in the lambda.
13769   if (BuildAndDiagnose)
13770     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13771                             RefersToCapturedVariable);
13772 
13773   // Compute the type of a reference to this captured variable.
13774   if (ByRef)
13775     DeclRefType = CaptureType.getNonReferenceType();
13776   else {
13777     // C++ [expr.prim.lambda]p5:
13778     //   The closure type for a lambda-expression has a public inline
13779     //   function call operator [...]. This function call operator is
13780     //   declared const (9.3.1) if and only if the lambda-expression's
13781     //   parameter-declaration-clause is not followed by mutable.
13782     DeclRefType = CaptureType.getNonReferenceType();
13783     if (!LSI->Mutable && !CaptureType->isReferenceType())
13784       DeclRefType.addConst();
13785   }
13786 
13787   // Add the capture.
13788   if (BuildAndDiagnose)
13789     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13790                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13791 
13792   return true;
13793 }
13794 
13795 bool Sema::tryCaptureVariable(
13796     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13797     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13798     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13799   // An init-capture is notionally from the context surrounding its
13800   // declaration, but its parent DC is the lambda class.
13801   DeclContext *VarDC = Var->getDeclContext();
13802   if (Var->isInitCapture())
13803     VarDC = VarDC->getParent();
13804 
13805   DeclContext *DC = CurContext;
13806   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13807       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13808   // We need to sync up the Declaration Context with the
13809   // FunctionScopeIndexToStopAt
13810   if (FunctionScopeIndexToStopAt) {
13811     unsigned FSIndex = FunctionScopes.size() - 1;
13812     while (FSIndex != MaxFunctionScopesIndex) {
13813       DC = getLambdaAwareParentOfDeclContext(DC);
13814       --FSIndex;
13815     }
13816   }
13817 
13818 
13819   // If the variable is declared in the current context, there is no need to
13820   // capture it.
13821   if (VarDC == DC) return true;
13822 
13823   // Capture global variables if it is required to use private copy of this
13824   // variable.
13825   bool IsGlobal = !Var->hasLocalStorage();
13826   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13827     return true;
13828 
13829   // Walk up the stack to determine whether we can capture the variable,
13830   // performing the "simple" checks that don't depend on type. We stop when
13831   // we've either hit the declared scope of the variable or find an existing
13832   // capture of that variable.  We start from the innermost capturing-entity
13833   // (the DC) and ensure that all intervening capturing-entities
13834   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13835   // declcontext can either capture the variable or have already captured
13836   // the variable.
13837   CaptureType = Var->getType();
13838   DeclRefType = CaptureType.getNonReferenceType();
13839   bool Nested = false;
13840   bool Explicit = (Kind != TryCapture_Implicit);
13841   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13842   do {
13843     // Only block literals, captured statements, and lambda expressions can
13844     // capture; other scopes don't work.
13845     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13846                                                               ExprLoc,
13847                                                               BuildAndDiagnose,
13848                                                               *this);
13849     // We need to check for the parent *first* because, if we *have*
13850     // private-captured a global variable, we need to recursively capture it in
13851     // intermediate blocks, lambdas, etc.
13852     if (!ParentDC) {
13853       if (IsGlobal) {
13854         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13855         break;
13856       }
13857       return true;
13858     }
13859 
13860     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13861     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13862 
13863 
13864     // Check whether we've already captured it.
13865     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13866                                              DeclRefType))
13867       break;
13868     // If we are instantiating a generic lambda call operator body,
13869     // we do not want to capture new variables.  What was captured
13870     // during either a lambdas transformation or initial parsing
13871     // should be used.
13872     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13873       if (BuildAndDiagnose) {
13874         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13875         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13876           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13877           Diag(Var->getLocation(), diag::note_previous_decl)
13878              << Var->getDeclName();
13879           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13880         } else
13881           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13882       }
13883       return true;
13884     }
13885     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13886     // certain types of variables (unnamed, variably modified types etc.)
13887     // so check for eligibility.
13888     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13889        return true;
13890 
13891     // Try to capture variable-length arrays types.
13892     if (Var->getType()->isVariablyModifiedType()) {
13893       // We're going to walk down into the type and look for VLA
13894       // expressions.
13895       QualType QTy = Var->getType();
13896       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13897         QTy = PVD->getOriginalType();
13898       captureVariablyModifiedType(Context, QTy, CSI);
13899     }
13900 
13901     if (getLangOpts().OpenMP) {
13902       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13903         // OpenMP private variables should not be captured in outer scope, so
13904         // just break here. Similarly, global variables that are captured in a
13905         // target region should not be captured outside the scope of the region.
13906         if (RSI->CapRegionKind == CR_OpenMP) {
13907           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13908           // When we detect target captures we are looking from inside the
13909           // target region, therefore we need to propagate the capture from the
13910           // enclosing region. Therefore, the capture is not initially nested.
13911           if (IsTargetCap)
13912             FunctionScopesIndex--;
13913 
13914           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13915             Nested = !IsTargetCap;
13916             DeclRefType = DeclRefType.getUnqualifiedType();
13917             CaptureType = Context.getLValueReferenceType(DeclRefType);
13918             break;
13919           }
13920         }
13921       }
13922     }
13923     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13924       // No capture-default, and this is not an explicit capture
13925       // so cannot capture this variable.
13926       if (BuildAndDiagnose) {
13927         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13928         Diag(Var->getLocation(), diag::note_previous_decl)
13929           << Var->getDeclName();
13930         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13931           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13932                diag::note_lambda_decl);
13933         // FIXME: If we error out because an outer lambda can not implicitly
13934         // capture a variable that an inner lambda explicitly captures, we
13935         // should have the inner lambda do the explicit capture - because
13936         // it makes for cleaner diagnostics later.  This would purely be done
13937         // so that the diagnostic does not misleadingly claim that a variable
13938         // can not be captured by a lambda implicitly even though it is captured
13939         // explicitly.  Suggestion:
13940         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13941         //    at the function head
13942         //  - cache the StartingDeclContext - this must be a lambda
13943         //  - captureInLambda in the innermost lambda the variable.
13944       }
13945       return true;
13946     }
13947 
13948     FunctionScopesIndex--;
13949     DC = ParentDC;
13950     Explicit = false;
13951   } while (!VarDC->Equals(DC));
13952 
13953   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13954   // computing the type of the capture at each step, checking type-specific
13955   // requirements, and adding captures if requested.
13956   // If the variable had already been captured previously, we start capturing
13957   // at the lambda nested within that one.
13958   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13959        ++I) {
13960     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13961 
13962     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13963       if (!captureInBlock(BSI, Var, ExprLoc,
13964                           BuildAndDiagnose, CaptureType,
13965                           DeclRefType, Nested, *this))
13966         return true;
13967       Nested = true;
13968     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13969       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13970                                    BuildAndDiagnose, CaptureType,
13971                                    DeclRefType, Nested, *this))
13972         return true;
13973       Nested = true;
13974     } else {
13975       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13976       if (!captureInLambda(LSI, Var, ExprLoc,
13977                            BuildAndDiagnose, CaptureType,
13978                            DeclRefType, Nested, Kind, EllipsisLoc,
13979                             /*IsTopScope*/I == N - 1, *this))
13980         return true;
13981       Nested = true;
13982     }
13983   }
13984   return false;
13985 }
13986 
13987 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13988                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13989   QualType CaptureType;
13990   QualType DeclRefType;
13991   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13992                             /*BuildAndDiagnose=*/true, CaptureType,
13993                             DeclRefType, nullptr);
13994 }
13995 
13996 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13997   QualType CaptureType;
13998   QualType DeclRefType;
13999   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14000                              /*BuildAndDiagnose=*/false, CaptureType,
14001                              DeclRefType, nullptr);
14002 }
14003 
14004 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14005   QualType CaptureType;
14006   QualType DeclRefType;
14007 
14008   // Determine whether we can capture this variable.
14009   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14010                          /*BuildAndDiagnose=*/false, CaptureType,
14011                          DeclRefType, nullptr))
14012     return QualType();
14013 
14014   return DeclRefType;
14015 }
14016 
14017 
14018 
14019 // If either the type of the variable or the initializer is dependent,
14020 // return false. Otherwise, determine whether the variable is a constant
14021 // expression. Use this if you need to know if a variable that might or
14022 // might not be dependent is truly a constant expression.
14023 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14024     ASTContext &Context) {
14025 
14026   if (Var->getType()->isDependentType())
14027     return false;
14028   const VarDecl *DefVD = nullptr;
14029   Var->getAnyInitializer(DefVD);
14030   if (!DefVD)
14031     return false;
14032   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14033   Expr *Init = cast<Expr>(Eval->Value);
14034   if (Init->isValueDependent())
14035     return false;
14036   return IsVariableAConstantExpression(Var, Context);
14037 }
14038 
14039 
14040 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14041   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14042   // an object that satisfies the requirements for appearing in a
14043   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14044   // is immediately applied."  This function handles the lvalue-to-rvalue
14045   // conversion part.
14046   MaybeODRUseExprs.erase(E->IgnoreParens());
14047 
14048   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14049   // to a variable that is a constant expression, and if so, identify it as
14050   // a reference to a variable that does not involve an odr-use of that
14051   // variable.
14052   if (LambdaScopeInfo *LSI = getCurLambda()) {
14053     Expr *SansParensExpr = E->IgnoreParens();
14054     VarDecl *Var = nullptr;
14055     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14056       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14057     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14058       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14059 
14060     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14061       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14062   }
14063 }
14064 
14065 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14066   Res = CorrectDelayedTyposInExpr(Res);
14067 
14068   if (!Res.isUsable())
14069     return Res;
14070 
14071   // If a constant-expression is a reference to a variable where we delay
14072   // deciding whether it is an odr-use, just assume we will apply the
14073   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14074   // (a non-type template argument), we have special handling anyway.
14075   UpdateMarkingForLValueToRValue(Res.get());
14076   return Res;
14077 }
14078 
14079 void Sema::CleanupVarDeclMarking() {
14080   for (Expr *E : MaybeODRUseExprs) {
14081     VarDecl *Var;
14082     SourceLocation Loc;
14083     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14084       Var = cast<VarDecl>(DRE->getDecl());
14085       Loc = DRE->getLocation();
14086     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14087       Var = cast<VarDecl>(ME->getMemberDecl());
14088       Loc = ME->getMemberLoc();
14089     } else {
14090       llvm_unreachable("Unexpected expression");
14091     }
14092 
14093     MarkVarDeclODRUsed(Var, Loc, *this,
14094                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14095   }
14096 
14097   MaybeODRUseExprs.clear();
14098 }
14099 
14100 
14101 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14102                                     VarDecl *Var, Expr *E) {
14103   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14104          "Invalid Expr argument to DoMarkVarDeclReferenced");
14105   Var->setReferenced();
14106 
14107   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14108   bool MarkODRUsed = true;
14109 
14110   // If the context is not potentially evaluated, this is not an odr-use and
14111   // does not trigger instantiation.
14112   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
14113     if (SemaRef.isUnevaluatedContext())
14114       return;
14115 
14116     // If we don't yet know whether this context is going to end up being an
14117     // evaluated context, and we're referencing a variable from an enclosing
14118     // scope, add a potential capture.
14119     //
14120     // FIXME: Is this necessary? These contexts are only used for default
14121     // arguments, where local variables can't be used.
14122     const bool RefersToEnclosingScope =
14123         (SemaRef.CurContext != Var->getDeclContext() &&
14124          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14125     if (RefersToEnclosingScope) {
14126       if (LambdaScopeInfo *const LSI =
14127               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14128         // If a variable could potentially be odr-used, defer marking it so
14129         // until we finish analyzing the full expression for any
14130         // lvalue-to-rvalue
14131         // or discarded value conversions that would obviate odr-use.
14132         // Add it to the list of potential captures that will be analyzed
14133         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14134         // unless the variable is a reference that was initialized by a constant
14135         // expression (this will never need to be captured or odr-used).
14136         assert(E && "Capture variable should be used in an expression.");
14137         if (!Var->getType()->isReferenceType() ||
14138             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14139           LSI->addPotentialCapture(E->IgnoreParens());
14140       }
14141     }
14142 
14143     if (!isTemplateInstantiation(TSK))
14144       return;
14145 
14146     // Instantiate, but do not mark as odr-used, variable templates.
14147     MarkODRUsed = false;
14148   }
14149 
14150   VarTemplateSpecializationDecl *VarSpec =
14151       dyn_cast<VarTemplateSpecializationDecl>(Var);
14152   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14153          "Can't instantiate a partial template specialization.");
14154 
14155   // If this might be a member specialization of a static data member, check
14156   // the specialization is visible. We already did the checks for variable
14157   // template specializations when we created them.
14158   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14159     SemaRef.checkSpecializationVisibility(Loc, Var);
14160 
14161   // Perform implicit instantiation of static data members, static data member
14162   // templates of class templates, and variable template specializations. Delay
14163   // instantiations of variable templates, except for those that could be used
14164   // in a constant expression.
14165   if (isTemplateInstantiation(TSK)) {
14166     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14167 
14168     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14169       if (Var->getPointOfInstantiation().isInvalid()) {
14170         // This is a modification of an existing AST node. Notify listeners.
14171         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14172           L->StaticDataMemberInstantiated(Var);
14173       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14174         // Don't bother trying to instantiate it again, unless we might need
14175         // its initializer before we get to the end of the TU.
14176         TryInstantiating = false;
14177     }
14178 
14179     if (Var->getPointOfInstantiation().isInvalid())
14180       Var->setTemplateSpecializationKind(TSK, Loc);
14181 
14182     if (TryInstantiating) {
14183       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14184       bool InstantiationDependent = false;
14185       bool IsNonDependent =
14186           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14187                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14188                   : true;
14189 
14190       // Do not instantiate specializations that are still type-dependent.
14191       if (IsNonDependent) {
14192         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14193           // Do not defer instantiations of variables which could be used in a
14194           // constant expression.
14195           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14196         } else {
14197           SemaRef.PendingInstantiations
14198               .push_back(std::make_pair(Var, PointOfInstantiation));
14199         }
14200       }
14201     }
14202   }
14203 
14204   if (!MarkODRUsed)
14205     return;
14206 
14207   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14208   // the requirements for appearing in a constant expression (5.19) and, if
14209   // it is an object, the lvalue-to-rvalue conversion (4.1)
14210   // is immediately applied."  We check the first part here, and
14211   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14212   // Note that we use the C++11 definition everywhere because nothing in
14213   // C++03 depends on whether we get the C++03 version correct. The second
14214   // part does not apply to references, since they are not objects.
14215   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14216     // A reference initialized by a constant expression can never be
14217     // odr-used, so simply ignore it.
14218     if (!Var->getType()->isReferenceType())
14219       SemaRef.MaybeODRUseExprs.insert(E);
14220   } else
14221     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14222                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14223 }
14224 
14225 /// \brief Mark a variable referenced, and check whether it is odr-used
14226 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14227 /// used directly for normal expressions referring to VarDecl.
14228 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14229   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14230 }
14231 
14232 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14233                                Decl *D, Expr *E, bool MightBeOdrUse) {
14234   if (SemaRef.isInOpenMPDeclareTargetContext())
14235     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14236 
14237   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14238     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14239     return;
14240   }
14241 
14242   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14243 
14244   // If this is a call to a method via a cast, also mark the method in the
14245   // derived class used in case codegen can devirtualize the call.
14246   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14247   if (!ME)
14248     return;
14249   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14250   if (!MD)
14251     return;
14252   // Only attempt to devirtualize if this is truly a virtual call.
14253   bool IsVirtualCall = MD->isVirtual() &&
14254                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14255   if (!IsVirtualCall)
14256     return;
14257   const Expr *Base = ME->getBase();
14258   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14259   if (!MostDerivedClassDecl)
14260     return;
14261   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14262   if (!DM || DM->isPure())
14263     return;
14264   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14265 }
14266 
14267 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14268 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14269   // TODO: update this with DR# once a defect report is filed.
14270   // C++11 defect. The address of a pure member should not be an ODR use, even
14271   // if it's a qualified reference.
14272   bool OdrUse = true;
14273   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14274     if (Method->isVirtual())
14275       OdrUse = false;
14276   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14277 }
14278 
14279 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14280 void Sema::MarkMemberReferenced(MemberExpr *E) {
14281   // C++11 [basic.def.odr]p2:
14282   //   A non-overloaded function whose name appears as a potentially-evaluated
14283   //   expression or a member of a set of candidate functions, if selected by
14284   //   overload resolution when referred to from a potentially-evaluated
14285   //   expression, is odr-used, unless it is a pure virtual function and its
14286   //   name is not explicitly qualified.
14287   bool MightBeOdrUse = true;
14288   if (E->performsVirtualDispatch(getLangOpts())) {
14289     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14290       if (Method->isPure())
14291         MightBeOdrUse = false;
14292   }
14293   SourceLocation Loc = E->getMemberLoc().isValid() ?
14294                             E->getMemberLoc() : E->getLocStart();
14295   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14296 }
14297 
14298 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14299 /// marks the declaration referenced, and performs odr-use checking for
14300 /// functions and variables. This method should not be used when building a
14301 /// normal expression which refers to a variable.
14302 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14303                                  bool MightBeOdrUse) {
14304   if (MightBeOdrUse) {
14305     if (auto *VD = dyn_cast<VarDecl>(D)) {
14306       MarkVariableReferenced(Loc, VD);
14307       return;
14308     }
14309   }
14310   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14311     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14312     return;
14313   }
14314   D->setReferenced();
14315 }
14316 
14317 namespace {
14318   // Mark all of the declarations referenced
14319   // FIXME: Not fully implemented yet! We need to have a better understanding
14320   // of when we're entering
14321   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14322     Sema &S;
14323     SourceLocation Loc;
14324 
14325   public:
14326     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14327 
14328     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14329 
14330     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14331     bool TraverseRecordType(RecordType *T);
14332   };
14333 }
14334 
14335 bool MarkReferencedDecls::TraverseTemplateArgument(
14336     const TemplateArgument &Arg) {
14337   if (Arg.getKind() == TemplateArgument::Declaration) {
14338     if (Decl *D = Arg.getAsDecl())
14339       S.MarkAnyDeclReferenced(Loc, D, true);
14340   }
14341 
14342   return Inherited::TraverseTemplateArgument(Arg);
14343 }
14344 
14345 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14346   if (ClassTemplateSpecializationDecl *Spec
14347                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14348     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14349     return TraverseTemplateArguments(Args.data(), Args.size());
14350   }
14351 
14352   return true;
14353 }
14354 
14355 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14356   MarkReferencedDecls Marker(*this, Loc);
14357   Marker.TraverseType(Context.getCanonicalType(T));
14358 }
14359 
14360 namespace {
14361   /// \brief Helper class that marks all of the declarations referenced by
14362   /// potentially-evaluated subexpressions as "referenced".
14363   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14364     Sema &S;
14365     bool SkipLocalVariables;
14366 
14367   public:
14368     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14369 
14370     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14371       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14372 
14373     void VisitDeclRefExpr(DeclRefExpr *E) {
14374       // If we were asked not to visit local variables, don't.
14375       if (SkipLocalVariables) {
14376         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14377           if (VD->hasLocalStorage())
14378             return;
14379       }
14380 
14381       S.MarkDeclRefReferenced(E);
14382     }
14383 
14384     void VisitMemberExpr(MemberExpr *E) {
14385       S.MarkMemberReferenced(E);
14386       Inherited::VisitMemberExpr(E);
14387     }
14388 
14389     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14390       S.MarkFunctionReferenced(E->getLocStart(),
14391             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14392       Visit(E->getSubExpr());
14393     }
14394 
14395     void VisitCXXNewExpr(CXXNewExpr *E) {
14396       if (E->getOperatorNew())
14397         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14398       if (E->getOperatorDelete())
14399         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14400       Inherited::VisitCXXNewExpr(E);
14401     }
14402 
14403     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14404       if (E->getOperatorDelete())
14405         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14406       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14407       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14408         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14409         S.MarkFunctionReferenced(E->getLocStart(),
14410                                     S.LookupDestructor(Record));
14411       }
14412 
14413       Inherited::VisitCXXDeleteExpr(E);
14414     }
14415 
14416     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14417       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14418       Inherited::VisitCXXConstructExpr(E);
14419     }
14420 
14421     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14422       Visit(E->getExpr());
14423     }
14424 
14425     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14426       Inherited::VisitImplicitCastExpr(E);
14427 
14428       if (E->getCastKind() == CK_LValueToRValue)
14429         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14430     }
14431   };
14432 }
14433 
14434 /// \brief Mark any declarations that appear within this expression or any
14435 /// potentially-evaluated subexpressions as "referenced".
14436 ///
14437 /// \param SkipLocalVariables If true, don't mark local variables as
14438 /// 'referenced'.
14439 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14440                                             bool SkipLocalVariables) {
14441   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14442 }
14443 
14444 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14445 /// of the program being compiled.
14446 ///
14447 /// This routine emits the given diagnostic when the code currently being
14448 /// type-checked is "potentially evaluated", meaning that there is a
14449 /// possibility that the code will actually be executable. Code in sizeof()
14450 /// expressions, code used only during overload resolution, etc., are not
14451 /// potentially evaluated. This routine will suppress such diagnostics or,
14452 /// in the absolutely nutty case of potentially potentially evaluated
14453 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14454 /// later.
14455 ///
14456 /// This routine should be used for all diagnostics that describe the run-time
14457 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14458 /// Failure to do so will likely result in spurious diagnostics or failures
14459 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14460 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14461                                const PartialDiagnostic &PD) {
14462   switch (ExprEvalContexts.back().Context) {
14463   case Unevaluated:
14464   case UnevaluatedAbstract:
14465   case DiscardedStatement:
14466     // The argument will never be evaluated, so don't complain.
14467     break;
14468 
14469   case ConstantEvaluated:
14470     // Relevant diagnostics should be produced by constant evaluation.
14471     break;
14472 
14473   case PotentiallyEvaluated:
14474   case PotentiallyEvaluatedIfUsed:
14475     if (Statement && getCurFunctionOrMethodDecl()) {
14476       FunctionScopes.back()->PossiblyUnreachableDiags.
14477         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14478     }
14479     else
14480       Diag(Loc, PD);
14481 
14482     return true;
14483   }
14484 
14485   return false;
14486 }
14487 
14488 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14489                                CallExpr *CE, FunctionDecl *FD) {
14490   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14491     return false;
14492 
14493   // If we're inside a decltype's expression, don't check for a valid return
14494   // type or construct temporaries until we know whether this is the last call.
14495   if (ExprEvalContexts.back().IsDecltype) {
14496     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14497     return false;
14498   }
14499 
14500   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14501     FunctionDecl *FD;
14502     CallExpr *CE;
14503 
14504   public:
14505     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14506       : FD(FD), CE(CE) { }
14507 
14508     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14509       if (!FD) {
14510         S.Diag(Loc, diag::err_call_incomplete_return)
14511           << T << CE->getSourceRange();
14512         return;
14513       }
14514 
14515       S.Diag(Loc, diag::err_call_function_incomplete_return)
14516         << CE->getSourceRange() << FD->getDeclName() << T;
14517       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14518           << FD->getDeclName();
14519     }
14520   } Diagnoser(FD, CE);
14521 
14522   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14523     return true;
14524 
14525   return false;
14526 }
14527 
14528 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14529 // will prevent this condition from triggering, which is what we want.
14530 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14531   SourceLocation Loc;
14532 
14533   unsigned diagnostic = diag::warn_condition_is_assignment;
14534   bool IsOrAssign = false;
14535 
14536   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14537     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14538       return;
14539 
14540     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14541 
14542     // Greylist some idioms by putting them into a warning subcategory.
14543     if (ObjCMessageExpr *ME
14544           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14545       Selector Sel = ME->getSelector();
14546 
14547       // self = [<foo> init...]
14548       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14549         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14550 
14551       // <foo> = [<bar> nextObject]
14552       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14553         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14554     }
14555 
14556     Loc = Op->getOperatorLoc();
14557   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14558     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14559       return;
14560 
14561     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14562     Loc = Op->getOperatorLoc();
14563   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14564     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14565   else {
14566     // Not an assignment.
14567     return;
14568   }
14569 
14570   Diag(Loc, diagnostic) << E->getSourceRange();
14571 
14572   SourceLocation Open = E->getLocStart();
14573   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14574   Diag(Loc, diag::note_condition_assign_silence)
14575         << FixItHint::CreateInsertion(Open, "(")
14576         << FixItHint::CreateInsertion(Close, ")");
14577 
14578   if (IsOrAssign)
14579     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14580       << FixItHint::CreateReplacement(Loc, "!=");
14581   else
14582     Diag(Loc, diag::note_condition_assign_to_comparison)
14583       << FixItHint::CreateReplacement(Loc, "==");
14584 }
14585 
14586 /// \brief Redundant parentheses over an equality comparison can indicate
14587 /// that the user intended an assignment used as condition.
14588 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14589   // Don't warn if the parens came from a macro.
14590   SourceLocation parenLoc = ParenE->getLocStart();
14591   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14592     return;
14593   // Don't warn for dependent expressions.
14594   if (ParenE->isTypeDependent())
14595     return;
14596 
14597   Expr *E = ParenE->IgnoreParens();
14598 
14599   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14600     if (opE->getOpcode() == BO_EQ &&
14601         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14602                                                            == Expr::MLV_Valid) {
14603       SourceLocation Loc = opE->getOperatorLoc();
14604 
14605       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14606       SourceRange ParenERange = ParenE->getSourceRange();
14607       Diag(Loc, diag::note_equality_comparison_silence)
14608         << FixItHint::CreateRemoval(ParenERange.getBegin())
14609         << FixItHint::CreateRemoval(ParenERange.getEnd());
14610       Diag(Loc, diag::note_equality_comparison_to_assign)
14611         << FixItHint::CreateReplacement(Loc, "=");
14612     }
14613 }
14614 
14615 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14616                                        bool IsConstexpr) {
14617   DiagnoseAssignmentAsCondition(E);
14618   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14619     DiagnoseEqualityWithExtraParens(parenE);
14620 
14621   ExprResult result = CheckPlaceholderExpr(E);
14622   if (result.isInvalid()) return ExprError();
14623   E = result.get();
14624 
14625   if (!E->isTypeDependent()) {
14626     if (getLangOpts().CPlusPlus)
14627       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14628 
14629     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14630     if (ERes.isInvalid())
14631       return ExprError();
14632     E = ERes.get();
14633 
14634     QualType T = E->getType();
14635     if (!T->isScalarType()) { // C99 6.8.4.1p1
14636       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14637         << T << E->getSourceRange();
14638       return ExprError();
14639     }
14640     CheckBoolLikeConversion(E, Loc);
14641   }
14642 
14643   return E;
14644 }
14645 
14646 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14647                                            Expr *SubExpr, ConditionKind CK) {
14648   // Empty conditions are valid in for-statements.
14649   if (!SubExpr)
14650     return ConditionResult();
14651 
14652   ExprResult Cond;
14653   switch (CK) {
14654   case ConditionKind::Boolean:
14655     Cond = CheckBooleanCondition(Loc, SubExpr);
14656     break;
14657 
14658   case ConditionKind::ConstexprIf:
14659     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14660     break;
14661 
14662   case ConditionKind::Switch:
14663     Cond = CheckSwitchCondition(Loc, SubExpr);
14664     break;
14665   }
14666   if (Cond.isInvalid())
14667     return ConditionError();
14668 
14669   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14670   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14671   if (!FullExpr.get())
14672     return ConditionError();
14673 
14674   return ConditionResult(*this, nullptr, FullExpr,
14675                          CK == ConditionKind::ConstexprIf);
14676 }
14677 
14678 namespace {
14679   /// A visitor for rebuilding a call to an __unknown_any expression
14680   /// to have an appropriate type.
14681   struct RebuildUnknownAnyFunction
14682     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14683 
14684     Sema &S;
14685 
14686     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14687 
14688     ExprResult VisitStmt(Stmt *S) {
14689       llvm_unreachable("unexpected statement!");
14690     }
14691 
14692     ExprResult VisitExpr(Expr *E) {
14693       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14694         << E->getSourceRange();
14695       return ExprError();
14696     }
14697 
14698     /// Rebuild an expression which simply semantically wraps another
14699     /// expression which it shares the type and value kind of.
14700     template <class T> ExprResult rebuildSugarExpr(T *E) {
14701       ExprResult SubResult = Visit(E->getSubExpr());
14702       if (SubResult.isInvalid()) return ExprError();
14703 
14704       Expr *SubExpr = SubResult.get();
14705       E->setSubExpr(SubExpr);
14706       E->setType(SubExpr->getType());
14707       E->setValueKind(SubExpr->getValueKind());
14708       assert(E->getObjectKind() == OK_Ordinary);
14709       return E;
14710     }
14711 
14712     ExprResult VisitParenExpr(ParenExpr *E) {
14713       return rebuildSugarExpr(E);
14714     }
14715 
14716     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14717       return rebuildSugarExpr(E);
14718     }
14719 
14720     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14721       ExprResult SubResult = Visit(E->getSubExpr());
14722       if (SubResult.isInvalid()) return ExprError();
14723 
14724       Expr *SubExpr = SubResult.get();
14725       E->setSubExpr(SubExpr);
14726       E->setType(S.Context.getPointerType(SubExpr->getType()));
14727       assert(E->getValueKind() == VK_RValue);
14728       assert(E->getObjectKind() == OK_Ordinary);
14729       return E;
14730     }
14731 
14732     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14733       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14734 
14735       E->setType(VD->getType());
14736 
14737       assert(E->getValueKind() == VK_RValue);
14738       if (S.getLangOpts().CPlusPlus &&
14739           !(isa<CXXMethodDecl>(VD) &&
14740             cast<CXXMethodDecl>(VD)->isInstance()))
14741         E->setValueKind(VK_LValue);
14742 
14743       return E;
14744     }
14745 
14746     ExprResult VisitMemberExpr(MemberExpr *E) {
14747       return resolveDecl(E, E->getMemberDecl());
14748     }
14749 
14750     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14751       return resolveDecl(E, E->getDecl());
14752     }
14753   };
14754 }
14755 
14756 /// Given a function expression of unknown-any type, try to rebuild it
14757 /// to have a function type.
14758 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14759   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14760   if (Result.isInvalid()) return ExprError();
14761   return S.DefaultFunctionArrayConversion(Result.get());
14762 }
14763 
14764 namespace {
14765   /// A visitor for rebuilding an expression of type __unknown_anytype
14766   /// into one which resolves the type directly on the referring
14767   /// expression.  Strict preservation of the original source
14768   /// structure is not a goal.
14769   struct RebuildUnknownAnyExpr
14770     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14771 
14772     Sema &S;
14773 
14774     /// The current destination type.
14775     QualType DestType;
14776 
14777     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14778       : S(S), DestType(CastType) {}
14779 
14780     ExprResult VisitStmt(Stmt *S) {
14781       llvm_unreachable("unexpected statement!");
14782     }
14783 
14784     ExprResult VisitExpr(Expr *E) {
14785       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14786         << E->getSourceRange();
14787       return ExprError();
14788     }
14789 
14790     ExprResult VisitCallExpr(CallExpr *E);
14791     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14792 
14793     /// Rebuild an expression which simply semantically wraps another
14794     /// expression which it shares the type and value kind of.
14795     template <class T> ExprResult rebuildSugarExpr(T *E) {
14796       ExprResult SubResult = Visit(E->getSubExpr());
14797       if (SubResult.isInvalid()) return ExprError();
14798       Expr *SubExpr = SubResult.get();
14799       E->setSubExpr(SubExpr);
14800       E->setType(SubExpr->getType());
14801       E->setValueKind(SubExpr->getValueKind());
14802       assert(E->getObjectKind() == OK_Ordinary);
14803       return E;
14804     }
14805 
14806     ExprResult VisitParenExpr(ParenExpr *E) {
14807       return rebuildSugarExpr(E);
14808     }
14809 
14810     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14811       return rebuildSugarExpr(E);
14812     }
14813 
14814     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14815       const PointerType *Ptr = DestType->getAs<PointerType>();
14816       if (!Ptr) {
14817         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14818           << E->getSourceRange();
14819         return ExprError();
14820       }
14821 
14822       if (isa<CallExpr>(E->getSubExpr())) {
14823         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14824           << E->getSourceRange();
14825         return ExprError();
14826       }
14827 
14828       assert(E->getValueKind() == VK_RValue);
14829       assert(E->getObjectKind() == OK_Ordinary);
14830       E->setType(DestType);
14831 
14832       // Build the sub-expression as if it were an object of the pointee type.
14833       DestType = Ptr->getPointeeType();
14834       ExprResult SubResult = Visit(E->getSubExpr());
14835       if (SubResult.isInvalid()) return ExprError();
14836       E->setSubExpr(SubResult.get());
14837       return E;
14838     }
14839 
14840     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14841 
14842     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14843 
14844     ExprResult VisitMemberExpr(MemberExpr *E) {
14845       return resolveDecl(E, E->getMemberDecl());
14846     }
14847 
14848     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14849       return resolveDecl(E, E->getDecl());
14850     }
14851   };
14852 }
14853 
14854 /// Rebuilds a call expression which yielded __unknown_anytype.
14855 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14856   Expr *CalleeExpr = E->getCallee();
14857 
14858   enum FnKind {
14859     FK_MemberFunction,
14860     FK_FunctionPointer,
14861     FK_BlockPointer
14862   };
14863 
14864   FnKind Kind;
14865   QualType CalleeType = CalleeExpr->getType();
14866   if (CalleeType == S.Context.BoundMemberTy) {
14867     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14868     Kind = FK_MemberFunction;
14869     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14870   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14871     CalleeType = Ptr->getPointeeType();
14872     Kind = FK_FunctionPointer;
14873   } else {
14874     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14875     Kind = FK_BlockPointer;
14876   }
14877   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14878 
14879   // Verify that this is a legal result type of a function.
14880   if (DestType->isArrayType() || DestType->isFunctionType()) {
14881     unsigned diagID = diag::err_func_returning_array_function;
14882     if (Kind == FK_BlockPointer)
14883       diagID = diag::err_block_returning_array_function;
14884 
14885     S.Diag(E->getExprLoc(), diagID)
14886       << DestType->isFunctionType() << DestType;
14887     return ExprError();
14888   }
14889 
14890   // Otherwise, go ahead and set DestType as the call's result.
14891   E->setType(DestType.getNonLValueExprType(S.Context));
14892   E->setValueKind(Expr::getValueKindForType(DestType));
14893   assert(E->getObjectKind() == OK_Ordinary);
14894 
14895   // Rebuild the function type, replacing the result type with DestType.
14896   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14897   if (Proto) {
14898     // __unknown_anytype(...) is a special case used by the debugger when
14899     // it has no idea what a function's signature is.
14900     //
14901     // We want to build this call essentially under the K&R
14902     // unprototyped rules, but making a FunctionNoProtoType in C++
14903     // would foul up all sorts of assumptions.  However, we cannot
14904     // simply pass all arguments as variadic arguments, nor can we
14905     // portably just call the function under a non-variadic type; see
14906     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14907     // However, it turns out that in practice it is generally safe to
14908     // call a function declared as "A foo(B,C,D);" under the prototype
14909     // "A foo(B,C,D,...);".  The only known exception is with the
14910     // Windows ABI, where any variadic function is implicitly cdecl
14911     // regardless of its normal CC.  Therefore we change the parameter
14912     // types to match the types of the arguments.
14913     //
14914     // This is a hack, but it is far superior to moving the
14915     // corresponding target-specific code from IR-gen to Sema/AST.
14916 
14917     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14918     SmallVector<QualType, 8> ArgTypes;
14919     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14920       ArgTypes.reserve(E->getNumArgs());
14921       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14922         Expr *Arg = E->getArg(i);
14923         QualType ArgType = Arg->getType();
14924         if (E->isLValue()) {
14925           ArgType = S.Context.getLValueReferenceType(ArgType);
14926         } else if (E->isXValue()) {
14927           ArgType = S.Context.getRValueReferenceType(ArgType);
14928         }
14929         ArgTypes.push_back(ArgType);
14930       }
14931       ParamTypes = ArgTypes;
14932     }
14933     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14934                                          Proto->getExtProtoInfo());
14935   } else {
14936     DestType = S.Context.getFunctionNoProtoType(DestType,
14937                                                 FnType->getExtInfo());
14938   }
14939 
14940   // Rebuild the appropriate pointer-to-function type.
14941   switch (Kind) {
14942   case FK_MemberFunction:
14943     // Nothing to do.
14944     break;
14945 
14946   case FK_FunctionPointer:
14947     DestType = S.Context.getPointerType(DestType);
14948     break;
14949 
14950   case FK_BlockPointer:
14951     DestType = S.Context.getBlockPointerType(DestType);
14952     break;
14953   }
14954 
14955   // Finally, we can recurse.
14956   ExprResult CalleeResult = Visit(CalleeExpr);
14957   if (!CalleeResult.isUsable()) return ExprError();
14958   E->setCallee(CalleeResult.get());
14959 
14960   // Bind a temporary if necessary.
14961   return S.MaybeBindToTemporary(E);
14962 }
14963 
14964 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14965   // Verify that this is a legal result type of a call.
14966   if (DestType->isArrayType() || DestType->isFunctionType()) {
14967     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14968       << DestType->isFunctionType() << DestType;
14969     return ExprError();
14970   }
14971 
14972   // Rewrite the method result type if available.
14973   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14974     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14975     Method->setReturnType(DestType);
14976   }
14977 
14978   // Change the type of the message.
14979   E->setType(DestType.getNonReferenceType());
14980   E->setValueKind(Expr::getValueKindForType(DestType));
14981 
14982   return S.MaybeBindToTemporary(E);
14983 }
14984 
14985 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14986   // The only case we should ever see here is a function-to-pointer decay.
14987   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14988     assert(E->getValueKind() == VK_RValue);
14989     assert(E->getObjectKind() == OK_Ordinary);
14990 
14991     E->setType(DestType);
14992 
14993     // Rebuild the sub-expression as the pointee (function) type.
14994     DestType = DestType->castAs<PointerType>()->getPointeeType();
14995 
14996     ExprResult Result = Visit(E->getSubExpr());
14997     if (!Result.isUsable()) return ExprError();
14998 
14999     E->setSubExpr(Result.get());
15000     return E;
15001   } else if (E->getCastKind() == CK_LValueToRValue) {
15002     assert(E->getValueKind() == VK_RValue);
15003     assert(E->getObjectKind() == OK_Ordinary);
15004 
15005     assert(isa<BlockPointerType>(E->getType()));
15006 
15007     E->setType(DestType);
15008 
15009     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15010     DestType = S.Context.getLValueReferenceType(DestType);
15011 
15012     ExprResult Result = Visit(E->getSubExpr());
15013     if (!Result.isUsable()) return ExprError();
15014 
15015     E->setSubExpr(Result.get());
15016     return E;
15017   } else {
15018     llvm_unreachable("Unhandled cast type!");
15019   }
15020 }
15021 
15022 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15023   ExprValueKind ValueKind = VK_LValue;
15024   QualType Type = DestType;
15025 
15026   // We know how to make this work for certain kinds of decls:
15027 
15028   //  - functions
15029   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15030     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15031       DestType = Ptr->getPointeeType();
15032       ExprResult Result = resolveDecl(E, VD);
15033       if (Result.isInvalid()) return ExprError();
15034       return S.ImpCastExprToType(Result.get(), Type,
15035                                  CK_FunctionToPointerDecay, VK_RValue);
15036     }
15037 
15038     if (!Type->isFunctionType()) {
15039       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15040         << VD << E->getSourceRange();
15041       return ExprError();
15042     }
15043     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15044       // We must match the FunctionDecl's type to the hack introduced in
15045       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15046       // type. See the lengthy commentary in that routine.
15047       QualType FDT = FD->getType();
15048       const FunctionType *FnType = FDT->castAs<FunctionType>();
15049       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15050       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15051       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15052         SourceLocation Loc = FD->getLocation();
15053         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15054                                       FD->getDeclContext(),
15055                                       Loc, Loc, FD->getNameInfo().getName(),
15056                                       DestType, FD->getTypeSourceInfo(),
15057                                       SC_None, false/*isInlineSpecified*/,
15058                                       FD->hasPrototype(),
15059                                       false/*isConstexprSpecified*/);
15060 
15061         if (FD->getQualifier())
15062           NewFD->setQualifierInfo(FD->getQualifierLoc());
15063 
15064         SmallVector<ParmVarDecl*, 16> Params;
15065         for (const auto &AI : FT->param_types()) {
15066           ParmVarDecl *Param =
15067             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15068           Param->setScopeInfo(0, Params.size());
15069           Params.push_back(Param);
15070         }
15071         NewFD->setParams(Params);
15072         DRE->setDecl(NewFD);
15073         VD = DRE->getDecl();
15074       }
15075     }
15076 
15077     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15078       if (MD->isInstance()) {
15079         ValueKind = VK_RValue;
15080         Type = S.Context.BoundMemberTy;
15081       }
15082 
15083     // Function references aren't l-values in C.
15084     if (!S.getLangOpts().CPlusPlus)
15085       ValueKind = VK_RValue;
15086 
15087   //  - variables
15088   } else if (isa<VarDecl>(VD)) {
15089     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15090       Type = RefTy->getPointeeType();
15091     } else if (Type->isFunctionType()) {
15092       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15093         << VD << E->getSourceRange();
15094       return ExprError();
15095     }
15096 
15097   //  - nothing else
15098   } else {
15099     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15100       << VD << E->getSourceRange();
15101     return ExprError();
15102   }
15103 
15104   // Modifying the declaration like this is friendly to IR-gen but
15105   // also really dangerous.
15106   VD->setType(DestType);
15107   E->setType(Type);
15108   E->setValueKind(ValueKind);
15109   return E;
15110 }
15111 
15112 /// Check a cast of an unknown-any type.  We intentionally only
15113 /// trigger this for C-style casts.
15114 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15115                                      Expr *CastExpr, CastKind &CastKind,
15116                                      ExprValueKind &VK, CXXCastPath &Path) {
15117   // The type we're casting to must be either void or complete.
15118   if (!CastType->isVoidType() &&
15119       RequireCompleteType(TypeRange.getBegin(), CastType,
15120                           diag::err_typecheck_cast_to_incomplete))
15121     return ExprError();
15122 
15123   // Rewrite the casted expression from scratch.
15124   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15125   if (!result.isUsable()) return ExprError();
15126 
15127   CastExpr = result.get();
15128   VK = CastExpr->getValueKind();
15129   CastKind = CK_NoOp;
15130 
15131   return CastExpr;
15132 }
15133 
15134 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15135   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15136 }
15137 
15138 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15139                                     Expr *arg, QualType &paramType) {
15140   // If the syntactic form of the argument is not an explicit cast of
15141   // any sort, just do default argument promotion.
15142   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15143   if (!castArg) {
15144     ExprResult result = DefaultArgumentPromotion(arg);
15145     if (result.isInvalid()) return ExprError();
15146     paramType = result.get()->getType();
15147     return result;
15148   }
15149 
15150   // Otherwise, use the type that was written in the explicit cast.
15151   assert(!arg->hasPlaceholderType());
15152   paramType = castArg->getTypeAsWritten();
15153 
15154   // Copy-initialize a parameter of that type.
15155   InitializedEntity entity =
15156     InitializedEntity::InitializeParameter(Context, paramType,
15157                                            /*consumed*/ false);
15158   return PerformCopyInitialization(entity, callLoc, arg);
15159 }
15160 
15161 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15162   Expr *orig = E;
15163   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15164   while (true) {
15165     E = E->IgnoreParenImpCasts();
15166     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15167       E = call->getCallee();
15168       diagID = diag::err_uncasted_call_of_unknown_any;
15169     } else {
15170       break;
15171     }
15172   }
15173 
15174   SourceLocation loc;
15175   NamedDecl *d;
15176   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15177     loc = ref->getLocation();
15178     d = ref->getDecl();
15179   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15180     loc = mem->getMemberLoc();
15181     d = mem->getMemberDecl();
15182   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15183     diagID = diag::err_uncasted_call_of_unknown_any;
15184     loc = msg->getSelectorStartLoc();
15185     d = msg->getMethodDecl();
15186     if (!d) {
15187       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15188         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15189         << orig->getSourceRange();
15190       return ExprError();
15191     }
15192   } else {
15193     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15194       << E->getSourceRange();
15195     return ExprError();
15196   }
15197 
15198   S.Diag(loc, diagID) << d << orig->getSourceRange();
15199 
15200   // Never recoverable.
15201   return ExprError();
15202 }
15203 
15204 /// Check for operands with placeholder types and complain if found.
15205 /// Returns true if there was an error and no recovery was possible.
15206 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15207   if (!getLangOpts().CPlusPlus) {
15208     // C cannot handle TypoExpr nodes on either side of a binop because it
15209     // doesn't handle dependent types properly, so make sure any TypoExprs have
15210     // been dealt with before checking the operands.
15211     ExprResult Result = CorrectDelayedTyposInExpr(E);
15212     if (!Result.isUsable()) return ExprError();
15213     E = Result.get();
15214   }
15215 
15216   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15217   if (!placeholderType) return E;
15218 
15219   switch (placeholderType->getKind()) {
15220 
15221   // Overloaded expressions.
15222   case BuiltinType::Overload: {
15223     // Try to resolve a single function template specialization.
15224     // This is obligatory.
15225     ExprResult Result = E;
15226     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15227       return Result;
15228 
15229     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15230     // leaves Result unchanged on failure.
15231     Result = E;
15232     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15233       return Result;
15234 
15235     // If that failed, try to recover with a call.
15236     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15237                          /*complain*/ true);
15238     return Result;
15239   }
15240 
15241   // Bound member functions.
15242   case BuiltinType::BoundMember: {
15243     ExprResult result = E;
15244     const Expr *BME = E->IgnoreParens();
15245     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15246     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15247     if (isa<CXXPseudoDestructorExpr>(BME)) {
15248       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15249     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15250       if (ME->getMemberNameInfo().getName().getNameKind() ==
15251           DeclarationName::CXXDestructorName)
15252         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15253     }
15254     tryToRecoverWithCall(result, PD,
15255                          /*complain*/ true);
15256     return result;
15257   }
15258 
15259   // ARC unbridged casts.
15260   case BuiltinType::ARCUnbridgedCast: {
15261     Expr *realCast = stripARCUnbridgedCast(E);
15262     diagnoseARCUnbridgedCast(realCast);
15263     return realCast;
15264   }
15265 
15266   // Expressions of unknown type.
15267   case BuiltinType::UnknownAny:
15268     return diagnoseUnknownAnyExpr(*this, E);
15269 
15270   // Pseudo-objects.
15271   case BuiltinType::PseudoObject:
15272     return checkPseudoObjectRValue(E);
15273 
15274   case BuiltinType::BuiltinFn: {
15275     // Accept __noop without parens by implicitly converting it to a call expr.
15276     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15277     if (DRE) {
15278       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15279       if (FD->getBuiltinID() == Builtin::BI__noop) {
15280         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15281                               CK_BuiltinFnToFnPtr).get();
15282         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15283                                       VK_RValue, SourceLocation());
15284       }
15285     }
15286 
15287     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15288     return ExprError();
15289   }
15290 
15291   // Expressions of unknown type.
15292   case BuiltinType::OMPArraySection:
15293     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15294     return ExprError();
15295 
15296   // Everything else should be impossible.
15297 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15298   case BuiltinType::Id:
15299 #include "clang/Basic/OpenCLImageTypes.def"
15300 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15301 #define PLACEHOLDER_TYPE(Id, SingletonId)
15302 #include "clang/AST/BuiltinTypes.def"
15303     break;
15304   }
15305 
15306   llvm_unreachable("invalid placeholder type!");
15307 }
15308 
15309 bool Sema::CheckCaseExpression(Expr *E) {
15310   if (E->isTypeDependent())
15311     return true;
15312   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15313     return E->getType()->isIntegralOrEnumerationType();
15314   return false;
15315 }
15316 
15317 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15318 ExprResult
15319 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15320   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15321          "Unknown Objective-C Boolean value!");
15322   QualType BoolT = Context.ObjCBuiltinBoolTy;
15323   if (!Context.getBOOLDecl()) {
15324     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15325                         Sema::LookupOrdinaryName);
15326     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15327       NamedDecl *ND = Result.getFoundDecl();
15328       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15329         Context.setBOOLDecl(TD);
15330     }
15331   }
15332   if (Context.getBOOLDecl())
15333     BoolT = Context.getBOOLType();
15334   return new (Context)
15335       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15336 }
15337 
15338 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15339     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15340     SourceLocation RParen) {
15341 
15342   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15343 
15344   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15345                            [&](const AvailabilitySpec &Spec) {
15346                              return Spec.getPlatform() == Platform;
15347                            });
15348 
15349   VersionTuple Version;
15350   if (Spec != AvailSpecs.end())
15351     Version = Spec->getVersion();
15352 
15353   return new (Context)
15354       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15355 }
15356