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().isEnabled("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().isEnabled("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 (D->isInvalidDecl())
2781     return true;
2782 
2783   if (isa<TypedefNameDecl>(D)) {
2784     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2785     return true;
2786   }
2787 
2788   if (isa<ObjCInterfaceDecl>(D)) {
2789     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2790     return true;
2791   }
2792 
2793   if (isa<NamespaceDecl>(D)) {
2794     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2795     return true;
2796   }
2797 
2798   return false;
2799 }
2800 
2801 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2802                                           LookupResult &R, bool NeedsADL,
2803                                           bool AcceptInvalidDecl) {
2804   // If this is a single, fully-resolved result and we don't need ADL,
2805   // just build an ordinary singleton decl ref.
2806   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2807     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2808                                     R.getRepresentativeDecl(), nullptr,
2809                                     AcceptInvalidDecl);
2810 
2811   // We only need to check the declaration if there's exactly one
2812   // result, because in the overloaded case the results can only be
2813   // functions and function templates.
2814   if (R.isSingleResult() &&
2815       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2816     return ExprError();
2817 
2818   // Otherwise, just build an unresolved lookup expression.  Suppress
2819   // any lookup-related diagnostics; we'll hash these out later, when
2820   // we've picked a target.
2821   R.suppressDiagnostics();
2822 
2823   UnresolvedLookupExpr *ULE
2824     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2825                                    SS.getWithLocInContext(Context),
2826                                    R.getLookupNameInfo(),
2827                                    NeedsADL, R.isOverloadedResult(),
2828                                    R.begin(), R.end());
2829 
2830   return ULE;
2831 }
2832 
2833 static void
2834 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2835                                    ValueDecl *var, DeclContext *DC);
2836 
2837 /// \brief Complete semantic analysis for a reference to the given declaration.
2838 ExprResult Sema::BuildDeclarationNameExpr(
2839     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2840     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2841     bool AcceptInvalidDecl) {
2842   assert(D && "Cannot refer to a NULL declaration");
2843   assert(!isa<FunctionTemplateDecl>(D) &&
2844          "Cannot refer unambiguously to a function template");
2845 
2846   SourceLocation Loc = NameInfo.getLoc();
2847   if (CheckDeclInExpr(*this, Loc, D))
2848     return ExprError();
2849 
2850   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2851     // Specifically diagnose references to class templates that are missing
2852     // a template argument list.
2853     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2854                                            << Template << SS.getRange();
2855     Diag(Template->getLocation(), diag::note_template_decl_here);
2856     return ExprError();
2857   }
2858 
2859   // Make sure that we're referring to a value.
2860   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2861   if (!VD) {
2862     Diag(Loc, diag::err_ref_non_value)
2863       << D << SS.getRange();
2864     Diag(D->getLocation(), diag::note_declared_at);
2865     return ExprError();
2866   }
2867 
2868   // Check whether this declaration can be used. Note that we suppress
2869   // this check when we're going to perform argument-dependent lookup
2870   // on this function name, because this might not be the function
2871   // that overload resolution actually selects.
2872   if (DiagnoseUseOfDecl(VD, Loc))
2873     return ExprError();
2874 
2875   // Only create DeclRefExpr's for valid Decl's.
2876   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2877     return ExprError();
2878 
2879   // Handle members of anonymous structs and unions.  If we got here,
2880   // and the reference is to a class member indirect field, then this
2881   // must be the subject of a pointer-to-member expression.
2882   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2883     if (!indirectField->isCXXClassMember())
2884       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2885                                                       indirectField);
2886 
2887   {
2888     QualType type = VD->getType();
2889     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2890       // C++ [except.spec]p17:
2891       //   An exception-specification is considered to be needed when:
2892       //   - in an expression, the function is the unique lookup result or
2893       //     the selected member of a set of overloaded functions.
2894       ResolveExceptionSpec(Loc, FPT);
2895       type = VD->getType();
2896     }
2897     ExprValueKind valueKind = VK_RValue;
2898 
2899     switch (D->getKind()) {
2900     // Ignore all the non-ValueDecl kinds.
2901 #define ABSTRACT_DECL(kind)
2902 #define VALUE(type, base)
2903 #define DECL(type, base) \
2904     case Decl::type:
2905 #include "clang/AST/DeclNodes.inc"
2906       llvm_unreachable("invalid value decl kind");
2907 
2908     // These shouldn't make it here.
2909     case Decl::ObjCAtDefsField:
2910     case Decl::ObjCIvar:
2911       llvm_unreachable("forming non-member reference to ivar?");
2912 
2913     // Enum constants are always r-values and never references.
2914     // Unresolved using declarations are dependent.
2915     case Decl::EnumConstant:
2916     case Decl::UnresolvedUsingValue:
2917     case Decl::OMPDeclareReduction:
2918       valueKind = VK_RValue;
2919       break;
2920 
2921     // Fields and indirect fields that got here must be for
2922     // pointer-to-member expressions; we just call them l-values for
2923     // internal consistency, because this subexpression doesn't really
2924     // exist in the high-level semantics.
2925     case Decl::Field:
2926     case Decl::IndirectField:
2927       assert(getLangOpts().CPlusPlus &&
2928              "building reference to field in C?");
2929 
2930       // These can't have reference type in well-formed programs, but
2931       // for internal consistency we do this anyway.
2932       type = type.getNonReferenceType();
2933       valueKind = VK_LValue;
2934       break;
2935 
2936     // Non-type template parameters are either l-values or r-values
2937     // depending on the type.
2938     case Decl::NonTypeTemplateParm: {
2939       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2940         type = reftype->getPointeeType();
2941         valueKind = VK_LValue; // even if the parameter is an r-value reference
2942         break;
2943       }
2944 
2945       // For non-references, we need to strip qualifiers just in case
2946       // the template parameter was declared as 'const int' or whatever.
2947       valueKind = VK_RValue;
2948       type = type.getUnqualifiedType();
2949       break;
2950     }
2951 
2952     case Decl::Var:
2953     case Decl::VarTemplateSpecialization:
2954     case Decl::VarTemplatePartialSpecialization:
2955     case Decl::Decomposition:
2956     case Decl::OMPCapturedExpr:
2957       // In C, "extern void blah;" is valid and is an r-value.
2958       if (!getLangOpts().CPlusPlus &&
2959           !type.hasQualifiers() &&
2960           type->isVoidType()) {
2961         valueKind = VK_RValue;
2962         break;
2963       }
2964       // fallthrough
2965 
2966     case Decl::ImplicitParam:
2967     case Decl::ParmVar: {
2968       // These are always l-values.
2969       valueKind = VK_LValue;
2970       type = type.getNonReferenceType();
2971 
2972       // FIXME: Does the addition of const really only apply in
2973       // potentially-evaluated contexts? Since the variable isn't actually
2974       // captured in an unevaluated context, it seems that the answer is no.
2975       if (!isUnevaluatedContext()) {
2976         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2977         if (!CapturedType.isNull())
2978           type = CapturedType;
2979       }
2980 
2981       break;
2982     }
2983 
2984     case Decl::Binding: {
2985       // These are always lvalues.
2986       valueKind = VK_LValue;
2987       type = type.getNonReferenceType();
2988       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2989       // decides how that's supposed to work.
2990       auto *BD = cast<BindingDecl>(VD);
2991       if (BD->getDeclContext()->isFunctionOrMethod() &&
2992           BD->getDeclContext() != CurContext)
2993         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2994       break;
2995     }
2996 
2997     case Decl::Function: {
2998       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2999         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3000           type = Context.BuiltinFnTy;
3001           valueKind = VK_RValue;
3002           break;
3003         }
3004       }
3005 
3006       const FunctionType *fty = type->castAs<FunctionType>();
3007 
3008       // If we're referring to a function with an __unknown_anytype
3009       // result type, make the entire expression __unknown_anytype.
3010       if (fty->getReturnType() == Context.UnknownAnyTy) {
3011         type = Context.UnknownAnyTy;
3012         valueKind = VK_RValue;
3013         break;
3014       }
3015 
3016       // Functions are l-values in C++.
3017       if (getLangOpts().CPlusPlus) {
3018         valueKind = VK_LValue;
3019         break;
3020       }
3021 
3022       // C99 DR 316 says that, if a function type comes from a
3023       // function definition (without a prototype), that type is only
3024       // used for checking compatibility. Therefore, when referencing
3025       // the function, we pretend that we don't have the full function
3026       // type.
3027       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3028           isa<FunctionProtoType>(fty))
3029         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3030                                               fty->getExtInfo());
3031 
3032       // Functions are r-values in C.
3033       valueKind = VK_RValue;
3034       break;
3035     }
3036 
3037     case Decl::MSProperty:
3038       valueKind = VK_LValue;
3039       break;
3040 
3041     case Decl::CXXMethod:
3042       // If we're referring to a method with an __unknown_anytype
3043       // result type, make the entire expression __unknown_anytype.
3044       // This should only be possible with a type written directly.
3045       if (const FunctionProtoType *proto
3046             = dyn_cast<FunctionProtoType>(VD->getType()))
3047         if (proto->getReturnType() == Context.UnknownAnyTy) {
3048           type = Context.UnknownAnyTy;
3049           valueKind = VK_RValue;
3050           break;
3051         }
3052 
3053       // C++ methods are l-values if static, r-values if non-static.
3054       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3055         valueKind = VK_LValue;
3056         break;
3057       }
3058       // fallthrough
3059 
3060     case Decl::CXXConversion:
3061     case Decl::CXXDestructor:
3062     case Decl::CXXConstructor:
3063       valueKind = VK_RValue;
3064       break;
3065     }
3066 
3067     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3068                             TemplateArgs);
3069   }
3070 }
3071 
3072 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3073                                     SmallString<32> &Target) {
3074   Target.resize(CharByteWidth * (Source.size() + 1));
3075   char *ResultPtr = &Target[0];
3076   const llvm::UTF8 *ErrorPtr;
3077   bool success =
3078       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3079   (void)success;
3080   assert(success);
3081   Target.resize(ResultPtr - &Target[0]);
3082 }
3083 
3084 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3085                                      PredefinedExpr::IdentType IT) {
3086   // Pick the current block, lambda, captured statement or function.
3087   Decl *currentDecl = nullptr;
3088   if (const BlockScopeInfo *BSI = getCurBlock())
3089     currentDecl = BSI->TheDecl;
3090   else if (const LambdaScopeInfo *LSI = getCurLambda())
3091     currentDecl = LSI->CallOperator;
3092   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3093     currentDecl = CSI->TheCapturedDecl;
3094   else
3095     currentDecl = getCurFunctionOrMethodDecl();
3096 
3097   if (!currentDecl) {
3098     Diag(Loc, diag::ext_predef_outside_function);
3099     currentDecl = Context.getTranslationUnitDecl();
3100   }
3101 
3102   QualType ResTy;
3103   StringLiteral *SL = nullptr;
3104   if (cast<DeclContext>(currentDecl)->isDependentContext())
3105     ResTy = Context.DependentTy;
3106   else {
3107     // Pre-defined identifiers are of type char[x], where x is the length of
3108     // the string.
3109     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3110     unsigned Length = Str.length();
3111 
3112     llvm::APInt LengthI(32, Length + 1);
3113     if (IT == PredefinedExpr::LFunction) {
3114       ResTy = Context.WideCharTy.withConst();
3115       SmallString<32> RawChars;
3116       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3117                               Str, RawChars);
3118       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3119                                            /*IndexTypeQuals*/ 0);
3120       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3121                                  /*Pascal*/ false, ResTy, Loc);
3122     } else {
3123       ResTy = Context.CharTy.withConst();
3124       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3125                                            /*IndexTypeQuals*/ 0);
3126       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3127                                  /*Pascal*/ false, ResTy, Loc);
3128     }
3129   }
3130 
3131   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3132 }
3133 
3134 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3135   PredefinedExpr::IdentType IT;
3136 
3137   switch (Kind) {
3138   default: llvm_unreachable("Unknown simple primary expr!");
3139   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3140   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3141   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3142   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3143   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3144   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3145   }
3146 
3147   return BuildPredefinedExpr(Loc, IT);
3148 }
3149 
3150 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3151   SmallString<16> CharBuffer;
3152   bool Invalid = false;
3153   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3154   if (Invalid)
3155     return ExprError();
3156 
3157   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3158                             PP, Tok.getKind());
3159   if (Literal.hadError())
3160     return ExprError();
3161 
3162   QualType Ty;
3163   if (Literal.isWide())
3164     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3165   else if (Literal.isUTF16())
3166     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3167   else if (Literal.isUTF32())
3168     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3169   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3170     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3171   else
3172     Ty = Context.CharTy;  // 'x' -> char in C++
3173 
3174   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3175   if (Literal.isWide())
3176     Kind = CharacterLiteral::Wide;
3177   else if (Literal.isUTF16())
3178     Kind = CharacterLiteral::UTF16;
3179   else if (Literal.isUTF32())
3180     Kind = CharacterLiteral::UTF32;
3181   else if (Literal.isUTF8())
3182     Kind = CharacterLiteral::UTF8;
3183 
3184   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3185                                              Tok.getLocation());
3186 
3187   if (Literal.getUDSuffix().empty())
3188     return Lit;
3189 
3190   // We're building a user-defined literal.
3191   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3192   SourceLocation UDSuffixLoc =
3193     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3194 
3195   // Make sure we're allowed user-defined literals here.
3196   if (!UDLScope)
3197     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3198 
3199   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3200   //   operator "" X (ch)
3201   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3202                                         Lit, Tok.getLocation());
3203 }
3204 
3205 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3206   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3207   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3208                                 Context.IntTy, Loc);
3209 }
3210 
3211 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3212                                   QualType Ty, SourceLocation Loc) {
3213   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3214 
3215   using llvm::APFloat;
3216   APFloat Val(Format);
3217 
3218   APFloat::opStatus result = Literal.GetFloatValue(Val);
3219 
3220   // Overflow is always an error, but underflow is only an error if
3221   // we underflowed to zero (APFloat reports denormals as underflow).
3222   if ((result & APFloat::opOverflow) ||
3223       ((result & APFloat::opUnderflow) && Val.isZero())) {
3224     unsigned diagnostic;
3225     SmallString<20> buffer;
3226     if (result & APFloat::opOverflow) {
3227       diagnostic = diag::warn_float_overflow;
3228       APFloat::getLargest(Format).toString(buffer);
3229     } else {
3230       diagnostic = diag::warn_float_underflow;
3231       APFloat::getSmallest(Format).toString(buffer);
3232     }
3233 
3234     S.Diag(Loc, diagnostic)
3235       << Ty
3236       << StringRef(buffer.data(), buffer.size());
3237   }
3238 
3239   bool isExact = (result == APFloat::opOK);
3240   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3241 }
3242 
3243 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3244   assert(E && "Invalid expression");
3245 
3246   if (E->isValueDependent())
3247     return false;
3248 
3249   QualType QT = E->getType();
3250   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3251     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3252     return true;
3253   }
3254 
3255   llvm::APSInt ValueAPS;
3256   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3257 
3258   if (R.isInvalid())
3259     return true;
3260 
3261   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3262   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3263     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3264         << ValueAPS.toString(10) << ValueIsPositive;
3265     return true;
3266   }
3267 
3268   return false;
3269 }
3270 
3271 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3272   // Fast path for a single digit (which is quite common).  A single digit
3273   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3274   if (Tok.getLength() == 1) {
3275     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3276     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3277   }
3278 
3279   SmallString<128> SpellingBuffer;
3280   // NumericLiteralParser wants to overread by one character.  Add padding to
3281   // the buffer in case the token is copied to the buffer.  If getSpelling()
3282   // returns a StringRef to the memory buffer, it should have a null char at
3283   // the EOF, so it is also safe.
3284   SpellingBuffer.resize(Tok.getLength() + 1);
3285 
3286   // Get the spelling of the token, which eliminates trigraphs, etc.
3287   bool Invalid = false;
3288   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3289   if (Invalid)
3290     return ExprError();
3291 
3292   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3293   if (Literal.hadError)
3294     return ExprError();
3295 
3296   if (Literal.hasUDSuffix()) {
3297     // We're building a user-defined literal.
3298     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3299     SourceLocation UDSuffixLoc =
3300       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3301 
3302     // Make sure we're allowed user-defined literals here.
3303     if (!UDLScope)
3304       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3305 
3306     QualType CookedTy;
3307     if (Literal.isFloatingLiteral()) {
3308       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3309       // long double, the literal is treated as a call of the form
3310       //   operator "" X (f L)
3311       CookedTy = Context.LongDoubleTy;
3312     } else {
3313       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3314       // unsigned long long, the literal is treated as a call of the form
3315       //   operator "" X (n ULL)
3316       CookedTy = Context.UnsignedLongLongTy;
3317     }
3318 
3319     DeclarationName OpName =
3320       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3321     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3322     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3323 
3324     SourceLocation TokLoc = Tok.getLocation();
3325 
3326     // Perform literal operator lookup to determine if we're building a raw
3327     // literal or a cooked one.
3328     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3329     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3330                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3331                                   /*AllowStringTemplate*/false)) {
3332     case LOLR_Error:
3333       return ExprError();
3334 
3335     case LOLR_Cooked: {
3336       Expr *Lit;
3337       if (Literal.isFloatingLiteral()) {
3338         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3339       } else {
3340         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3341         if (Literal.GetIntegerValue(ResultVal))
3342           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3343               << /* Unsigned */ 1;
3344         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3345                                      Tok.getLocation());
3346       }
3347       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3348     }
3349 
3350     case LOLR_Raw: {
3351       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3352       // literal is treated as a call of the form
3353       //   operator "" X ("n")
3354       unsigned Length = Literal.getUDSuffixOffset();
3355       QualType StrTy = Context.getConstantArrayType(
3356           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3357           ArrayType::Normal, 0);
3358       Expr *Lit = StringLiteral::Create(
3359           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3360           /*Pascal*/false, StrTy, &TokLoc, 1);
3361       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3362     }
3363 
3364     case LOLR_Template: {
3365       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3366       // template), L is treated as a call fo the form
3367       //   operator "" X <'c1', 'c2', ... 'ck'>()
3368       // where n is the source character sequence c1 c2 ... ck.
3369       TemplateArgumentListInfo ExplicitArgs;
3370       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3371       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3372       llvm::APSInt Value(CharBits, CharIsUnsigned);
3373       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3374         Value = TokSpelling[I];
3375         TemplateArgument Arg(Context, Value, Context.CharTy);
3376         TemplateArgumentLocInfo ArgInfo;
3377         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3378       }
3379       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3380                                       &ExplicitArgs);
3381     }
3382     case LOLR_StringTemplate:
3383       llvm_unreachable("unexpected literal operator lookup result");
3384     }
3385   }
3386 
3387   Expr *Res;
3388 
3389   if (Literal.isFloatingLiteral()) {
3390     QualType Ty;
3391     if (Literal.isHalf){
3392       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3393         Ty = Context.HalfTy;
3394       else {
3395         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3396         return ExprError();
3397       }
3398     } else if (Literal.isFloat)
3399       Ty = Context.FloatTy;
3400     else if (Literal.isLong)
3401       Ty = Context.LongDoubleTy;
3402     else if (Literal.isFloat128)
3403       Ty = Context.Float128Ty;
3404     else
3405       Ty = Context.DoubleTy;
3406 
3407     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3408 
3409     if (Ty == Context.DoubleTy) {
3410       if (getLangOpts().SinglePrecisionConstants) {
3411         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3412         if (BTy->getKind() != BuiltinType::Float) {
3413           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3414         }
3415       } else if (getLangOpts().OpenCL &&
3416                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3417         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3418         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3419         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3420       }
3421     }
3422   } else if (!Literal.isIntegerLiteral()) {
3423     return ExprError();
3424   } else {
3425     QualType Ty;
3426 
3427     // 'long long' is a C99 or C++11 feature.
3428     if (!getLangOpts().C99 && Literal.isLongLong) {
3429       if (getLangOpts().CPlusPlus)
3430         Diag(Tok.getLocation(),
3431              getLangOpts().CPlusPlus11 ?
3432              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3433       else
3434         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3435     }
3436 
3437     // Get the value in the widest-possible width.
3438     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3439     llvm::APInt ResultVal(MaxWidth, 0);
3440 
3441     if (Literal.GetIntegerValue(ResultVal)) {
3442       // If this value didn't fit into uintmax_t, error and force to ull.
3443       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3444           << /* Unsigned */ 1;
3445       Ty = Context.UnsignedLongLongTy;
3446       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3447              "long long is not intmax_t?");
3448     } else {
3449       // If this value fits into a ULL, try to figure out what else it fits into
3450       // according to the rules of C99 6.4.4.1p5.
3451 
3452       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3453       // be an unsigned int.
3454       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3455 
3456       // Check from smallest to largest, picking the smallest type we can.
3457       unsigned Width = 0;
3458 
3459       // Microsoft specific integer suffixes are explicitly sized.
3460       if (Literal.MicrosoftInteger) {
3461         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3462           Width = 8;
3463           Ty = Context.CharTy;
3464         } else {
3465           Width = Literal.MicrosoftInteger;
3466           Ty = Context.getIntTypeForBitwidth(Width,
3467                                              /*Signed=*/!Literal.isUnsigned);
3468         }
3469       }
3470 
3471       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3472         // Are int/unsigned possibilities?
3473         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3474 
3475         // Does it fit in a unsigned int?
3476         if (ResultVal.isIntN(IntSize)) {
3477           // Does it fit in a signed int?
3478           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3479             Ty = Context.IntTy;
3480           else if (AllowUnsigned)
3481             Ty = Context.UnsignedIntTy;
3482           Width = IntSize;
3483         }
3484       }
3485 
3486       // Are long/unsigned long possibilities?
3487       if (Ty.isNull() && !Literal.isLongLong) {
3488         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3489 
3490         // Does it fit in a unsigned long?
3491         if (ResultVal.isIntN(LongSize)) {
3492           // Does it fit in a signed long?
3493           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3494             Ty = Context.LongTy;
3495           else if (AllowUnsigned)
3496             Ty = Context.UnsignedLongTy;
3497           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3498           // is compatible.
3499           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3500             const unsigned LongLongSize =
3501                 Context.getTargetInfo().getLongLongWidth();
3502             Diag(Tok.getLocation(),
3503                  getLangOpts().CPlusPlus
3504                      ? Literal.isLong
3505                            ? diag::warn_old_implicitly_unsigned_long_cxx
3506                            : /*C++98 UB*/ diag::
3507                                  ext_old_implicitly_unsigned_long_cxx
3508                      : diag::warn_old_implicitly_unsigned_long)
3509                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3510                                             : /*will be ill-formed*/ 1);
3511             Ty = Context.UnsignedLongTy;
3512           }
3513           Width = LongSize;
3514         }
3515       }
3516 
3517       // Check long long if needed.
3518       if (Ty.isNull()) {
3519         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3520 
3521         // Does it fit in a unsigned long long?
3522         if (ResultVal.isIntN(LongLongSize)) {
3523           // Does it fit in a signed long long?
3524           // To be compatible with MSVC, hex integer literals ending with the
3525           // LL or i64 suffix are always signed in Microsoft mode.
3526           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3527               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3528             Ty = Context.LongLongTy;
3529           else if (AllowUnsigned)
3530             Ty = Context.UnsignedLongLongTy;
3531           Width = LongLongSize;
3532         }
3533       }
3534 
3535       // If we still couldn't decide a type, we probably have something that
3536       // does not fit in a signed long long, but has no U suffix.
3537       if (Ty.isNull()) {
3538         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3539         Ty = Context.UnsignedLongLongTy;
3540         Width = Context.getTargetInfo().getLongLongWidth();
3541       }
3542 
3543       if (ResultVal.getBitWidth() != Width)
3544         ResultVal = ResultVal.trunc(Width);
3545     }
3546     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3547   }
3548 
3549   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3550   if (Literal.isImaginary)
3551     Res = new (Context) ImaginaryLiteral(Res,
3552                                         Context.getComplexType(Res->getType()));
3553 
3554   return Res;
3555 }
3556 
3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3558   assert(E && "ActOnParenExpr() missing expr");
3559   return new (Context) ParenExpr(L, R, E);
3560 }
3561 
3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3563                                          SourceLocation Loc,
3564                                          SourceRange ArgRange) {
3565   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3566   // scalar or vector data type argument..."
3567   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3568   // type (C99 6.2.5p18) or void.
3569   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3570     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3571       << T << ArgRange;
3572     return true;
3573   }
3574 
3575   assert((T->isVoidType() || !T->isIncompleteType()) &&
3576          "Scalar types should always be complete");
3577   return false;
3578 }
3579 
3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3581                                            SourceLocation Loc,
3582                                            SourceRange ArgRange,
3583                                            UnaryExprOrTypeTrait TraitKind) {
3584   // Invalid types must be hard errors for SFINAE in C++.
3585   if (S.LangOpts.CPlusPlus)
3586     return true;
3587 
3588   // C99 6.5.3.4p1:
3589   if (T->isFunctionType() &&
3590       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3591     // sizeof(function)/alignof(function) is allowed as an extension.
3592     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3593       << TraitKind << ArgRange;
3594     return false;
3595   }
3596 
3597   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3598   // this is an error (OpenCL v1.1 s6.3.k)
3599   if (T->isVoidType()) {
3600     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3601                                         : diag::ext_sizeof_alignof_void_type;
3602     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3603     return false;
3604   }
3605 
3606   return true;
3607 }
3608 
3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3610                                              SourceLocation Loc,
3611                                              SourceRange ArgRange,
3612                                              UnaryExprOrTypeTrait TraitKind) {
3613   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3614   // runtime doesn't allow it.
3615   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3616     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3617       << T << (TraitKind == UETT_SizeOf)
3618       << ArgRange;
3619     return true;
3620   }
3621 
3622   return false;
3623 }
3624 
3625 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3626 /// pointer type is equal to T) and emit a warning if it is.
3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3628                                      Expr *E) {
3629   // Don't warn if the operation changed the type.
3630   if (T != E->getType())
3631     return;
3632 
3633   // Now look for array decays.
3634   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3635   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3636     return;
3637 
3638   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3639                                              << ICE->getType()
3640                                              << ICE->getSubExpr()->getType();
3641 }
3642 
3643 /// \brief Check the constraints on expression operands to unary type expression
3644 /// and type traits.
3645 ///
3646 /// Completes any types necessary and validates the constraints on the operand
3647 /// expression. The logic mostly mirrors the type-based overload, but may modify
3648 /// the expression as it completes the type for that expression through template
3649 /// instantiation, etc.
3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3651                                             UnaryExprOrTypeTrait ExprKind) {
3652   QualType ExprTy = E->getType();
3653   assert(!ExprTy->isReferenceType());
3654 
3655   if (ExprKind == UETT_VecStep)
3656     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3657                                         E->getSourceRange());
3658 
3659   // Whitelist some types as extensions
3660   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                       E->getSourceRange(), ExprKind))
3662     return false;
3663 
3664   // 'alignof' applied to an expression only requires the base element type of
3665   // the expression to be complete. 'sizeof' requires the expression's type to
3666   // be complete (and will attempt to complete it if it's an array of unknown
3667   // bound).
3668   if (ExprKind == UETT_AlignOf) {
3669     if (RequireCompleteType(E->getExprLoc(),
3670                             Context.getBaseElementType(E->getType()),
3671                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3672                             E->getSourceRange()))
3673       return true;
3674   } else {
3675     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3676                                 ExprKind, E->getSourceRange()))
3677       return true;
3678   }
3679 
3680   // Completing the expression's type may have changed it.
3681   ExprTy = E->getType();
3682   assert(!ExprTy->isReferenceType());
3683 
3684   if (ExprTy->isFunctionType()) {
3685     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3686       << ExprKind << E->getSourceRange();
3687     return true;
3688   }
3689 
3690   // The operand for sizeof and alignof is in an unevaluated expression context,
3691   // so side effects could result in unintended consequences.
3692   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3693       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3694     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3695 
3696   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3697                                        E->getSourceRange(), ExprKind))
3698     return true;
3699 
3700   if (ExprKind == UETT_SizeOf) {
3701     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3702       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3703         QualType OType = PVD->getOriginalType();
3704         QualType Type = PVD->getType();
3705         if (Type->isPointerType() && OType->isArrayType()) {
3706           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3707             << Type << OType;
3708           Diag(PVD->getLocation(), diag::note_declared_at);
3709         }
3710       }
3711     }
3712 
3713     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3714     // decays into a pointer and returns an unintended result. This is most
3715     // likely a typo for "sizeof(array) op x".
3716     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3717       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3718                                BO->getLHS());
3719       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720                                BO->getRHS());
3721     }
3722   }
3723 
3724   return false;
3725 }
3726 
3727 /// \brief Check the constraints on operands to unary expression and type
3728 /// traits.
3729 ///
3730 /// This will complete any types necessary, and validate the various constraints
3731 /// on those operands.
3732 ///
3733 /// The UsualUnaryConversions() function is *not* called by this routine.
3734 /// C99 6.3.2.1p[2-4] all state:
3735 ///   Except when it is the operand of the sizeof operator ...
3736 ///
3737 /// C++ [expr.sizeof]p4
3738 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3739 ///   standard conversions are not applied to the operand of sizeof.
3740 ///
3741 /// This policy is followed for all of the unary trait expressions.
3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3743                                             SourceLocation OpLoc,
3744                                             SourceRange ExprRange,
3745                                             UnaryExprOrTypeTrait ExprKind) {
3746   if (ExprType->isDependentType())
3747     return false;
3748 
3749   // C++ [expr.sizeof]p2:
3750   //     When applied to a reference or a reference type, the result
3751   //     is the size of the referenced type.
3752   // C++11 [expr.alignof]p3:
3753   //     When alignof is applied to a reference type, the result
3754   //     shall be the alignment of the referenced type.
3755   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3756     ExprType = Ref->getPointeeType();
3757 
3758   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3759   //   When alignof or _Alignof is applied to an array type, the result
3760   //   is the alignment of the element type.
3761   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3762     ExprType = Context.getBaseElementType(ExprType);
3763 
3764   if (ExprKind == UETT_VecStep)
3765     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3766 
3767   // Whitelist some types as extensions
3768   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3769                                       ExprKind))
3770     return false;
3771 
3772   if (RequireCompleteType(OpLoc, ExprType,
3773                           diag::err_sizeof_alignof_incomplete_type,
3774                           ExprKind, ExprRange))
3775     return true;
3776 
3777   if (ExprType->isFunctionType()) {
3778     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3779       << ExprKind << ExprRange;
3780     return true;
3781   }
3782 
3783   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3784                                        ExprKind))
3785     return true;
3786 
3787   return false;
3788 }
3789 
3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3791   E = E->IgnoreParens();
3792 
3793   // Cannot know anything else if the expression is dependent.
3794   if (E->isTypeDependent())
3795     return false;
3796 
3797   if (E->getObjectKind() == OK_BitField) {
3798     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3799        << 1 << E->getSourceRange();
3800     return true;
3801   }
3802 
3803   ValueDecl *D = nullptr;
3804   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3805     D = DRE->getDecl();
3806   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3807     D = ME->getMemberDecl();
3808   }
3809 
3810   // If it's a field, require the containing struct to have a
3811   // complete definition so that we can compute the layout.
3812   //
3813   // This can happen in C++11 onwards, either by naming the member
3814   // in a way that is not transformed into a member access expression
3815   // (in an unevaluated operand, for instance), or by naming the member
3816   // in a trailing-return-type.
3817   //
3818   // For the record, since __alignof__ on expressions is a GCC
3819   // extension, GCC seems to permit this but always gives the
3820   // nonsensical answer 0.
3821   //
3822   // We don't really need the layout here --- we could instead just
3823   // directly check for all the appropriate alignment-lowing
3824   // attributes --- but that would require duplicating a lot of
3825   // logic that just isn't worth duplicating for such a marginal
3826   // use-case.
3827   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3828     // Fast path this check, since we at least know the record has a
3829     // definition if we can find a member of it.
3830     if (!FD->getParent()->isCompleteDefinition()) {
3831       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3832         << E->getSourceRange();
3833       return true;
3834     }
3835 
3836     // Otherwise, if it's a field, and the field doesn't have
3837     // reference type, then it must have a complete type (or be a
3838     // flexible array member, which we explicitly want to
3839     // white-list anyway), which makes the following checks trivial.
3840     if (!FD->getType()->isReferenceType())
3841       return false;
3842   }
3843 
3844   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3845 }
3846 
3847 bool Sema::CheckVecStepExpr(Expr *E) {
3848   E = E->IgnoreParens();
3849 
3850   // Cannot know anything else if the expression is dependent.
3851   if (E->isTypeDependent())
3852     return false;
3853 
3854   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3855 }
3856 
3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3858                                         CapturingScopeInfo *CSI) {
3859   assert(T->isVariablyModifiedType());
3860   assert(CSI != nullptr);
3861 
3862   // We're going to walk down into the type and look for VLA expressions.
3863   do {
3864     const Type *Ty = T.getTypePtr();
3865     switch (Ty->getTypeClass()) {
3866 #define TYPE(Class, Base)
3867 #define ABSTRACT_TYPE(Class, Base)
3868 #define NON_CANONICAL_TYPE(Class, Base)
3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3871 #include "clang/AST/TypeNodes.def"
3872       T = QualType();
3873       break;
3874     // These types are never variably-modified.
3875     case Type::Builtin:
3876     case Type::Complex:
3877     case Type::Vector:
3878     case Type::ExtVector:
3879     case Type::Record:
3880     case Type::Enum:
3881     case Type::Elaborated:
3882     case Type::TemplateSpecialization:
3883     case Type::ObjCObject:
3884     case Type::ObjCInterface:
3885     case Type::ObjCObjectPointer:
3886     case Type::ObjCTypeParam:
3887     case Type::Pipe:
3888       llvm_unreachable("type class is never variably-modified!");
3889     case Type::Adjusted:
3890       T = cast<AdjustedType>(Ty)->getOriginalType();
3891       break;
3892     case Type::Decayed:
3893       T = cast<DecayedType>(Ty)->getPointeeType();
3894       break;
3895     case Type::Pointer:
3896       T = cast<PointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::BlockPointer:
3899       T = cast<BlockPointerType>(Ty)->getPointeeType();
3900       break;
3901     case Type::LValueReference:
3902     case Type::RValueReference:
3903       T = cast<ReferenceType>(Ty)->getPointeeType();
3904       break;
3905     case Type::MemberPointer:
3906       T = cast<MemberPointerType>(Ty)->getPointeeType();
3907       break;
3908     case Type::ConstantArray:
3909     case Type::IncompleteArray:
3910       // Losing element qualification here is fine.
3911       T = cast<ArrayType>(Ty)->getElementType();
3912       break;
3913     case Type::VariableArray: {
3914       // Losing element qualification here is fine.
3915       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3916 
3917       // Unknown size indication requires no size computation.
3918       // Otherwise, evaluate and record it.
3919       if (auto Size = VAT->getSizeExpr()) {
3920         if (!CSI->isVLATypeCaptured(VAT)) {
3921           RecordDecl *CapRecord = nullptr;
3922           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3923             CapRecord = LSI->Lambda;
3924           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3925             CapRecord = CRSI->TheRecordDecl;
3926           }
3927           if (CapRecord) {
3928             auto ExprLoc = Size->getExprLoc();
3929             auto SizeType = Context.getSizeType();
3930             // Build the non-static data member.
3931             auto Field =
3932                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3933                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3934                                   /*BW*/ nullptr, /*Mutable*/ false,
3935                                   /*InitStyle*/ ICIS_NoInit);
3936             Field->setImplicit(true);
3937             Field->setAccess(AS_private);
3938             Field->setCapturedVLAType(VAT);
3939             CapRecord->addDecl(Field);
3940 
3941             CSI->addVLATypeCapture(ExprLoc, SizeType);
3942           }
3943         }
3944       }
3945       T = VAT->getElementType();
3946       break;
3947     }
3948     case Type::FunctionProto:
3949     case Type::FunctionNoProto:
3950       T = cast<FunctionType>(Ty)->getReturnType();
3951       break;
3952     case Type::Paren:
3953     case Type::TypeOf:
3954     case Type::UnaryTransform:
3955     case Type::Attributed:
3956     case Type::SubstTemplateTypeParm:
3957     case Type::PackExpansion:
3958       // Keep walking after single level desugaring.
3959       T = T.getSingleStepDesugaredType(Context);
3960       break;
3961     case Type::Typedef:
3962       T = cast<TypedefType>(Ty)->desugar();
3963       break;
3964     case Type::Decltype:
3965       T = cast<DecltypeType>(Ty)->desugar();
3966       break;
3967     case Type::Auto:
3968       T = cast<AutoType>(Ty)->getDeducedType();
3969       break;
3970     case Type::TypeOfExpr:
3971       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3972       break;
3973     case Type::Atomic:
3974       T = cast<AtomicType>(Ty)->getValueType();
3975       break;
3976     }
3977   } while (!T.isNull() && T->isVariablyModifiedType());
3978 }
3979 
3980 /// \brief Build a sizeof or alignof expression given a type operand.
3981 ExprResult
3982 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3983                                      SourceLocation OpLoc,
3984                                      UnaryExprOrTypeTrait ExprKind,
3985                                      SourceRange R) {
3986   if (!TInfo)
3987     return ExprError();
3988 
3989   QualType T = TInfo->getType();
3990 
3991   if (!T->isDependentType() &&
3992       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3993     return ExprError();
3994 
3995   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3996     if (auto *TT = T->getAs<TypedefType>()) {
3997       for (auto I = FunctionScopes.rbegin(),
3998                 E = std::prev(FunctionScopes.rend());
3999            I != E; ++I) {
4000         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4001         if (CSI == nullptr)
4002           break;
4003         DeclContext *DC = nullptr;
4004         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4005           DC = LSI->CallOperator;
4006         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4007           DC = CRSI->TheCapturedDecl;
4008         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4009           DC = BSI->TheDecl;
4010         if (DC) {
4011           if (DC->containsDecl(TT->getDecl()))
4012             break;
4013           captureVariablyModifiedType(Context, T, CSI);
4014         }
4015       }
4016     }
4017   }
4018 
4019   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4020   return new (Context) UnaryExprOrTypeTraitExpr(
4021       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4022 }
4023 
4024 /// \brief Build a sizeof or alignof expression given an expression
4025 /// operand.
4026 ExprResult
4027 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4028                                      UnaryExprOrTypeTrait ExprKind) {
4029   ExprResult PE = CheckPlaceholderExpr(E);
4030   if (PE.isInvalid())
4031     return ExprError();
4032 
4033   E = PE.get();
4034 
4035   // Verify that the operand is valid.
4036   bool isInvalid = false;
4037   if (E->isTypeDependent()) {
4038     // Delay type-checking for type-dependent expressions.
4039   } else if (ExprKind == UETT_AlignOf) {
4040     isInvalid = CheckAlignOfExpr(*this, E);
4041   } else if (ExprKind == UETT_VecStep) {
4042     isInvalid = CheckVecStepExpr(E);
4043   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4044       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4045       isInvalid = true;
4046   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4047     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4048     isInvalid = true;
4049   } else {
4050     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4051   }
4052 
4053   if (isInvalid)
4054     return ExprError();
4055 
4056   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4057     PE = TransformToPotentiallyEvaluated(E);
4058     if (PE.isInvalid()) return ExprError();
4059     E = PE.get();
4060   }
4061 
4062   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4063   return new (Context) UnaryExprOrTypeTraitExpr(
4064       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4065 }
4066 
4067 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4068 /// expr and the same for @c alignof and @c __alignof
4069 /// Note that the ArgRange is invalid if isType is false.
4070 ExprResult
4071 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4072                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4073                                     void *TyOrEx, SourceRange ArgRange) {
4074   // If error parsing type, ignore.
4075   if (!TyOrEx) return ExprError();
4076 
4077   if (IsType) {
4078     TypeSourceInfo *TInfo;
4079     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4080     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4081   }
4082 
4083   Expr *ArgEx = (Expr *)TyOrEx;
4084   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4085   return Result;
4086 }
4087 
4088 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4089                                      bool IsReal) {
4090   if (V.get()->isTypeDependent())
4091     return S.Context.DependentTy;
4092 
4093   // _Real and _Imag are only l-values for normal l-values.
4094   if (V.get()->getObjectKind() != OK_Ordinary) {
4095     V = S.DefaultLvalueConversion(V.get());
4096     if (V.isInvalid())
4097       return QualType();
4098   }
4099 
4100   // These operators return the element type of a complex type.
4101   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4102     return CT->getElementType();
4103 
4104   // Otherwise they pass through real integer and floating point types here.
4105   if (V.get()->getType()->isArithmeticType())
4106     return V.get()->getType();
4107 
4108   // Test for placeholders.
4109   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4110   if (PR.isInvalid()) return QualType();
4111   if (PR.get() != V.get()) {
4112     V = PR;
4113     return CheckRealImagOperand(S, V, Loc, IsReal);
4114   }
4115 
4116   // Reject anything else.
4117   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4118     << (IsReal ? "__real" : "__imag");
4119   return QualType();
4120 }
4121 
4122 
4123 
4124 ExprResult
4125 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4126                           tok::TokenKind Kind, Expr *Input) {
4127   UnaryOperatorKind Opc;
4128   switch (Kind) {
4129   default: llvm_unreachable("Unknown unary op!");
4130   case tok::plusplus:   Opc = UO_PostInc; break;
4131   case tok::minusminus: Opc = UO_PostDec; break;
4132   }
4133 
4134   // Since this might is a postfix expression, get rid of ParenListExprs.
4135   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4136   if (Result.isInvalid()) return ExprError();
4137   Input = Result.get();
4138 
4139   return BuildUnaryOp(S, OpLoc, Opc, Input);
4140 }
4141 
4142 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4143 ///
4144 /// \return true on error
4145 static bool checkArithmeticOnObjCPointer(Sema &S,
4146                                          SourceLocation opLoc,
4147                                          Expr *op) {
4148   assert(op->getType()->isObjCObjectPointerType());
4149   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4150       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4151     return false;
4152 
4153   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4154     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4155     << op->getSourceRange();
4156   return true;
4157 }
4158 
4159 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4160   auto *BaseNoParens = Base->IgnoreParens();
4161   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4162     return MSProp->getPropertyDecl()->getType()->isArrayType();
4163   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4164 }
4165 
4166 ExprResult
4167 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4168                               Expr *idx, SourceLocation rbLoc) {
4169   if (base && !base->getType().isNull() &&
4170       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4171     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4172                                     /*Length=*/nullptr, rbLoc);
4173 
4174   // Since this might be a postfix expression, get rid of ParenListExprs.
4175   if (isa<ParenListExpr>(base)) {
4176     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4177     if (result.isInvalid()) return ExprError();
4178     base = result.get();
4179   }
4180 
4181   // Handle any non-overload placeholder types in the base and index
4182   // expressions.  We can't handle overloads here because the other
4183   // operand might be an overloadable type, in which case the overload
4184   // resolution for the operator overload should get the first crack
4185   // at the overload.
4186   bool IsMSPropertySubscript = false;
4187   if (base->getType()->isNonOverloadPlaceholderType()) {
4188     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4189     if (!IsMSPropertySubscript) {
4190       ExprResult result = CheckPlaceholderExpr(base);
4191       if (result.isInvalid())
4192         return ExprError();
4193       base = result.get();
4194     }
4195   }
4196   if (idx->getType()->isNonOverloadPlaceholderType()) {
4197     ExprResult result = CheckPlaceholderExpr(idx);
4198     if (result.isInvalid()) return ExprError();
4199     idx = result.get();
4200   }
4201 
4202   // Build an unanalyzed expression if either operand is type-dependent.
4203   if (getLangOpts().CPlusPlus &&
4204       (base->isTypeDependent() || idx->isTypeDependent())) {
4205     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4206                                             VK_LValue, OK_Ordinary, rbLoc);
4207   }
4208 
4209   // MSDN, property (C++)
4210   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4211   // This attribute can also be used in the declaration of an empty array in a
4212   // class or structure definition. For example:
4213   // __declspec(property(get=GetX, put=PutX)) int x[];
4214   // The above statement indicates that x[] can be used with one or more array
4215   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4216   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4217   if (IsMSPropertySubscript) {
4218     // Build MS property subscript expression if base is MS property reference
4219     // or MS property subscript.
4220     return new (Context) MSPropertySubscriptExpr(
4221         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4222   }
4223 
4224   // Use C++ overloaded-operator rules if either operand has record
4225   // type.  The spec says to do this if either type is *overloadable*,
4226   // but enum types can't declare subscript operators or conversion
4227   // operators, so there's nothing interesting for overload resolution
4228   // to do if there aren't any record types involved.
4229   //
4230   // ObjC pointers have their own subscripting logic that is not tied
4231   // to overload resolution and so should not take this path.
4232   if (getLangOpts().CPlusPlus &&
4233       (base->getType()->isRecordType() ||
4234        (!base->getType()->isObjCObjectPointerType() &&
4235         idx->getType()->isRecordType()))) {
4236     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4237   }
4238 
4239   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4240 }
4241 
4242 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4243                                           Expr *LowerBound,
4244                                           SourceLocation ColonLoc, Expr *Length,
4245                                           SourceLocation RBLoc) {
4246   if (Base->getType()->isPlaceholderType() &&
4247       !Base->getType()->isSpecificPlaceholderType(
4248           BuiltinType::OMPArraySection)) {
4249     ExprResult Result = CheckPlaceholderExpr(Base);
4250     if (Result.isInvalid())
4251       return ExprError();
4252     Base = Result.get();
4253   }
4254   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4255     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4256     if (Result.isInvalid())
4257       return ExprError();
4258     Result = DefaultLvalueConversion(Result.get());
4259     if (Result.isInvalid())
4260       return ExprError();
4261     LowerBound = Result.get();
4262   }
4263   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4264     ExprResult Result = CheckPlaceholderExpr(Length);
4265     if (Result.isInvalid())
4266       return ExprError();
4267     Result = DefaultLvalueConversion(Result.get());
4268     if (Result.isInvalid())
4269       return ExprError();
4270     Length = Result.get();
4271   }
4272 
4273   // Build an unanalyzed expression if either operand is type-dependent.
4274   if (Base->isTypeDependent() ||
4275       (LowerBound &&
4276        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4277       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4278     return new (Context)
4279         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4280                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4281   }
4282 
4283   // Perform default conversions.
4284   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4285   QualType ResultTy;
4286   if (OriginalTy->isAnyPointerType()) {
4287     ResultTy = OriginalTy->getPointeeType();
4288   } else if (OriginalTy->isArrayType()) {
4289     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4290   } else {
4291     return ExprError(
4292         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4293         << Base->getSourceRange());
4294   }
4295   // C99 6.5.2.1p1
4296   if (LowerBound) {
4297     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4298                                                       LowerBound);
4299     if (Res.isInvalid())
4300       return ExprError(Diag(LowerBound->getExprLoc(),
4301                             diag::err_omp_typecheck_section_not_integer)
4302                        << 0 << LowerBound->getSourceRange());
4303     LowerBound = Res.get();
4304 
4305     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4306         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4307       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4308           << 0 << LowerBound->getSourceRange();
4309   }
4310   if (Length) {
4311     auto Res =
4312         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4313     if (Res.isInvalid())
4314       return ExprError(Diag(Length->getExprLoc(),
4315                             diag::err_omp_typecheck_section_not_integer)
4316                        << 1 << Length->getSourceRange());
4317     Length = Res.get();
4318 
4319     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4320         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4321       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4322           << 1 << Length->getSourceRange();
4323   }
4324 
4325   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4326   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4327   // type. Note that functions are not objects, and that (in C99 parlance)
4328   // incomplete types are not object types.
4329   if (ResultTy->isFunctionType()) {
4330     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4331         << ResultTy << Base->getSourceRange();
4332     return ExprError();
4333   }
4334 
4335   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4336                           diag::err_omp_section_incomplete_type, Base))
4337     return ExprError();
4338 
4339   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4340     llvm::APSInt LowerBoundValue;
4341     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4342       // OpenMP 4.5, [2.4 Array Sections]
4343       // The array section must be a subset of the original array.
4344       if (LowerBoundValue.isNegative()) {
4345         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4346             << LowerBound->getSourceRange();
4347         return ExprError();
4348       }
4349     }
4350   }
4351 
4352   if (Length) {
4353     llvm::APSInt LengthValue;
4354     if (Length->EvaluateAsInt(LengthValue, Context)) {
4355       // OpenMP 4.5, [2.4 Array Sections]
4356       // The length must evaluate to non-negative integers.
4357       if (LengthValue.isNegative()) {
4358         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4359             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4360             << Length->getSourceRange();
4361         return ExprError();
4362       }
4363     }
4364   } else if (ColonLoc.isValid() &&
4365              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4366                                       !OriginalTy->isVariableArrayType()))) {
4367     // OpenMP 4.5, [2.4 Array Sections]
4368     // When the size of the array dimension is not known, the length must be
4369     // specified explicitly.
4370     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4371         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4372     return ExprError();
4373   }
4374 
4375   if (!Base->getType()->isSpecificPlaceholderType(
4376           BuiltinType::OMPArraySection)) {
4377     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4378     if (Result.isInvalid())
4379       return ExprError();
4380     Base = Result.get();
4381   }
4382   return new (Context)
4383       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4384                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4385 }
4386 
4387 ExprResult
4388 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4389                                       Expr *Idx, SourceLocation RLoc) {
4390   Expr *LHSExp = Base;
4391   Expr *RHSExp = Idx;
4392 
4393   ExprValueKind VK = VK_LValue;
4394   ExprObjectKind OK = OK_Ordinary;
4395 
4396   // Per C++ core issue 1213, the result is an xvalue if either operand is
4397   // a non-lvalue array, and an lvalue otherwise.
4398   if (getLangOpts().CPlusPlus11 &&
4399       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4400        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4401     VK = VK_XValue;
4402 
4403   // Perform default conversions.
4404   if (!LHSExp->getType()->getAs<VectorType>()) {
4405     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4406     if (Result.isInvalid())
4407       return ExprError();
4408     LHSExp = Result.get();
4409   }
4410   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4411   if (Result.isInvalid())
4412     return ExprError();
4413   RHSExp = Result.get();
4414 
4415   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4416 
4417   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4418   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4419   // in the subscript position. As a result, we need to derive the array base
4420   // and index from the expression types.
4421   Expr *BaseExpr, *IndexExpr;
4422   QualType ResultType;
4423   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4424     BaseExpr = LHSExp;
4425     IndexExpr = RHSExp;
4426     ResultType = Context.DependentTy;
4427   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4428     BaseExpr = LHSExp;
4429     IndexExpr = RHSExp;
4430     ResultType = PTy->getPointeeType();
4431   } else if (const ObjCObjectPointerType *PTy =
4432                LHSTy->getAs<ObjCObjectPointerType>()) {
4433     BaseExpr = LHSExp;
4434     IndexExpr = RHSExp;
4435 
4436     // Use custom logic if this should be the pseudo-object subscript
4437     // expression.
4438     if (!LangOpts.isSubscriptPointerArithmetic())
4439       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4440                                           nullptr);
4441 
4442     ResultType = PTy->getPointeeType();
4443   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4444      // Handle the uncommon case of "123[Ptr]".
4445     BaseExpr = RHSExp;
4446     IndexExpr = LHSExp;
4447     ResultType = PTy->getPointeeType();
4448   } else if (const ObjCObjectPointerType *PTy =
4449                RHSTy->getAs<ObjCObjectPointerType>()) {
4450      // Handle the uncommon case of "123[Ptr]".
4451     BaseExpr = RHSExp;
4452     IndexExpr = LHSExp;
4453     ResultType = PTy->getPointeeType();
4454     if (!LangOpts.isSubscriptPointerArithmetic()) {
4455       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4456         << ResultType << BaseExpr->getSourceRange();
4457       return ExprError();
4458     }
4459   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4460     BaseExpr = LHSExp;    // vectors: V[123]
4461     IndexExpr = RHSExp;
4462     VK = LHSExp->getValueKind();
4463     if (VK != VK_RValue)
4464       OK = OK_VectorComponent;
4465 
4466     // FIXME: need to deal with const...
4467     ResultType = VTy->getElementType();
4468   } else if (LHSTy->isArrayType()) {
4469     // If we see an array that wasn't promoted by
4470     // DefaultFunctionArrayLvalueConversion, it must be an array that
4471     // wasn't promoted because of the C90 rule that doesn't
4472     // allow promoting non-lvalue arrays.  Warn, then
4473     // force the promotion here.
4474     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4475         LHSExp->getSourceRange();
4476     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4477                                CK_ArrayToPointerDecay).get();
4478     LHSTy = LHSExp->getType();
4479 
4480     BaseExpr = LHSExp;
4481     IndexExpr = RHSExp;
4482     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4483   } else if (RHSTy->isArrayType()) {
4484     // Same as previous, except for 123[f().a] case
4485     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4486         RHSExp->getSourceRange();
4487     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4488                                CK_ArrayToPointerDecay).get();
4489     RHSTy = RHSExp->getType();
4490 
4491     BaseExpr = RHSExp;
4492     IndexExpr = LHSExp;
4493     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4494   } else {
4495     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4496        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4497   }
4498   // C99 6.5.2.1p1
4499   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4500     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4501                      << IndexExpr->getSourceRange());
4502 
4503   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4504        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4505          && !IndexExpr->isTypeDependent())
4506     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4507 
4508   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4509   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4510   // type. Note that Functions are not objects, and that (in C99 parlance)
4511   // incomplete types are not object types.
4512   if (ResultType->isFunctionType()) {
4513     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4514       << ResultType << BaseExpr->getSourceRange();
4515     return ExprError();
4516   }
4517 
4518   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4519     // GNU extension: subscripting on pointer to void
4520     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4521       << BaseExpr->getSourceRange();
4522 
4523     // C forbids expressions of unqualified void type from being l-values.
4524     // See IsCForbiddenLValueType.
4525     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4526   } else if (!ResultType->isDependentType() &&
4527       RequireCompleteType(LLoc, ResultType,
4528                           diag::err_subscript_incomplete_type, BaseExpr))
4529     return ExprError();
4530 
4531   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4532          !ResultType.isCForbiddenLValueType());
4533 
4534   return new (Context)
4535       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4536 }
4537 
4538 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4539                                   ParmVarDecl *Param) {
4540   if (Param->hasUnparsedDefaultArg()) {
4541     Diag(CallLoc,
4542          diag::err_use_of_default_argument_to_function_declared_later) <<
4543       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4544     Diag(UnparsedDefaultArgLocs[Param],
4545          diag::note_default_argument_declared_here);
4546     return true;
4547   }
4548 
4549   if (Param->hasUninstantiatedDefaultArg()) {
4550     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4551 
4552     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4553                                                  Param);
4554 
4555     // Instantiate the expression.
4556     MultiLevelTemplateArgumentList MutiLevelArgList
4557       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4558 
4559     InstantiatingTemplate Inst(*this, CallLoc, Param,
4560                                MutiLevelArgList.getInnermost());
4561     if (Inst.isInvalid())
4562       return true;
4563     if (Inst.isAlreadyInstantiating()) {
4564       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4565       Param->setInvalidDecl();
4566       return true;
4567     }
4568 
4569     ExprResult Result;
4570     {
4571       // C++ [dcl.fct.default]p5:
4572       //   The names in the [default argument] expression are bound, and
4573       //   the semantic constraints are checked, at the point where the
4574       //   default argument expression appears.
4575       ContextRAII SavedContext(*this, FD);
4576       LocalInstantiationScope Local(*this);
4577       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4578                                 /*DirectInit*/false);
4579     }
4580     if (Result.isInvalid())
4581       return true;
4582 
4583     // Check the expression as an initializer for the parameter.
4584     InitializedEntity Entity
4585       = InitializedEntity::InitializeParameter(Context, Param);
4586     InitializationKind Kind
4587       = InitializationKind::CreateCopy(Param->getLocation(),
4588              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4589     Expr *ResultE = Result.getAs<Expr>();
4590 
4591     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4592     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4593     if (Result.isInvalid())
4594       return true;
4595 
4596     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4597                                  Param->getOuterLocStart());
4598     if (Result.isInvalid())
4599       return true;
4600 
4601     // Remember the instantiated default argument.
4602     Param->setDefaultArg(Result.getAs<Expr>());
4603     if (ASTMutationListener *L = getASTMutationListener()) {
4604       L->DefaultArgumentInstantiated(Param);
4605     }
4606   }
4607 
4608   // If the default argument expression is not set yet, we are building it now.
4609   if (!Param->hasInit()) {
4610     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4611     Param->setInvalidDecl();
4612     return true;
4613   }
4614 
4615   // If the default expression creates temporaries, we need to
4616   // push them to the current stack of expression temporaries so they'll
4617   // be properly destroyed.
4618   // FIXME: We should really be rebuilding the default argument with new
4619   // bound temporaries; see the comment in PR5810.
4620   // We don't need to do that with block decls, though, because
4621   // blocks in default argument expression can never capture anything.
4622   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4623     // Set the "needs cleanups" bit regardless of whether there are
4624     // any explicit objects.
4625     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4626 
4627     // Append all the objects to the cleanup list.  Right now, this
4628     // should always be a no-op, because blocks in default argument
4629     // expressions should never be able to capture anything.
4630     assert(!Init->getNumObjects() &&
4631            "default argument expression has capturing blocks?");
4632   }
4633 
4634   // We already type-checked the argument, so we know it works.
4635   // Just mark all of the declarations in this potentially-evaluated expression
4636   // as being "referenced".
4637   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4638                                    /*SkipLocalVariables=*/true);
4639   return false;
4640 }
4641 
4642 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4643                                         FunctionDecl *FD, ParmVarDecl *Param) {
4644   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4645     return ExprError();
4646   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4647 }
4648 
4649 Sema::VariadicCallType
4650 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4651                           Expr *Fn) {
4652   if (Proto && Proto->isVariadic()) {
4653     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4654       return VariadicConstructor;
4655     else if (Fn && Fn->getType()->isBlockPointerType())
4656       return VariadicBlock;
4657     else if (FDecl) {
4658       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4659         if (Method->isInstance())
4660           return VariadicMethod;
4661     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4662       return VariadicMethod;
4663     return VariadicFunction;
4664   }
4665   return VariadicDoesNotApply;
4666 }
4667 
4668 namespace {
4669 class FunctionCallCCC : public FunctionCallFilterCCC {
4670 public:
4671   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4672                   unsigned NumArgs, MemberExpr *ME)
4673       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4674         FunctionName(FuncName) {}
4675 
4676   bool ValidateCandidate(const TypoCorrection &candidate) override {
4677     if (!candidate.getCorrectionSpecifier() ||
4678         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4679       return false;
4680     }
4681 
4682     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4683   }
4684 
4685 private:
4686   const IdentifierInfo *const FunctionName;
4687 };
4688 }
4689 
4690 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4691                                                FunctionDecl *FDecl,
4692                                                ArrayRef<Expr *> Args) {
4693   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4694   DeclarationName FuncName = FDecl->getDeclName();
4695   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4696 
4697   if (TypoCorrection Corrected = S.CorrectTypo(
4698           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4699           S.getScopeForContext(S.CurContext), nullptr,
4700           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4701                                              Args.size(), ME),
4702           Sema::CTK_ErrorRecovery)) {
4703     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4704       if (Corrected.isOverloaded()) {
4705         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4706         OverloadCandidateSet::iterator Best;
4707         for (NamedDecl *CD : Corrected) {
4708           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4709             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4710                                    OCS);
4711         }
4712         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4713         case OR_Success:
4714           ND = Best->FoundDecl;
4715           Corrected.setCorrectionDecl(ND);
4716           break;
4717         default:
4718           break;
4719         }
4720       }
4721       ND = ND->getUnderlyingDecl();
4722       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4723         return Corrected;
4724     }
4725   }
4726   return TypoCorrection();
4727 }
4728 
4729 /// ConvertArgumentsForCall - Converts the arguments specified in
4730 /// Args/NumArgs to the parameter types of the function FDecl with
4731 /// function prototype Proto. Call is the call expression itself, and
4732 /// Fn is the function expression. For a C++ member function, this
4733 /// routine does not attempt to convert the object argument. Returns
4734 /// true if the call is ill-formed.
4735 bool
4736 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4737                               FunctionDecl *FDecl,
4738                               const FunctionProtoType *Proto,
4739                               ArrayRef<Expr *> Args,
4740                               SourceLocation RParenLoc,
4741                               bool IsExecConfig) {
4742   // Bail out early if calling a builtin with custom typechecking.
4743   if (FDecl)
4744     if (unsigned ID = FDecl->getBuiltinID())
4745       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4746         return false;
4747 
4748   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4749   // assignment, to the types of the corresponding parameter, ...
4750   unsigned NumParams = Proto->getNumParams();
4751   bool Invalid = false;
4752   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4753   unsigned FnKind = Fn->getType()->isBlockPointerType()
4754                        ? 1 /* block */
4755                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4756                                        : 0 /* function */);
4757 
4758   // If too few arguments are available (and we don't have default
4759   // arguments for the remaining parameters), don't make the call.
4760   if (Args.size() < NumParams) {
4761     if (Args.size() < MinArgs) {
4762       TypoCorrection TC;
4763       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4764         unsigned diag_id =
4765             MinArgs == NumParams && !Proto->isVariadic()
4766                 ? diag::err_typecheck_call_too_few_args_suggest
4767                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4768         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4769                                         << static_cast<unsigned>(Args.size())
4770                                         << TC.getCorrectionRange());
4771       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4772         Diag(RParenLoc,
4773              MinArgs == NumParams && !Proto->isVariadic()
4774                  ? diag::err_typecheck_call_too_few_args_one
4775                  : diag::err_typecheck_call_too_few_args_at_least_one)
4776             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4777       else
4778         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4779                             ? diag::err_typecheck_call_too_few_args
4780                             : diag::err_typecheck_call_too_few_args_at_least)
4781             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4782             << Fn->getSourceRange();
4783 
4784       // Emit the location of the prototype.
4785       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4786         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4787           << FDecl;
4788 
4789       return true;
4790     }
4791     Call->setNumArgs(Context, NumParams);
4792   }
4793 
4794   // If too many are passed and not variadic, error on the extras and drop
4795   // them.
4796   if (Args.size() > NumParams) {
4797     if (!Proto->isVariadic()) {
4798       TypoCorrection TC;
4799       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4800         unsigned diag_id =
4801             MinArgs == NumParams && !Proto->isVariadic()
4802                 ? diag::err_typecheck_call_too_many_args_suggest
4803                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4804         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4805                                         << static_cast<unsigned>(Args.size())
4806                                         << TC.getCorrectionRange());
4807       } else if (NumParams == 1 && FDecl &&
4808                  FDecl->getParamDecl(0)->getDeclName())
4809         Diag(Args[NumParams]->getLocStart(),
4810              MinArgs == NumParams
4811                  ? diag::err_typecheck_call_too_many_args_one
4812                  : diag::err_typecheck_call_too_many_args_at_most_one)
4813             << FnKind << FDecl->getParamDecl(0)
4814             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4815             << SourceRange(Args[NumParams]->getLocStart(),
4816                            Args.back()->getLocEnd());
4817       else
4818         Diag(Args[NumParams]->getLocStart(),
4819              MinArgs == NumParams
4820                  ? diag::err_typecheck_call_too_many_args
4821                  : diag::err_typecheck_call_too_many_args_at_most)
4822             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4823             << Fn->getSourceRange()
4824             << SourceRange(Args[NumParams]->getLocStart(),
4825                            Args.back()->getLocEnd());
4826 
4827       // Emit the location of the prototype.
4828       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4829         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4830           << FDecl;
4831 
4832       // This deletes the extra arguments.
4833       Call->setNumArgs(Context, NumParams);
4834       return true;
4835     }
4836   }
4837   SmallVector<Expr *, 8> AllArgs;
4838   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4839 
4840   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4841                                    Proto, 0, Args, AllArgs, CallType);
4842   if (Invalid)
4843     return true;
4844   unsigned TotalNumArgs = AllArgs.size();
4845   for (unsigned i = 0; i < TotalNumArgs; ++i)
4846     Call->setArg(i, AllArgs[i]);
4847 
4848   return false;
4849 }
4850 
4851 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4852                                   const FunctionProtoType *Proto,
4853                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4854                                   SmallVectorImpl<Expr *> &AllArgs,
4855                                   VariadicCallType CallType, bool AllowExplicit,
4856                                   bool IsListInitialization) {
4857   unsigned NumParams = Proto->getNumParams();
4858   bool Invalid = false;
4859   size_t ArgIx = 0;
4860   // Continue to check argument types (even if we have too few/many args).
4861   for (unsigned i = FirstParam; i < NumParams; i++) {
4862     QualType ProtoArgType = Proto->getParamType(i);
4863 
4864     Expr *Arg;
4865     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4866     if (ArgIx < Args.size()) {
4867       Arg = Args[ArgIx++];
4868 
4869       if (RequireCompleteType(Arg->getLocStart(),
4870                               ProtoArgType,
4871                               diag::err_call_incomplete_argument, Arg))
4872         return true;
4873 
4874       // Strip the unbridged-cast placeholder expression off, if applicable.
4875       bool CFAudited = false;
4876       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4877           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4878           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4879         Arg = stripARCUnbridgedCast(Arg);
4880       else if (getLangOpts().ObjCAutoRefCount &&
4881                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4882                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4883         CFAudited = true;
4884 
4885       InitializedEntity Entity =
4886           Param ? InitializedEntity::InitializeParameter(Context, Param,
4887                                                          ProtoArgType)
4888                 : InitializedEntity::InitializeParameter(
4889                       Context, ProtoArgType, Proto->isParamConsumed(i));
4890 
4891       // Remember that parameter belongs to a CF audited API.
4892       if (CFAudited)
4893         Entity.setParameterCFAudited();
4894 
4895       ExprResult ArgE = PerformCopyInitialization(
4896           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4897       if (ArgE.isInvalid())
4898         return true;
4899 
4900       Arg = ArgE.getAs<Expr>();
4901     } else {
4902       assert(Param && "can't use default arguments without a known callee");
4903 
4904       ExprResult ArgExpr =
4905         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4906       if (ArgExpr.isInvalid())
4907         return true;
4908 
4909       Arg = ArgExpr.getAs<Expr>();
4910     }
4911 
4912     // Check for array bounds violations for each argument to the call. This
4913     // check only triggers warnings when the argument isn't a more complex Expr
4914     // with its own checking, such as a BinaryOperator.
4915     CheckArrayAccess(Arg);
4916 
4917     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4918     CheckStaticArrayArgument(CallLoc, Param, Arg);
4919 
4920     AllArgs.push_back(Arg);
4921   }
4922 
4923   // If this is a variadic call, handle args passed through "...".
4924   if (CallType != VariadicDoesNotApply) {
4925     // Assume that extern "C" functions with variadic arguments that
4926     // return __unknown_anytype aren't *really* variadic.
4927     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4928         FDecl->isExternC()) {
4929       for (Expr *A : Args.slice(ArgIx)) {
4930         QualType paramType; // ignored
4931         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4932         Invalid |= arg.isInvalid();
4933         AllArgs.push_back(arg.get());
4934       }
4935 
4936     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4937     } else {
4938       for (Expr *A : Args.slice(ArgIx)) {
4939         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4940         Invalid |= Arg.isInvalid();
4941         AllArgs.push_back(Arg.get());
4942       }
4943     }
4944 
4945     // Check for array bounds violations.
4946     for (Expr *A : Args.slice(ArgIx))
4947       CheckArrayAccess(A);
4948   }
4949   return Invalid;
4950 }
4951 
4952 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4953   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4954   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4955     TL = DTL.getOriginalLoc();
4956   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4957     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4958       << ATL.getLocalSourceRange();
4959 }
4960 
4961 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4962 /// array parameter, check that it is non-null, and that if it is formed by
4963 /// array-to-pointer decay, the underlying array is sufficiently large.
4964 ///
4965 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4966 /// array type derivation, then for each call to the function, the value of the
4967 /// corresponding actual argument shall provide access to the first element of
4968 /// an array with at least as many elements as specified by the size expression.
4969 void
4970 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4971                                ParmVarDecl *Param,
4972                                const Expr *ArgExpr) {
4973   // Static array parameters are not supported in C++.
4974   if (!Param || getLangOpts().CPlusPlus)
4975     return;
4976 
4977   QualType OrigTy = Param->getOriginalType();
4978 
4979   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4980   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4981     return;
4982 
4983   if (ArgExpr->isNullPointerConstant(Context,
4984                                      Expr::NPC_NeverValueDependent)) {
4985     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4986     DiagnoseCalleeStaticArrayParam(*this, Param);
4987     return;
4988   }
4989 
4990   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4991   if (!CAT)
4992     return;
4993 
4994   const ConstantArrayType *ArgCAT =
4995     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4996   if (!ArgCAT)
4997     return;
4998 
4999   if (ArgCAT->getSize().ult(CAT->getSize())) {
5000     Diag(CallLoc, diag::warn_static_array_too_small)
5001       << ArgExpr->getSourceRange()
5002       << (unsigned) ArgCAT->getSize().getZExtValue()
5003       << (unsigned) CAT->getSize().getZExtValue();
5004     DiagnoseCalleeStaticArrayParam(*this, Param);
5005   }
5006 }
5007 
5008 /// Given a function expression of unknown-any type, try to rebuild it
5009 /// to have a function type.
5010 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5011 
5012 /// Is the given type a placeholder that we need to lower out
5013 /// immediately during argument processing?
5014 static bool isPlaceholderToRemoveAsArg(QualType type) {
5015   // Placeholders are never sugared.
5016   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5017   if (!placeholder) return false;
5018 
5019   switch (placeholder->getKind()) {
5020   // Ignore all the non-placeholder types.
5021 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5022   case BuiltinType::Id:
5023 #include "clang/Basic/OpenCLImageTypes.def"
5024 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5025 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5026 #include "clang/AST/BuiltinTypes.def"
5027     return false;
5028 
5029   // We cannot lower out overload sets; they might validly be resolved
5030   // by the call machinery.
5031   case BuiltinType::Overload:
5032     return false;
5033 
5034   // Unbridged casts in ARC can be handled in some call positions and
5035   // should be left in place.
5036   case BuiltinType::ARCUnbridgedCast:
5037     return false;
5038 
5039   // Pseudo-objects should be converted as soon as possible.
5040   case BuiltinType::PseudoObject:
5041     return true;
5042 
5043   // The debugger mode could theoretically but currently does not try
5044   // to resolve unknown-typed arguments based on known parameter types.
5045   case BuiltinType::UnknownAny:
5046     return true;
5047 
5048   // These are always invalid as call arguments and should be reported.
5049   case BuiltinType::BoundMember:
5050   case BuiltinType::BuiltinFn:
5051   case BuiltinType::OMPArraySection:
5052     return true;
5053 
5054   }
5055   llvm_unreachable("bad builtin type kind");
5056 }
5057 
5058 /// Check an argument list for placeholders that we won't try to
5059 /// handle later.
5060 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5061   // Apply this processing to all the arguments at once instead of
5062   // dying at the first failure.
5063   bool hasInvalid = false;
5064   for (size_t i = 0, e = args.size(); i != e; i++) {
5065     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5066       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5067       if (result.isInvalid()) hasInvalid = true;
5068       else args[i] = result.get();
5069     } else if (hasInvalid) {
5070       (void)S.CorrectDelayedTyposInExpr(args[i]);
5071     }
5072   }
5073   return hasInvalid;
5074 }
5075 
5076 /// If a builtin function has a pointer argument with no explicit address
5077 /// space, then it should be able to accept a pointer to any address
5078 /// space as input.  In order to do this, we need to replace the
5079 /// standard builtin declaration with one that uses the same address space
5080 /// as the call.
5081 ///
5082 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5083 ///                  it does not contain any pointer arguments without
5084 ///                  an address space qualifer.  Otherwise the rewritten
5085 ///                  FunctionDecl is returned.
5086 /// TODO: Handle pointer return types.
5087 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5088                                                 const FunctionDecl *FDecl,
5089                                                 MultiExprArg ArgExprs) {
5090 
5091   QualType DeclType = FDecl->getType();
5092   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5093 
5094   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5095       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5096     return nullptr;
5097 
5098   bool NeedsNewDecl = false;
5099   unsigned i = 0;
5100   SmallVector<QualType, 8> OverloadParams;
5101 
5102   for (QualType ParamType : FT->param_types()) {
5103 
5104     // Convert array arguments to pointer to simplify type lookup.
5105     ExprResult ArgRes =
5106         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5107     if (ArgRes.isInvalid())
5108       return nullptr;
5109     Expr *Arg = ArgRes.get();
5110     QualType ArgType = Arg->getType();
5111     if (!ParamType->isPointerType() ||
5112         ParamType.getQualifiers().hasAddressSpace() ||
5113         !ArgType->isPointerType() ||
5114         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5115       OverloadParams.push_back(ParamType);
5116       continue;
5117     }
5118 
5119     NeedsNewDecl = true;
5120     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5121 
5122     QualType PointeeType = ParamType->getPointeeType();
5123     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5124     OverloadParams.push_back(Context.getPointerType(PointeeType));
5125   }
5126 
5127   if (!NeedsNewDecl)
5128     return nullptr;
5129 
5130   FunctionProtoType::ExtProtoInfo EPI;
5131   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5132                                                 OverloadParams, EPI);
5133   DeclContext *Parent = Context.getTranslationUnitDecl();
5134   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5135                                                     FDecl->getLocation(),
5136                                                     FDecl->getLocation(),
5137                                                     FDecl->getIdentifier(),
5138                                                     OverloadTy,
5139                                                     /*TInfo=*/nullptr,
5140                                                     SC_Extern, false,
5141                                                     /*hasPrototype=*/true);
5142   SmallVector<ParmVarDecl*, 16> Params;
5143   FT = cast<FunctionProtoType>(OverloadTy);
5144   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5145     QualType ParamType = FT->getParamType(i);
5146     ParmVarDecl *Parm =
5147         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5148                                 SourceLocation(), nullptr, ParamType,
5149                                 /*TInfo=*/nullptr, SC_None, nullptr);
5150     Parm->setScopeInfo(0, i);
5151     Params.push_back(Parm);
5152   }
5153   OverloadDecl->setParams(Params);
5154   return OverloadDecl;
5155 }
5156 
5157 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5158                                        std::size_t NumArgs) {
5159   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5160                          /*PartialOverloading=*/false))
5161     return Callee->isVariadic();
5162   return Callee->getMinRequiredArguments() <= NumArgs;
5163 }
5164 
5165 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5166 /// This provides the location of the left/right parens and a list of comma
5167 /// locations.
5168 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5169                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5170                                Expr *ExecConfig, bool IsExecConfig) {
5171   // Since this might be a postfix expression, get rid of ParenListExprs.
5172   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5173   if (Result.isInvalid()) return ExprError();
5174   Fn = Result.get();
5175 
5176   if (checkArgsForPlaceholders(*this, ArgExprs))
5177     return ExprError();
5178 
5179   if (getLangOpts().CPlusPlus) {
5180     // If this is a pseudo-destructor expression, build the call immediately.
5181     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5182       if (!ArgExprs.empty()) {
5183         // Pseudo-destructor calls should not have any arguments.
5184         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5185             << FixItHint::CreateRemoval(
5186                    SourceRange(ArgExprs.front()->getLocStart(),
5187                                ArgExprs.back()->getLocEnd()));
5188       }
5189 
5190       return new (Context)
5191           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5192     }
5193     if (Fn->getType() == Context.PseudoObjectTy) {
5194       ExprResult result = CheckPlaceholderExpr(Fn);
5195       if (result.isInvalid()) return ExprError();
5196       Fn = result.get();
5197     }
5198 
5199     // Determine whether this is a dependent call inside a C++ template,
5200     // in which case we won't do any semantic analysis now.
5201     bool Dependent = false;
5202     if (Fn->isTypeDependent())
5203       Dependent = true;
5204     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5205       Dependent = true;
5206 
5207     if (Dependent) {
5208       if (ExecConfig) {
5209         return new (Context) CUDAKernelCallExpr(
5210             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5211             Context.DependentTy, VK_RValue, RParenLoc);
5212       } else {
5213         return new (Context) CallExpr(
5214             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5215       }
5216     }
5217 
5218     // Determine whether this is a call to an object (C++ [over.call.object]).
5219     if (Fn->getType()->isRecordType())
5220       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5221                                           RParenLoc);
5222 
5223     if (Fn->getType() == Context.UnknownAnyTy) {
5224       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5225       if (result.isInvalid()) return ExprError();
5226       Fn = result.get();
5227     }
5228 
5229     if (Fn->getType() == Context.BoundMemberTy) {
5230       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5231                                        RParenLoc);
5232     }
5233   }
5234 
5235   // Check for overloaded calls.  This can happen even in C due to extensions.
5236   if (Fn->getType() == Context.OverloadTy) {
5237     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5238 
5239     // We aren't supposed to apply this logic for if there'Scope an '&'
5240     // involved.
5241     if (!find.HasFormOfMemberPointer) {
5242       OverloadExpr *ovl = find.Expression;
5243       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5244         return BuildOverloadedCallExpr(
5245             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5246             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5247       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5248                                        RParenLoc);
5249     }
5250   }
5251 
5252   // If we're directly calling a function, get the appropriate declaration.
5253   if (Fn->getType() == Context.UnknownAnyTy) {
5254     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5255     if (result.isInvalid()) return ExprError();
5256     Fn = result.get();
5257   }
5258 
5259   Expr *NakedFn = Fn->IgnoreParens();
5260 
5261   bool CallingNDeclIndirectly = false;
5262   NamedDecl *NDecl = nullptr;
5263   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5264     if (UnOp->getOpcode() == UO_AddrOf) {
5265       CallingNDeclIndirectly = true;
5266       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5267     }
5268   }
5269 
5270   if (isa<DeclRefExpr>(NakedFn)) {
5271     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5272 
5273     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5274     if (FDecl && FDecl->getBuiltinID()) {
5275       // Rewrite the function decl for this builtin by replacing parameters
5276       // with no explicit address space with the address space of the arguments
5277       // in ArgExprs.
5278       if ((FDecl =
5279                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5280         NDecl = FDecl;
5281         Fn = DeclRefExpr::Create(
5282             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5283             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5284       }
5285     }
5286   } else if (isa<MemberExpr>(NakedFn))
5287     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5288 
5289   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5290     if (CallingNDeclIndirectly &&
5291         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5292                                            Fn->getLocStart()))
5293       return ExprError();
5294 
5295     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5296       return ExprError();
5297 
5298     // CheckEnableIf assumes that the we're passing in a sane number of args for
5299     // FD, but that doesn't always hold true here. This is because, in some
5300     // cases, we'll emit a diag about an ill-formed function call, but then
5301     // we'll continue on as if the function call wasn't ill-formed. So, if the
5302     // number of args looks incorrect, don't do enable_if checks; we should've
5303     // already emitted an error about the bad call.
5304     if (FD->hasAttr<EnableIfAttr>() &&
5305         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5306       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5307         Diag(Fn->getLocStart(),
5308              isa<CXXMethodDecl>(FD)
5309                  ? diag::err_ovl_no_viable_member_function_in_call
5310                  : diag::err_ovl_no_viable_function_in_call)
5311             << FD << FD->getSourceRange();
5312         Diag(FD->getLocation(),
5313              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5314             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5315       }
5316     }
5317   }
5318 
5319   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5320                                ExecConfig, IsExecConfig);
5321 }
5322 
5323 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5324 ///
5325 /// __builtin_astype( value, dst type )
5326 ///
5327 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5328                                  SourceLocation BuiltinLoc,
5329                                  SourceLocation RParenLoc) {
5330   ExprValueKind VK = VK_RValue;
5331   ExprObjectKind OK = OK_Ordinary;
5332   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5333   QualType SrcTy = E->getType();
5334   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5335     return ExprError(Diag(BuiltinLoc,
5336                           diag::err_invalid_astype_of_different_size)
5337                      << DstTy
5338                      << SrcTy
5339                      << E->getSourceRange());
5340   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5341 }
5342 
5343 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5344 /// provided arguments.
5345 ///
5346 /// __builtin_convertvector( value, dst type )
5347 ///
5348 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5349                                         SourceLocation BuiltinLoc,
5350                                         SourceLocation RParenLoc) {
5351   TypeSourceInfo *TInfo;
5352   GetTypeFromParser(ParsedDestTy, &TInfo);
5353   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5354 }
5355 
5356 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5357 /// i.e. an expression not of \p OverloadTy.  The expression should
5358 /// unary-convert to an expression of function-pointer or
5359 /// block-pointer type.
5360 ///
5361 /// \param NDecl the declaration being called, if available
5362 ExprResult
5363 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5364                             SourceLocation LParenLoc,
5365                             ArrayRef<Expr *> Args,
5366                             SourceLocation RParenLoc,
5367                             Expr *Config, bool IsExecConfig) {
5368   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5369   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5370 
5371   // Functions with 'interrupt' attribute cannot be called directly.
5372   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5373     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5374     return ExprError();
5375   }
5376 
5377   // Promote the function operand.
5378   // We special-case function promotion here because we only allow promoting
5379   // builtin functions to function pointers in the callee of a call.
5380   ExprResult Result;
5381   if (BuiltinID &&
5382       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5383     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5384                                CK_BuiltinFnToFnPtr).get();
5385   } else {
5386     Result = CallExprUnaryConversions(Fn);
5387   }
5388   if (Result.isInvalid())
5389     return ExprError();
5390   Fn = Result.get();
5391 
5392   // Make the call expr early, before semantic checks.  This guarantees cleanup
5393   // of arguments and function on error.
5394   CallExpr *TheCall;
5395   if (Config)
5396     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5397                                                cast<CallExpr>(Config), Args,
5398                                                Context.BoolTy, VK_RValue,
5399                                                RParenLoc);
5400   else
5401     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5402                                      VK_RValue, RParenLoc);
5403 
5404   if (!getLangOpts().CPlusPlus) {
5405     // C cannot always handle TypoExpr nodes in builtin calls and direct
5406     // function calls as their argument checking don't necessarily handle
5407     // dependent types properly, so make sure any TypoExprs have been
5408     // dealt with.
5409     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5410     if (!Result.isUsable()) return ExprError();
5411     TheCall = dyn_cast<CallExpr>(Result.get());
5412     if (!TheCall) return Result;
5413     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5414   }
5415 
5416   // Bail out early if calling a builtin with custom typechecking.
5417   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5418     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5419 
5420  retry:
5421   const FunctionType *FuncT;
5422   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5423     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5424     // have type pointer to function".
5425     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5426     if (!FuncT)
5427       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5428                          << Fn->getType() << Fn->getSourceRange());
5429   } else if (const BlockPointerType *BPT =
5430                Fn->getType()->getAs<BlockPointerType>()) {
5431     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5432   } else {
5433     // Handle calls to expressions of unknown-any type.
5434     if (Fn->getType() == Context.UnknownAnyTy) {
5435       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5436       if (rewrite.isInvalid()) return ExprError();
5437       Fn = rewrite.get();
5438       TheCall->setCallee(Fn);
5439       goto retry;
5440     }
5441 
5442     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5443       << Fn->getType() << Fn->getSourceRange());
5444   }
5445 
5446   if (getLangOpts().CUDA) {
5447     if (Config) {
5448       // CUDA: Kernel calls must be to global functions
5449       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5450         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5451             << FDecl->getName() << Fn->getSourceRange());
5452 
5453       // CUDA: Kernel function must have 'void' return type
5454       if (!FuncT->getReturnType()->isVoidType())
5455         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5456             << Fn->getType() << Fn->getSourceRange());
5457     } else {
5458       // CUDA: Calls to global functions must be configured
5459       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5460         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5461             << FDecl->getName() << Fn->getSourceRange());
5462     }
5463   }
5464 
5465   // Check for a valid return type
5466   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5467                           FDecl))
5468     return ExprError();
5469 
5470   // We know the result type of the call, set it.
5471   TheCall->setType(FuncT->getCallResultType(Context));
5472   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5473 
5474   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5475   if (Proto) {
5476     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5477                                 IsExecConfig))
5478       return ExprError();
5479   } else {
5480     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5481 
5482     if (FDecl) {
5483       // Check if we have too few/too many template arguments, based
5484       // on our knowledge of the function definition.
5485       const FunctionDecl *Def = nullptr;
5486       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5487         Proto = Def->getType()->getAs<FunctionProtoType>();
5488        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5489           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5490           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5491       }
5492 
5493       // If the function we're calling isn't a function prototype, but we have
5494       // a function prototype from a prior declaratiom, use that prototype.
5495       if (!FDecl->hasPrototype())
5496         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5497     }
5498 
5499     // Promote the arguments (C99 6.5.2.2p6).
5500     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5501       Expr *Arg = Args[i];
5502 
5503       if (Proto && i < Proto->getNumParams()) {
5504         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5505             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5506         ExprResult ArgE =
5507             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5508         if (ArgE.isInvalid())
5509           return true;
5510 
5511         Arg = ArgE.getAs<Expr>();
5512 
5513       } else {
5514         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5515 
5516         if (ArgE.isInvalid())
5517           return true;
5518 
5519         Arg = ArgE.getAs<Expr>();
5520       }
5521 
5522       if (RequireCompleteType(Arg->getLocStart(),
5523                               Arg->getType(),
5524                               diag::err_call_incomplete_argument, Arg))
5525         return ExprError();
5526 
5527       TheCall->setArg(i, Arg);
5528     }
5529   }
5530 
5531   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5532     if (!Method->isStatic())
5533       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5534         << Fn->getSourceRange());
5535 
5536   // Check for sentinels
5537   if (NDecl)
5538     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5539 
5540   // Do special checking on direct calls to functions.
5541   if (FDecl) {
5542     if (CheckFunctionCall(FDecl, TheCall, Proto))
5543       return ExprError();
5544 
5545     if (BuiltinID)
5546       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5547   } else if (NDecl) {
5548     if (CheckPointerCall(NDecl, TheCall, Proto))
5549       return ExprError();
5550   } else {
5551     if (CheckOtherCall(TheCall, Proto))
5552       return ExprError();
5553   }
5554 
5555   return MaybeBindToTemporary(TheCall);
5556 }
5557 
5558 ExprResult
5559 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5560                            SourceLocation RParenLoc, Expr *InitExpr) {
5561   assert(Ty && "ActOnCompoundLiteral(): missing type");
5562   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5563 
5564   TypeSourceInfo *TInfo;
5565   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5566   if (!TInfo)
5567     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5568 
5569   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5570 }
5571 
5572 ExprResult
5573 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5574                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5575   QualType literalType = TInfo->getType();
5576 
5577   if (literalType->isArrayType()) {
5578     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5579           diag::err_illegal_decl_array_incomplete_type,
5580           SourceRange(LParenLoc,
5581                       LiteralExpr->getSourceRange().getEnd())))
5582       return ExprError();
5583     if (literalType->isVariableArrayType())
5584       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5585         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5586   } else if (!literalType->isDependentType() &&
5587              RequireCompleteType(LParenLoc, literalType,
5588                diag::err_typecheck_decl_incomplete_type,
5589                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5590     return ExprError();
5591 
5592   InitializedEntity Entity
5593     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5594   InitializationKind Kind
5595     = InitializationKind::CreateCStyleCast(LParenLoc,
5596                                            SourceRange(LParenLoc, RParenLoc),
5597                                            /*InitList=*/true);
5598   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5599   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5600                                       &literalType);
5601   if (Result.isInvalid())
5602     return ExprError();
5603   LiteralExpr = Result.get();
5604 
5605   bool isFileScope = !CurContext->isFunctionOrMethod();
5606   if (isFileScope &&
5607       !LiteralExpr->isTypeDependent() &&
5608       !LiteralExpr->isValueDependent() &&
5609       !literalType->isDependentType()) { // 6.5.2.5p3
5610     if (CheckForConstantInitializer(LiteralExpr, literalType))
5611       return ExprError();
5612   }
5613 
5614   // In C, compound literals are l-values for some reason.
5615   // For GCC compatibility, in C++, file-scope array compound literals with
5616   // constant initializers are also l-values, and compound literals are
5617   // otherwise prvalues.
5618   //
5619   // (GCC also treats C++ list-initialized file-scope array prvalues with
5620   // constant initializers as l-values, but that's non-conforming, so we don't
5621   // follow it there.)
5622   //
5623   // FIXME: It would be better to handle the lvalue cases as materializing and
5624   // lifetime-extending a temporary object, but our materialized temporaries
5625   // representation only supports lifetime extension from a variable, not "out
5626   // of thin air".
5627   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5628   // is bound to the result of applying array-to-pointer decay to the compound
5629   // literal.
5630   // FIXME: GCC supports compound literals of reference type, which should
5631   // obviously have a value kind derived from the kind of reference involved.
5632   ExprValueKind VK =
5633       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5634           ? VK_RValue
5635           : VK_LValue;
5636 
5637   return MaybeBindToTemporary(
5638       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5639                                         VK, LiteralExpr, isFileScope));
5640 }
5641 
5642 ExprResult
5643 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5644                     SourceLocation RBraceLoc) {
5645   // Immediately handle non-overload placeholders.  Overloads can be
5646   // resolved contextually, but everything else here can't.
5647   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5648     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5649       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5650 
5651       // Ignore failures; dropping the entire initializer list because
5652       // of one failure would be terrible for indexing/etc.
5653       if (result.isInvalid()) continue;
5654 
5655       InitArgList[I] = result.get();
5656     }
5657   }
5658 
5659   // Semantic analysis for initializers is done by ActOnDeclarator() and
5660   // CheckInitializer() - it requires knowledge of the object being intialized.
5661 
5662   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5663                                                RBraceLoc);
5664   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5665   return E;
5666 }
5667 
5668 /// Do an explicit extend of the given block pointer if we're in ARC.
5669 void Sema::maybeExtendBlockObject(ExprResult &E) {
5670   assert(E.get()->getType()->isBlockPointerType());
5671   assert(E.get()->isRValue());
5672 
5673   // Only do this in an r-value context.
5674   if (!getLangOpts().ObjCAutoRefCount) return;
5675 
5676   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5677                                CK_ARCExtendBlockObject, E.get(),
5678                                /*base path*/ nullptr, VK_RValue);
5679   Cleanup.setExprNeedsCleanups(true);
5680 }
5681 
5682 /// Prepare a conversion of the given expression to an ObjC object
5683 /// pointer type.
5684 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5685   QualType type = E.get()->getType();
5686   if (type->isObjCObjectPointerType()) {
5687     return CK_BitCast;
5688   } else if (type->isBlockPointerType()) {
5689     maybeExtendBlockObject(E);
5690     return CK_BlockPointerToObjCPointerCast;
5691   } else {
5692     assert(type->isPointerType());
5693     return CK_CPointerToObjCPointerCast;
5694   }
5695 }
5696 
5697 /// Prepares for a scalar cast, performing all the necessary stages
5698 /// except the final cast and returning the kind required.
5699 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5700   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5701   // Also, callers should have filtered out the invalid cases with
5702   // pointers.  Everything else should be possible.
5703 
5704   QualType SrcTy = Src.get()->getType();
5705   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5706     return CK_NoOp;
5707 
5708   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5709   case Type::STK_MemberPointer:
5710     llvm_unreachable("member pointer type in C");
5711 
5712   case Type::STK_CPointer:
5713   case Type::STK_BlockPointer:
5714   case Type::STK_ObjCObjectPointer:
5715     switch (DestTy->getScalarTypeKind()) {
5716     case Type::STK_CPointer: {
5717       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5718       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5719       if (SrcAS != DestAS)
5720         return CK_AddressSpaceConversion;
5721       return CK_BitCast;
5722     }
5723     case Type::STK_BlockPointer:
5724       return (SrcKind == Type::STK_BlockPointer
5725                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5726     case Type::STK_ObjCObjectPointer:
5727       if (SrcKind == Type::STK_ObjCObjectPointer)
5728         return CK_BitCast;
5729       if (SrcKind == Type::STK_CPointer)
5730         return CK_CPointerToObjCPointerCast;
5731       maybeExtendBlockObject(Src);
5732       return CK_BlockPointerToObjCPointerCast;
5733     case Type::STK_Bool:
5734       return CK_PointerToBoolean;
5735     case Type::STK_Integral:
5736       return CK_PointerToIntegral;
5737     case Type::STK_Floating:
5738     case Type::STK_FloatingComplex:
5739     case Type::STK_IntegralComplex:
5740     case Type::STK_MemberPointer:
5741       llvm_unreachable("illegal cast from pointer");
5742     }
5743     llvm_unreachable("Should have returned before this");
5744 
5745   case Type::STK_Bool: // casting from bool is like casting from an integer
5746   case Type::STK_Integral:
5747     switch (DestTy->getScalarTypeKind()) {
5748     case Type::STK_CPointer:
5749     case Type::STK_ObjCObjectPointer:
5750     case Type::STK_BlockPointer:
5751       if (Src.get()->isNullPointerConstant(Context,
5752                                            Expr::NPC_ValueDependentIsNull))
5753         return CK_NullToPointer;
5754       return CK_IntegralToPointer;
5755     case Type::STK_Bool:
5756       return CK_IntegralToBoolean;
5757     case Type::STK_Integral:
5758       return CK_IntegralCast;
5759     case Type::STK_Floating:
5760       return CK_IntegralToFloating;
5761     case Type::STK_IntegralComplex:
5762       Src = ImpCastExprToType(Src.get(),
5763                       DestTy->castAs<ComplexType>()->getElementType(),
5764                       CK_IntegralCast);
5765       return CK_IntegralRealToComplex;
5766     case Type::STK_FloatingComplex:
5767       Src = ImpCastExprToType(Src.get(),
5768                       DestTy->castAs<ComplexType>()->getElementType(),
5769                       CK_IntegralToFloating);
5770       return CK_FloatingRealToComplex;
5771     case Type::STK_MemberPointer:
5772       llvm_unreachable("member pointer type in C");
5773     }
5774     llvm_unreachable("Should have returned before this");
5775 
5776   case Type::STK_Floating:
5777     switch (DestTy->getScalarTypeKind()) {
5778     case Type::STK_Floating:
5779       return CK_FloatingCast;
5780     case Type::STK_Bool:
5781       return CK_FloatingToBoolean;
5782     case Type::STK_Integral:
5783       return CK_FloatingToIntegral;
5784     case Type::STK_FloatingComplex:
5785       Src = ImpCastExprToType(Src.get(),
5786                               DestTy->castAs<ComplexType>()->getElementType(),
5787                               CK_FloatingCast);
5788       return CK_FloatingRealToComplex;
5789     case Type::STK_IntegralComplex:
5790       Src = ImpCastExprToType(Src.get(),
5791                               DestTy->castAs<ComplexType>()->getElementType(),
5792                               CK_FloatingToIntegral);
5793       return CK_IntegralRealToComplex;
5794     case Type::STK_CPointer:
5795     case Type::STK_ObjCObjectPointer:
5796     case Type::STK_BlockPointer:
5797       llvm_unreachable("valid float->pointer cast?");
5798     case Type::STK_MemberPointer:
5799       llvm_unreachable("member pointer type in C");
5800     }
5801     llvm_unreachable("Should have returned before this");
5802 
5803   case Type::STK_FloatingComplex:
5804     switch (DestTy->getScalarTypeKind()) {
5805     case Type::STK_FloatingComplex:
5806       return CK_FloatingComplexCast;
5807     case Type::STK_IntegralComplex:
5808       return CK_FloatingComplexToIntegralComplex;
5809     case Type::STK_Floating: {
5810       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5811       if (Context.hasSameType(ET, DestTy))
5812         return CK_FloatingComplexToReal;
5813       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5814       return CK_FloatingCast;
5815     }
5816     case Type::STK_Bool:
5817       return CK_FloatingComplexToBoolean;
5818     case Type::STK_Integral:
5819       Src = ImpCastExprToType(Src.get(),
5820                               SrcTy->castAs<ComplexType>()->getElementType(),
5821                               CK_FloatingComplexToReal);
5822       return CK_FloatingToIntegral;
5823     case Type::STK_CPointer:
5824     case Type::STK_ObjCObjectPointer:
5825     case Type::STK_BlockPointer:
5826       llvm_unreachable("valid complex float->pointer cast?");
5827     case Type::STK_MemberPointer:
5828       llvm_unreachable("member pointer type in C");
5829     }
5830     llvm_unreachable("Should have returned before this");
5831 
5832   case Type::STK_IntegralComplex:
5833     switch (DestTy->getScalarTypeKind()) {
5834     case Type::STK_FloatingComplex:
5835       return CK_IntegralComplexToFloatingComplex;
5836     case Type::STK_IntegralComplex:
5837       return CK_IntegralComplexCast;
5838     case Type::STK_Integral: {
5839       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5840       if (Context.hasSameType(ET, DestTy))
5841         return CK_IntegralComplexToReal;
5842       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5843       return CK_IntegralCast;
5844     }
5845     case Type::STK_Bool:
5846       return CK_IntegralComplexToBoolean;
5847     case Type::STK_Floating:
5848       Src = ImpCastExprToType(Src.get(),
5849                               SrcTy->castAs<ComplexType>()->getElementType(),
5850                               CK_IntegralComplexToReal);
5851       return CK_IntegralToFloating;
5852     case Type::STK_CPointer:
5853     case Type::STK_ObjCObjectPointer:
5854     case Type::STK_BlockPointer:
5855       llvm_unreachable("valid complex int->pointer cast?");
5856     case Type::STK_MemberPointer:
5857       llvm_unreachable("member pointer type in C");
5858     }
5859     llvm_unreachable("Should have returned before this");
5860   }
5861 
5862   llvm_unreachable("Unhandled scalar cast");
5863 }
5864 
5865 static bool breakDownVectorType(QualType type, uint64_t &len,
5866                                 QualType &eltType) {
5867   // Vectors are simple.
5868   if (const VectorType *vecType = type->getAs<VectorType>()) {
5869     len = vecType->getNumElements();
5870     eltType = vecType->getElementType();
5871     assert(eltType->isScalarType());
5872     return true;
5873   }
5874 
5875   // We allow lax conversion to and from non-vector types, but only if
5876   // they're real types (i.e. non-complex, non-pointer scalar types).
5877   if (!type->isRealType()) return false;
5878 
5879   len = 1;
5880   eltType = type;
5881   return true;
5882 }
5883 
5884 /// Are the two types lax-compatible vector types?  That is, given
5885 /// that one of them is a vector, do they have equal storage sizes,
5886 /// where the storage size is the number of elements times the element
5887 /// size?
5888 ///
5889 /// This will also return false if either of the types is neither a
5890 /// vector nor a real type.
5891 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5892   assert(destTy->isVectorType() || srcTy->isVectorType());
5893 
5894   // Disallow lax conversions between scalars and ExtVectors (these
5895   // conversions are allowed for other vector types because common headers
5896   // depend on them).  Most scalar OP ExtVector cases are handled by the
5897   // splat path anyway, which does what we want (convert, not bitcast).
5898   // What this rules out for ExtVectors is crazy things like char4*float.
5899   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5900   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5901 
5902   uint64_t srcLen, destLen;
5903   QualType srcEltTy, destEltTy;
5904   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5905   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5906 
5907   // ASTContext::getTypeSize will return the size rounded up to a
5908   // power of 2, so instead of using that, we need to use the raw
5909   // element size multiplied by the element count.
5910   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5911   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5912 
5913   return (srcLen * srcEltSize == destLen * destEltSize);
5914 }
5915 
5916 /// Is this a legal conversion between two types, one of which is
5917 /// known to be a vector type?
5918 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5919   assert(destTy->isVectorType() || srcTy->isVectorType());
5920 
5921   if (!Context.getLangOpts().LaxVectorConversions)
5922     return false;
5923   return areLaxCompatibleVectorTypes(srcTy, destTy);
5924 }
5925 
5926 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5927                            CastKind &Kind) {
5928   assert(VectorTy->isVectorType() && "Not a vector type!");
5929 
5930   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5931     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5932       return Diag(R.getBegin(),
5933                   Ty->isVectorType() ?
5934                   diag::err_invalid_conversion_between_vectors :
5935                   diag::err_invalid_conversion_between_vector_and_integer)
5936         << VectorTy << Ty << R;
5937   } else
5938     return Diag(R.getBegin(),
5939                 diag::err_invalid_conversion_between_vector_and_scalar)
5940       << VectorTy << Ty << R;
5941 
5942   Kind = CK_BitCast;
5943   return false;
5944 }
5945 
5946 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5947   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5948 
5949   if (DestElemTy == SplattedExpr->getType())
5950     return SplattedExpr;
5951 
5952   assert(DestElemTy->isFloatingType() ||
5953          DestElemTy->isIntegralOrEnumerationType());
5954 
5955   CastKind CK;
5956   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5957     // OpenCL requires that we convert `true` boolean expressions to -1, but
5958     // only when splatting vectors.
5959     if (DestElemTy->isFloatingType()) {
5960       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5961       // in two steps: boolean to signed integral, then to floating.
5962       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5963                                                  CK_BooleanToSignedIntegral);
5964       SplattedExpr = CastExprRes.get();
5965       CK = CK_IntegralToFloating;
5966     } else {
5967       CK = CK_BooleanToSignedIntegral;
5968     }
5969   } else {
5970     ExprResult CastExprRes = SplattedExpr;
5971     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5972     if (CastExprRes.isInvalid())
5973       return ExprError();
5974     SplattedExpr = CastExprRes.get();
5975   }
5976   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5977 }
5978 
5979 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5980                                     Expr *CastExpr, CastKind &Kind) {
5981   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5982 
5983   QualType SrcTy = CastExpr->getType();
5984 
5985   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5986   // an ExtVectorType.
5987   // In OpenCL, casts between vectors of different types are not allowed.
5988   // (See OpenCL 6.2).
5989   if (SrcTy->isVectorType()) {
5990     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5991         || (getLangOpts().OpenCL &&
5992             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5993       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5994         << DestTy << SrcTy << R;
5995       return ExprError();
5996     }
5997     Kind = CK_BitCast;
5998     return CastExpr;
5999   }
6000 
6001   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6002   // conversion will take place first from scalar to elt type, and then
6003   // splat from elt type to vector.
6004   if (SrcTy->isPointerType())
6005     return Diag(R.getBegin(),
6006                 diag::err_invalid_conversion_between_vector_and_scalar)
6007       << DestTy << SrcTy << R;
6008 
6009   Kind = CK_VectorSplat;
6010   return prepareVectorSplat(DestTy, CastExpr);
6011 }
6012 
6013 ExprResult
6014 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6015                     Declarator &D, ParsedType &Ty,
6016                     SourceLocation RParenLoc, Expr *CastExpr) {
6017   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6018          "ActOnCastExpr(): missing type or expr");
6019 
6020   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6021   if (D.isInvalidType())
6022     return ExprError();
6023 
6024   if (getLangOpts().CPlusPlus) {
6025     // Check that there are no default arguments (C++ only).
6026     CheckExtraCXXDefaultArguments(D);
6027   } else {
6028     // Make sure any TypoExprs have been dealt with.
6029     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6030     if (!Res.isUsable())
6031       return ExprError();
6032     CastExpr = Res.get();
6033   }
6034 
6035   checkUnusedDeclAttributes(D);
6036 
6037   QualType castType = castTInfo->getType();
6038   Ty = CreateParsedType(castType, castTInfo);
6039 
6040   bool isVectorLiteral = false;
6041 
6042   // Check for an altivec or OpenCL literal,
6043   // i.e. all the elements are integer constants.
6044   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6045   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6046   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6047        && castType->isVectorType() && (PE || PLE)) {
6048     if (PLE && PLE->getNumExprs() == 0) {
6049       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6050       return ExprError();
6051     }
6052     if (PE || PLE->getNumExprs() == 1) {
6053       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6054       if (!E->getType()->isVectorType())
6055         isVectorLiteral = true;
6056     }
6057     else
6058       isVectorLiteral = true;
6059   }
6060 
6061   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6062   // then handle it as such.
6063   if (isVectorLiteral)
6064     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6065 
6066   // If the Expr being casted is a ParenListExpr, handle it specially.
6067   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6068   // sequence of BinOp comma operators.
6069   if (isa<ParenListExpr>(CastExpr)) {
6070     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6071     if (Result.isInvalid()) return ExprError();
6072     CastExpr = Result.get();
6073   }
6074 
6075   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6076       !getSourceManager().isInSystemMacro(LParenLoc))
6077     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6078 
6079   CheckTollFreeBridgeCast(castType, CastExpr);
6080 
6081   CheckObjCBridgeRelatedCast(castType, CastExpr);
6082 
6083   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6084 
6085   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6086 }
6087 
6088 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6089                                     SourceLocation RParenLoc, Expr *E,
6090                                     TypeSourceInfo *TInfo) {
6091   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6092          "Expected paren or paren list expression");
6093 
6094   Expr **exprs;
6095   unsigned numExprs;
6096   Expr *subExpr;
6097   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6098   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6099     LiteralLParenLoc = PE->getLParenLoc();
6100     LiteralRParenLoc = PE->getRParenLoc();
6101     exprs = PE->getExprs();
6102     numExprs = PE->getNumExprs();
6103   } else { // isa<ParenExpr> by assertion at function entrance
6104     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6105     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6106     subExpr = cast<ParenExpr>(E)->getSubExpr();
6107     exprs = &subExpr;
6108     numExprs = 1;
6109   }
6110 
6111   QualType Ty = TInfo->getType();
6112   assert(Ty->isVectorType() && "Expected vector type");
6113 
6114   SmallVector<Expr *, 8> initExprs;
6115   const VectorType *VTy = Ty->getAs<VectorType>();
6116   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6117 
6118   // '(...)' form of vector initialization in AltiVec: the number of
6119   // initializers must be one or must match the size of the vector.
6120   // If a single value is specified in the initializer then it will be
6121   // replicated to all the components of the vector
6122   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6123     // The number of initializers must be one or must match the size of the
6124     // vector. If a single value is specified in the initializer then it will
6125     // be replicated to all the components of the vector
6126     if (numExprs == 1) {
6127       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6128       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6129       if (Literal.isInvalid())
6130         return ExprError();
6131       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6132                                   PrepareScalarCast(Literal, ElemTy));
6133       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6134     }
6135     else if (numExprs < numElems) {
6136       Diag(E->getExprLoc(),
6137            diag::err_incorrect_number_of_vector_initializers);
6138       return ExprError();
6139     }
6140     else
6141       initExprs.append(exprs, exprs + numExprs);
6142   }
6143   else {
6144     // For OpenCL, when the number of initializers is a single value,
6145     // it will be replicated to all components of the vector.
6146     if (getLangOpts().OpenCL &&
6147         VTy->getVectorKind() == VectorType::GenericVector &&
6148         numExprs == 1) {
6149         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6150         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6151         if (Literal.isInvalid())
6152           return ExprError();
6153         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6154                                     PrepareScalarCast(Literal, ElemTy));
6155         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6156     }
6157 
6158     initExprs.append(exprs, exprs + numExprs);
6159   }
6160   // FIXME: This means that pretty-printing the final AST will produce curly
6161   // braces instead of the original commas.
6162   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6163                                                    initExprs, LiteralRParenLoc);
6164   initE->setType(Ty);
6165   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6166 }
6167 
6168 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6169 /// the ParenListExpr into a sequence of comma binary operators.
6170 ExprResult
6171 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6172   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6173   if (!E)
6174     return OrigExpr;
6175 
6176   ExprResult Result(E->getExpr(0));
6177 
6178   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6179     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6180                         E->getExpr(i));
6181 
6182   if (Result.isInvalid()) return ExprError();
6183 
6184   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6185 }
6186 
6187 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6188                                     SourceLocation R,
6189                                     MultiExprArg Val) {
6190   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6191   return expr;
6192 }
6193 
6194 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6195 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6196 /// emitted.
6197 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6198                                       SourceLocation QuestionLoc) {
6199   Expr *NullExpr = LHSExpr;
6200   Expr *NonPointerExpr = RHSExpr;
6201   Expr::NullPointerConstantKind NullKind =
6202       NullExpr->isNullPointerConstant(Context,
6203                                       Expr::NPC_ValueDependentIsNotNull);
6204 
6205   if (NullKind == Expr::NPCK_NotNull) {
6206     NullExpr = RHSExpr;
6207     NonPointerExpr = LHSExpr;
6208     NullKind =
6209         NullExpr->isNullPointerConstant(Context,
6210                                         Expr::NPC_ValueDependentIsNotNull);
6211   }
6212 
6213   if (NullKind == Expr::NPCK_NotNull)
6214     return false;
6215 
6216   if (NullKind == Expr::NPCK_ZeroExpression)
6217     return false;
6218 
6219   if (NullKind == Expr::NPCK_ZeroLiteral) {
6220     // In this case, check to make sure that we got here from a "NULL"
6221     // string in the source code.
6222     NullExpr = NullExpr->IgnoreParenImpCasts();
6223     SourceLocation loc = NullExpr->getExprLoc();
6224     if (!findMacroSpelling(loc, "NULL"))
6225       return false;
6226   }
6227 
6228   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6229   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6230       << NonPointerExpr->getType() << DiagType
6231       << NonPointerExpr->getSourceRange();
6232   return true;
6233 }
6234 
6235 /// \brief Return false if the condition expression is valid, true otherwise.
6236 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6237   QualType CondTy = Cond->getType();
6238 
6239   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6240   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6241     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6242       << CondTy << Cond->getSourceRange();
6243     return true;
6244   }
6245 
6246   // C99 6.5.15p2
6247   if (CondTy->isScalarType()) return false;
6248 
6249   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6250     << CondTy << Cond->getSourceRange();
6251   return true;
6252 }
6253 
6254 /// \brief Handle when one or both operands are void type.
6255 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6256                                          ExprResult &RHS) {
6257     Expr *LHSExpr = LHS.get();
6258     Expr *RHSExpr = RHS.get();
6259 
6260     if (!LHSExpr->getType()->isVoidType())
6261       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6262         << RHSExpr->getSourceRange();
6263     if (!RHSExpr->getType()->isVoidType())
6264       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6265         << LHSExpr->getSourceRange();
6266     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6267     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6268     return S.Context.VoidTy;
6269 }
6270 
6271 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6272 /// true otherwise.
6273 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6274                                         QualType PointerTy) {
6275   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6276       !NullExpr.get()->isNullPointerConstant(S.Context,
6277                                             Expr::NPC_ValueDependentIsNull))
6278     return true;
6279 
6280   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6281   return false;
6282 }
6283 
6284 /// \brief Checks compatibility between two pointers and return the resulting
6285 /// type.
6286 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6287                                                      ExprResult &RHS,
6288                                                      SourceLocation Loc) {
6289   QualType LHSTy = LHS.get()->getType();
6290   QualType RHSTy = RHS.get()->getType();
6291 
6292   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6293     // Two identical pointers types are always compatible.
6294     return LHSTy;
6295   }
6296 
6297   QualType lhptee, rhptee;
6298 
6299   // Get the pointee types.
6300   bool IsBlockPointer = false;
6301   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6302     lhptee = LHSBTy->getPointeeType();
6303     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6304     IsBlockPointer = true;
6305   } else {
6306     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6307     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6308   }
6309 
6310   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6311   // differently qualified versions of compatible types, the result type is
6312   // a pointer to an appropriately qualified version of the composite
6313   // type.
6314 
6315   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6316   // clause doesn't make sense for our extensions. E.g. address space 2 should
6317   // be incompatible with address space 3: they may live on different devices or
6318   // anything.
6319   Qualifiers lhQual = lhptee.getQualifiers();
6320   Qualifiers rhQual = rhptee.getQualifiers();
6321 
6322   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6323   lhQual.removeCVRQualifiers();
6324   rhQual.removeCVRQualifiers();
6325 
6326   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6327   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6328 
6329   // For OpenCL:
6330   // 1. If LHS and RHS types match exactly and:
6331   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6332   //  (b) AS overlap => generate addrspacecast
6333   //  (c) AS don't overlap => give an error
6334   // 2. if LHS and RHS types don't match:
6335   //  (a) AS match => use standard C rules, generate bitcast
6336   //  (b) AS overlap => generate addrspacecast instead of bitcast
6337   //  (c) AS don't overlap => give an error
6338 
6339   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6340   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6341 
6342   // OpenCL cases 1c, 2a, 2b, and 2c.
6343   if (CompositeTy.isNull()) {
6344     // In this situation, we assume void* type. No especially good
6345     // reason, but this is what gcc does, and we do have to pick
6346     // to get a consistent AST.
6347     QualType incompatTy;
6348     if (S.getLangOpts().OpenCL) {
6349       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6350       // spaces is disallowed.
6351       unsigned ResultAddrSpace;
6352       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6353         // Cases 2a and 2b.
6354         ResultAddrSpace = lhQual.getAddressSpace();
6355       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6356         // Cases 2a and 2b.
6357         ResultAddrSpace = rhQual.getAddressSpace();
6358       } else {
6359         // Cases 1c and 2c.
6360         S.Diag(Loc,
6361                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6362             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6363             << RHS.get()->getSourceRange();
6364         return QualType();
6365       }
6366 
6367       // Continue handling cases 2a and 2b.
6368       incompatTy = S.Context.getPointerType(
6369           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6370       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6371                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6372                                     ? CK_AddressSpaceConversion /* 2b */
6373                                     : CK_BitCast /* 2a */);
6374       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6375                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6376                                     ? CK_AddressSpaceConversion /* 2b */
6377                                     : CK_BitCast /* 2a */);
6378     } else {
6379       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6380           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6381           << RHS.get()->getSourceRange();
6382       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6383       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6384       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6385     }
6386     return incompatTy;
6387   }
6388 
6389   // The pointer types are compatible.
6390   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6391   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6392   if (IsBlockPointer)
6393     ResultTy = S.Context.getBlockPointerType(ResultTy);
6394   else {
6395     // Cases 1a and 1b for OpenCL.
6396     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6397     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6398                       ? CK_BitCast /* 1a */
6399                       : CK_AddressSpaceConversion /* 1b */;
6400     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6401                       ? CK_BitCast /* 1a */
6402                       : CK_AddressSpaceConversion /* 1b */;
6403     ResultTy = S.Context.getPointerType(ResultTy);
6404   }
6405 
6406   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6407   // if the target type does not change.
6408   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6409   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6410   return ResultTy;
6411 }
6412 
6413 /// \brief Return the resulting type when the operands are both block pointers.
6414 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6415                                                           ExprResult &LHS,
6416                                                           ExprResult &RHS,
6417                                                           SourceLocation Loc) {
6418   QualType LHSTy = LHS.get()->getType();
6419   QualType RHSTy = RHS.get()->getType();
6420 
6421   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6422     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6423       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6424       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6425       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6426       return destType;
6427     }
6428     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6429       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6430       << RHS.get()->getSourceRange();
6431     return QualType();
6432   }
6433 
6434   // We have 2 block pointer types.
6435   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6436 }
6437 
6438 /// \brief Return the resulting type when the operands are both pointers.
6439 static QualType
6440 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6441                                             ExprResult &RHS,
6442                                             SourceLocation Loc) {
6443   // get the pointer types
6444   QualType LHSTy = LHS.get()->getType();
6445   QualType RHSTy = RHS.get()->getType();
6446 
6447   // get the "pointed to" types
6448   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6449   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6450 
6451   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6452   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6453     // Figure out necessary qualifiers (C99 6.5.15p6)
6454     QualType destPointee
6455       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6456     QualType destType = S.Context.getPointerType(destPointee);
6457     // Add qualifiers if necessary.
6458     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6459     // Promote to void*.
6460     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6461     return destType;
6462   }
6463   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6464     QualType destPointee
6465       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6466     QualType destType = S.Context.getPointerType(destPointee);
6467     // Add qualifiers if necessary.
6468     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6469     // Promote to void*.
6470     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6471     return destType;
6472   }
6473 
6474   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6475 }
6476 
6477 /// \brief Return false if the first expression is not an integer and the second
6478 /// expression is not a pointer, true otherwise.
6479 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6480                                         Expr* PointerExpr, SourceLocation Loc,
6481                                         bool IsIntFirstExpr) {
6482   if (!PointerExpr->getType()->isPointerType() ||
6483       !Int.get()->getType()->isIntegerType())
6484     return false;
6485 
6486   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6487   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6488 
6489   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6490     << Expr1->getType() << Expr2->getType()
6491     << Expr1->getSourceRange() << Expr2->getSourceRange();
6492   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6493                             CK_IntegralToPointer);
6494   return true;
6495 }
6496 
6497 /// \brief Simple conversion between integer and floating point types.
6498 ///
6499 /// Used when handling the OpenCL conditional operator where the
6500 /// condition is a vector while the other operands are scalar.
6501 ///
6502 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6503 /// types are either integer or floating type. Between the two
6504 /// operands, the type with the higher rank is defined as the "result
6505 /// type". The other operand needs to be promoted to the same type. No
6506 /// other type promotion is allowed. We cannot use
6507 /// UsualArithmeticConversions() for this purpose, since it always
6508 /// promotes promotable types.
6509 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6510                                             ExprResult &RHS,
6511                                             SourceLocation QuestionLoc) {
6512   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6513   if (LHS.isInvalid())
6514     return QualType();
6515   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6516   if (RHS.isInvalid())
6517     return QualType();
6518 
6519   // For conversion purposes, we ignore any qualifiers.
6520   // For example, "const float" and "float" are equivalent.
6521   QualType LHSType =
6522     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6523   QualType RHSType =
6524     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6525 
6526   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6527     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6528       << LHSType << LHS.get()->getSourceRange();
6529     return QualType();
6530   }
6531 
6532   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6533     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6534       << RHSType << RHS.get()->getSourceRange();
6535     return QualType();
6536   }
6537 
6538   // If both types are identical, no conversion is needed.
6539   if (LHSType == RHSType)
6540     return LHSType;
6541 
6542   // Now handle "real" floating types (i.e. float, double, long double).
6543   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6544     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6545                                  /*IsCompAssign = */ false);
6546 
6547   // Finally, we have two differing integer types.
6548   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6549   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6550 }
6551 
6552 /// \brief Convert scalar operands to a vector that matches the
6553 ///        condition in length.
6554 ///
6555 /// Used when handling the OpenCL conditional operator where the
6556 /// condition is a vector while the other operands are scalar.
6557 ///
6558 /// We first compute the "result type" for the scalar operands
6559 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6560 /// into a vector of that type where the length matches the condition
6561 /// vector type. s6.11.6 requires that the element types of the result
6562 /// and the condition must have the same number of bits.
6563 static QualType
6564 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6565                               QualType CondTy, SourceLocation QuestionLoc) {
6566   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6567   if (ResTy.isNull()) return QualType();
6568 
6569   const VectorType *CV = CondTy->getAs<VectorType>();
6570   assert(CV);
6571 
6572   // Determine the vector result type
6573   unsigned NumElements = CV->getNumElements();
6574   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6575 
6576   // Ensure that all types have the same number of bits
6577   if (S.Context.getTypeSize(CV->getElementType())
6578       != S.Context.getTypeSize(ResTy)) {
6579     // Since VectorTy is created internally, it does not pretty print
6580     // with an OpenCL name. Instead, we just print a description.
6581     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6582     SmallString<64> Str;
6583     llvm::raw_svector_ostream OS(Str);
6584     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6585     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6586       << CondTy << OS.str();
6587     return QualType();
6588   }
6589 
6590   // Convert operands to the vector result type
6591   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6592   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6593 
6594   return VectorTy;
6595 }
6596 
6597 /// \brief Return false if this is a valid OpenCL condition vector
6598 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6599                                        SourceLocation QuestionLoc) {
6600   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6601   // integral type.
6602   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6603   assert(CondTy);
6604   QualType EleTy = CondTy->getElementType();
6605   if (EleTy->isIntegerType()) return false;
6606 
6607   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6608     << Cond->getType() << Cond->getSourceRange();
6609   return true;
6610 }
6611 
6612 /// \brief Return false if the vector condition type and the vector
6613 ///        result type are compatible.
6614 ///
6615 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6616 /// number of elements, and their element types have the same number
6617 /// of bits.
6618 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6619                               SourceLocation QuestionLoc) {
6620   const VectorType *CV = CondTy->getAs<VectorType>();
6621   const VectorType *RV = VecResTy->getAs<VectorType>();
6622   assert(CV && RV);
6623 
6624   if (CV->getNumElements() != RV->getNumElements()) {
6625     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6626       << CondTy << VecResTy;
6627     return true;
6628   }
6629 
6630   QualType CVE = CV->getElementType();
6631   QualType RVE = RV->getElementType();
6632 
6633   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6634     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6635       << CondTy << VecResTy;
6636     return true;
6637   }
6638 
6639   return false;
6640 }
6641 
6642 /// \brief Return the resulting type for the conditional operator in
6643 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6644 ///        s6.3.i) when the condition is a vector type.
6645 static QualType
6646 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6647                              ExprResult &LHS, ExprResult &RHS,
6648                              SourceLocation QuestionLoc) {
6649   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6650   if (Cond.isInvalid())
6651     return QualType();
6652   QualType CondTy = Cond.get()->getType();
6653 
6654   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6655     return QualType();
6656 
6657   // If either operand is a vector then find the vector type of the
6658   // result as specified in OpenCL v1.1 s6.3.i.
6659   if (LHS.get()->getType()->isVectorType() ||
6660       RHS.get()->getType()->isVectorType()) {
6661     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6662                                               /*isCompAssign*/false,
6663                                               /*AllowBothBool*/true,
6664                                               /*AllowBoolConversions*/false);
6665     if (VecResTy.isNull()) return QualType();
6666     // The result type must match the condition type as specified in
6667     // OpenCL v1.1 s6.11.6.
6668     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6669       return QualType();
6670     return VecResTy;
6671   }
6672 
6673   // Both operands are scalar.
6674   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6675 }
6676 
6677 /// \brief Return true if the Expr is block type
6678 static bool checkBlockType(Sema &S, const Expr *E) {
6679   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6680     QualType Ty = CE->getCallee()->getType();
6681     if (Ty->isBlockPointerType()) {
6682       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6683       return true;
6684     }
6685   }
6686   return false;
6687 }
6688 
6689 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6690 /// In that case, LHS = cond.
6691 /// C99 6.5.15
6692 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6693                                         ExprResult &RHS, ExprValueKind &VK,
6694                                         ExprObjectKind &OK,
6695                                         SourceLocation QuestionLoc) {
6696 
6697   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6698   if (!LHSResult.isUsable()) return QualType();
6699   LHS = LHSResult;
6700 
6701   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6702   if (!RHSResult.isUsable()) return QualType();
6703   RHS = RHSResult;
6704 
6705   // C++ is sufficiently different to merit its own checker.
6706   if (getLangOpts().CPlusPlus)
6707     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6708 
6709   VK = VK_RValue;
6710   OK = OK_Ordinary;
6711 
6712   // The OpenCL operator with a vector condition is sufficiently
6713   // different to merit its own checker.
6714   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6715     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6716 
6717   // First, check the condition.
6718   Cond = UsualUnaryConversions(Cond.get());
6719   if (Cond.isInvalid())
6720     return QualType();
6721   if (checkCondition(*this, Cond.get(), QuestionLoc))
6722     return QualType();
6723 
6724   // Now check the two expressions.
6725   if (LHS.get()->getType()->isVectorType() ||
6726       RHS.get()->getType()->isVectorType())
6727     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6728                                /*AllowBothBool*/true,
6729                                /*AllowBoolConversions*/false);
6730 
6731   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6732   if (LHS.isInvalid() || RHS.isInvalid())
6733     return QualType();
6734 
6735   QualType LHSTy = LHS.get()->getType();
6736   QualType RHSTy = RHS.get()->getType();
6737 
6738   // Diagnose attempts to convert between __float128 and long double where
6739   // such conversions currently can't be handled.
6740   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6741     Diag(QuestionLoc,
6742          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6743       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6744     return QualType();
6745   }
6746 
6747   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6748   // selection operator (?:).
6749   if (getLangOpts().OpenCL &&
6750       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6751     return QualType();
6752   }
6753 
6754   // If both operands have arithmetic type, do the usual arithmetic conversions
6755   // to find a common type: C99 6.5.15p3,5.
6756   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6757     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6758     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6759 
6760     return ResTy;
6761   }
6762 
6763   // If both operands are the same structure or union type, the result is that
6764   // type.
6765   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6766     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6767       if (LHSRT->getDecl() == RHSRT->getDecl())
6768         // "If both the operands have structure or union type, the result has
6769         // that type."  This implies that CV qualifiers are dropped.
6770         return LHSTy.getUnqualifiedType();
6771     // FIXME: Type of conditional expression must be complete in C mode.
6772   }
6773 
6774   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6775   // The following || allows only one side to be void (a GCC-ism).
6776   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6777     return checkConditionalVoidType(*this, LHS, RHS);
6778   }
6779 
6780   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6781   // the type of the other operand."
6782   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6783   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6784 
6785   // All objective-c pointer type analysis is done here.
6786   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6787                                                         QuestionLoc);
6788   if (LHS.isInvalid() || RHS.isInvalid())
6789     return QualType();
6790   if (!compositeType.isNull())
6791     return compositeType;
6792 
6793 
6794   // Handle block pointer types.
6795   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6796     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6797                                                      QuestionLoc);
6798 
6799   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6800   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6801     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6802                                                        QuestionLoc);
6803 
6804   // GCC compatibility: soften pointer/integer mismatch.  Note that
6805   // null pointers have been filtered out by this point.
6806   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6807       /*isIntFirstExpr=*/true))
6808     return RHSTy;
6809   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6810       /*isIntFirstExpr=*/false))
6811     return LHSTy;
6812 
6813   // Emit a better diagnostic if one of the expressions is a null pointer
6814   // constant and the other is not a pointer type. In this case, the user most
6815   // likely forgot to take the address of the other expression.
6816   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6817     return QualType();
6818 
6819   // Otherwise, the operands are not compatible.
6820   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6821     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6822     << RHS.get()->getSourceRange();
6823   return QualType();
6824 }
6825 
6826 /// FindCompositeObjCPointerType - Helper method to find composite type of
6827 /// two objective-c pointer types of the two input expressions.
6828 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6829                                             SourceLocation QuestionLoc) {
6830   QualType LHSTy = LHS.get()->getType();
6831   QualType RHSTy = RHS.get()->getType();
6832 
6833   // Handle things like Class and struct objc_class*.  Here we case the result
6834   // to the pseudo-builtin, because that will be implicitly cast back to the
6835   // redefinition type if an attempt is made to access its fields.
6836   if (LHSTy->isObjCClassType() &&
6837       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6838     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6839     return LHSTy;
6840   }
6841   if (RHSTy->isObjCClassType() &&
6842       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6843     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6844     return RHSTy;
6845   }
6846   // And the same for struct objc_object* / id
6847   if (LHSTy->isObjCIdType() &&
6848       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6849     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6850     return LHSTy;
6851   }
6852   if (RHSTy->isObjCIdType() &&
6853       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6854     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6855     return RHSTy;
6856   }
6857   // And the same for struct objc_selector* / SEL
6858   if (Context.isObjCSelType(LHSTy) &&
6859       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6860     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6861     return LHSTy;
6862   }
6863   if (Context.isObjCSelType(RHSTy) &&
6864       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6865     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6866     return RHSTy;
6867   }
6868   // Check constraints for Objective-C object pointers types.
6869   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6870 
6871     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6872       // Two identical object pointer types are always compatible.
6873       return LHSTy;
6874     }
6875     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6876     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6877     QualType compositeType = LHSTy;
6878 
6879     // If both operands are interfaces and either operand can be
6880     // assigned to the other, use that type as the composite
6881     // type. This allows
6882     //   xxx ? (A*) a : (B*) b
6883     // where B is a subclass of A.
6884     //
6885     // Additionally, as for assignment, if either type is 'id'
6886     // allow silent coercion. Finally, if the types are
6887     // incompatible then make sure to use 'id' as the composite
6888     // type so the result is acceptable for sending messages to.
6889 
6890     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6891     // It could return the composite type.
6892     if (!(compositeType =
6893           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6894       // Nothing more to do.
6895     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6896       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6897     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6898       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6899     } else if ((LHSTy->isObjCQualifiedIdType() ||
6900                 RHSTy->isObjCQualifiedIdType()) &&
6901                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6902       // Need to handle "id<xx>" explicitly.
6903       // GCC allows qualified id and any Objective-C type to devolve to
6904       // id. Currently localizing to here until clear this should be
6905       // part of ObjCQualifiedIdTypesAreCompatible.
6906       compositeType = Context.getObjCIdType();
6907     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6908       compositeType = Context.getObjCIdType();
6909     } else {
6910       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6911       << LHSTy << RHSTy
6912       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6913       QualType incompatTy = Context.getObjCIdType();
6914       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6915       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6916       return incompatTy;
6917     }
6918     // The object pointer types are compatible.
6919     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6920     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6921     return compositeType;
6922   }
6923   // Check Objective-C object pointer types and 'void *'
6924   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6925     if (getLangOpts().ObjCAutoRefCount) {
6926       // ARC forbids the implicit conversion of object pointers to 'void *',
6927       // so these types are not compatible.
6928       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6929           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6930       LHS = RHS = true;
6931       return QualType();
6932     }
6933     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6934     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6935     QualType destPointee
6936     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6937     QualType destType = Context.getPointerType(destPointee);
6938     // Add qualifiers if necessary.
6939     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6940     // Promote to void*.
6941     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6942     return destType;
6943   }
6944   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6945     if (getLangOpts().ObjCAutoRefCount) {
6946       // ARC forbids the implicit conversion of object pointers to 'void *',
6947       // so these types are not compatible.
6948       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6949           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6950       LHS = RHS = true;
6951       return QualType();
6952     }
6953     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6954     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6955     QualType destPointee
6956     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6957     QualType destType = Context.getPointerType(destPointee);
6958     // Add qualifiers if necessary.
6959     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6960     // Promote to void*.
6961     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6962     return destType;
6963   }
6964   return QualType();
6965 }
6966 
6967 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6968 /// ParenRange in parentheses.
6969 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6970                                const PartialDiagnostic &Note,
6971                                SourceRange ParenRange) {
6972   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6973   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6974       EndLoc.isValid()) {
6975     Self.Diag(Loc, Note)
6976       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6977       << FixItHint::CreateInsertion(EndLoc, ")");
6978   } else {
6979     // We can't display the parentheses, so just show the bare note.
6980     Self.Diag(Loc, Note) << ParenRange;
6981   }
6982 }
6983 
6984 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6985   return BinaryOperator::isAdditiveOp(Opc) ||
6986          BinaryOperator::isMultiplicativeOp(Opc) ||
6987          BinaryOperator::isShiftOp(Opc);
6988 }
6989 
6990 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6991 /// expression, either using a built-in or overloaded operator,
6992 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6993 /// expression.
6994 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6995                                    Expr **RHSExprs) {
6996   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6997   E = E->IgnoreImpCasts();
6998   E = E->IgnoreConversionOperator();
6999   E = E->IgnoreImpCasts();
7000 
7001   // Built-in binary operator.
7002   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7003     if (IsArithmeticOp(OP->getOpcode())) {
7004       *Opcode = OP->getOpcode();
7005       *RHSExprs = OP->getRHS();
7006       return true;
7007     }
7008   }
7009 
7010   // Overloaded operator.
7011   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7012     if (Call->getNumArgs() != 2)
7013       return false;
7014 
7015     // Make sure this is really a binary operator that is safe to pass into
7016     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7017     OverloadedOperatorKind OO = Call->getOperator();
7018     if (OO < OO_Plus || OO > OO_Arrow ||
7019         OO == OO_PlusPlus || OO == OO_MinusMinus)
7020       return false;
7021 
7022     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7023     if (IsArithmeticOp(OpKind)) {
7024       *Opcode = OpKind;
7025       *RHSExprs = Call->getArg(1);
7026       return true;
7027     }
7028   }
7029 
7030   return false;
7031 }
7032 
7033 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7034 /// or is a logical expression such as (x==y) which has int type, but is
7035 /// commonly interpreted as boolean.
7036 static bool ExprLooksBoolean(Expr *E) {
7037   E = E->IgnoreParenImpCasts();
7038 
7039   if (E->getType()->isBooleanType())
7040     return true;
7041   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7042     return OP->isComparisonOp() || OP->isLogicalOp();
7043   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7044     return OP->getOpcode() == UO_LNot;
7045   if (E->getType()->isPointerType())
7046     return true;
7047 
7048   return false;
7049 }
7050 
7051 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7052 /// and binary operator are mixed in a way that suggests the programmer assumed
7053 /// the conditional operator has higher precedence, for example:
7054 /// "int x = a + someBinaryCondition ? 1 : 2".
7055 static void DiagnoseConditionalPrecedence(Sema &Self,
7056                                           SourceLocation OpLoc,
7057                                           Expr *Condition,
7058                                           Expr *LHSExpr,
7059                                           Expr *RHSExpr) {
7060   BinaryOperatorKind CondOpcode;
7061   Expr *CondRHS;
7062 
7063   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7064     return;
7065   if (!ExprLooksBoolean(CondRHS))
7066     return;
7067 
7068   // The condition is an arithmetic binary expression, with a right-
7069   // hand side that looks boolean, so warn.
7070 
7071   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7072       << Condition->getSourceRange()
7073       << BinaryOperator::getOpcodeStr(CondOpcode);
7074 
7075   SuggestParentheses(Self, OpLoc,
7076     Self.PDiag(diag::note_precedence_silence)
7077       << BinaryOperator::getOpcodeStr(CondOpcode),
7078     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7079 
7080   SuggestParentheses(Self, OpLoc,
7081     Self.PDiag(diag::note_precedence_conditional_first),
7082     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7083 }
7084 
7085 /// Compute the nullability of a conditional expression.
7086 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7087                                               QualType LHSTy, QualType RHSTy,
7088                                               ASTContext &Ctx) {
7089   if (!ResTy->isAnyPointerType())
7090     return ResTy;
7091 
7092   auto GetNullability = [&Ctx](QualType Ty) {
7093     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7094     if (Kind)
7095       return *Kind;
7096     return NullabilityKind::Unspecified;
7097   };
7098 
7099   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7100   NullabilityKind MergedKind;
7101 
7102   // Compute nullability of a binary conditional expression.
7103   if (IsBin) {
7104     if (LHSKind == NullabilityKind::NonNull)
7105       MergedKind = NullabilityKind::NonNull;
7106     else
7107       MergedKind = RHSKind;
7108   // Compute nullability of a normal conditional expression.
7109   } else {
7110     if (LHSKind == NullabilityKind::Nullable ||
7111         RHSKind == NullabilityKind::Nullable)
7112       MergedKind = NullabilityKind::Nullable;
7113     else if (LHSKind == NullabilityKind::NonNull)
7114       MergedKind = RHSKind;
7115     else if (RHSKind == NullabilityKind::NonNull)
7116       MergedKind = LHSKind;
7117     else
7118       MergedKind = NullabilityKind::Unspecified;
7119   }
7120 
7121   // Return if ResTy already has the correct nullability.
7122   if (GetNullability(ResTy) == MergedKind)
7123     return ResTy;
7124 
7125   // Strip all nullability from ResTy.
7126   while (ResTy->getNullability(Ctx))
7127     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7128 
7129   // Create a new AttributedType with the new nullability kind.
7130   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7131   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7132 }
7133 
7134 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7135 /// in the case of a the GNU conditional expr extension.
7136 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7137                                     SourceLocation ColonLoc,
7138                                     Expr *CondExpr, Expr *LHSExpr,
7139                                     Expr *RHSExpr) {
7140   if (!getLangOpts().CPlusPlus) {
7141     // C cannot handle TypoExpr nodes in the condition because it
7142     // doesn't handle dependent types properly, so make sure any TypoExprs have
7143     // been dealt with before checking the operands.
7144     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7145     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7146     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7147 
7148     if (!CondResult.isUsable())
7149       return ExprError();
7150 
7151     if (LHSExpr) {
7152       if (!LHSResult.isUsable())
7153         return ExprError();
7154     }
7155 
7156     if (!RHSResult.isUsable())
7157       return ExprError();
7158 
7159     CondExpr = CondResult.get();
7160     LHSExpr = LHSResult.get();
7161     RHSExpr = RHSResult.get();
7162   }
7163 
7164   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7165   // was the condition.
7166   OpaqueValueExpr *opaqueValue = nullptr;
7167   Expr *commonExpr = nullptr;
7168   if (!LHSExpr) {
7169     commonExpr = CondExpr;
7170     // Lower out placeholder types first.  This is important so that we don't
7171     // try to capture a placeholder. This happens in few cases in C++; such
7172     // as Objective-C++'s dictionary subscripting syntax.
7173     if (commonExpr->hasPlaceholderType()) {
7174       ExprResult result = CheckPlaceholderExpr(commonExpr);
7175       if (!result.isUsable()) return ExprError();
7176       commonExpr = result.get();
7177     }
7178     // We usually want to apply unary conversions *before* saving, except
7179     // in the special case of a C++ l-value conditional.
7180     if (!(getLangOpts().CPlusPlus
7181           && !commonExpr->isTypeDependent()
7182           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7183           && commonExpr->isGLValue()
7184           && commonExpr->isOrdinaryOrBitFieldObject()
7185           && RHSExpr->isOrdinaryOrBitFieldObject()
7186           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7187       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7188       if (commonRes.isInvalid())
7189         return ExprError();
7190       commonExpr = commonRes.get();
7191     }
7192 
7193     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7194                                                 commonExpr->getType(),
7195                                                 commonExpr->getValueKind(),
7196                                                 commonExpr->getObjectKind(),
7197                                                 commonExpr);
7198     LHSExpr = CondExpr = opaqueValue;
7199   }
7200 
7201   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7202   ExprValueKind VK = VK_RValue;
7203   ExprObjectKind OK = OK_Ordinary;
7204   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7205   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7206                                              VK, OK, QuestionLoc);
7207   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7208       RHS.isInvalid())
7209     return ExprError();
7210 
7211   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7212                                 RHS.get());
7213 
7214   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7215 
7216   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7217                                          Context);
7218 
7219   if (!commonExpr)
7220     return new (Context)
7221         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7222                             RHS.get(), result, VK, OK);
7223 
7224   return new (Context) BinaryConditionalOperator(
7225       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7226       ColonLoc, result, VK, OK);
7227 }
7228 
7229 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7230 // being closely modeled after the C99 spec:-). The odd characteristic of this
7231 // routine is it effectively iqnores the qualifiers on the top level pointee.
7232 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7233 // FIXME: add a couple examples in this comment.
7234 static Sema::AssignConvertType
7235 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7236   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7237   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7238 
7239   // get the "pointed to" type (ignoring qualifiers at the top level)
7240   const Type *lhptee, *rhptee;
7241   Qualifiers lhq, rhq;
7242   std::tie(lhptee, lhq) =
7243       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7244   std::tie(rhptee, rhq) =
7245       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7246 
7247   Sema::AssignConvertType ConvTy = Sema::Compatible;
7248 
7249   // C99 6.5.16.1p1: This following citation is common to constraints
7250   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7251   // qualifiers of the type *pointed to* by the right;
7252 
7253   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7254   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7255       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7256     // Ignore lifetime for further calculation.
7257     lhq.removeObjCLifetime();
7258     rhq.removeObjCLifetime();
7259   }
7260 
7261   if (!lhq.compatiblyIncludes(rhq)) {
7262     // Treat address-space mismatches as fatal.  TODO: address subspaces
7263     if (!lhq.isAddressSpaceSupersetOf(rhq))
7264       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7265 
7266     // It's okay to add or remove GC or lifetime qualifiers when converting to
7267     // and from void*.
7268     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7269                         .compatiblyIncludes(
7270                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7271              && (lhptee->isVoidType() || rhptee->isVoidType()))
7272       ; // keep old
7273 
7274     // Treat lifetime mismatches as fatal.
7275     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7276       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7277 
7278     // For GCC/MS compatibility, other qualifier mismatches are treated
7279     // as still compatible in C.
7280     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7281   }
7282 
7283   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7284   // incomplete type and the other is a pointer to a qualified or unqualified
7285   // version of void...
7286   if (lhptee->isVoidType()) {
7287     if (rhptee->isIncompleteOrObjectType())
7288       return ConvTy;
7289 
7290     // As an extension, we allow cast to/from void* to function pointer.
7291     assert(rhptee->isFunctionType());
7292     return Sema::FunctionVoidPointer;
7293   }
7294 
7295   if (rhptee->isVoidType()) {
7296     if (lhptee->isIncompleteOrObjectType())
7297       return ConvTy;
7298 
7299     // As an extension, we allow cast to/from void* to function pointer.
7300     assert(lhptee->isFunctionType());
7301     return Sema::FunctionVoidPointer;
7302   }
7303 
7304   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7305   // unqualified versions of compatible types, ...
7306   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7307   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7308     // Check if the pointee types are compatible ignoring the sign.
7309     // We explicitly check for char so that we catch "char" vs
7310     // "unsigned char" on systems where "char" is unsigned.
7311     if (lhptee->isCharType())
7312       ltrans = S.Context.UnsignedCharTy;
7313     else if (lhptee->hasSignedIntegerRepresentation())
7314       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7315 
7316     if (rhptee->isCharType())
7317       rtrans = S.Context.UnsignedCharTy;
7318     else if (rhptee->hasSignedIntegerRepresentation())
7319       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7320 
7321     if (ltrans == rtrans) {
7322       // Types are compatible ignoring the sign. Qualifier incompatibility
7323       // takes priority over sign incompatibility because the sign
7324       // warning can be disabled.
7325       if (ConvTy != Sema::Compatible)
7326         return ConvTy;
7327 
7328       return Sema::IncompatiblePointerSign;
7329     }
7330 
7331     // If we are a multi-level pointer, it's possible that our issue is simply
7332     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7333     // the eventual target type is the same and the pointers have the same
7334     // level of indirection, this must be the issue.
7335     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7336       do {
7337         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7338         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7339       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7340 
7341       if (lhptee == rhptee)
7342         return Sema::IncompatibleNestedPointerQualifiers;
7343     }
7344 
7345     // General pointer incompatibility takes priority over qualifiers.
7346     return Sema::IncompatiblePointer;
7347   }
7348   if (!S.getLangOpts().CPlusPlus &&
7349       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7350     return Sema::IncompatiblePointer;
7351   return ConvTy;
7352 }
7353 
7354 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7355 /// block pointer types are compatible or whether a block and normal pointer
7356 /// are compatible. It is more restrict than comparing two function pointer
7357 // types.
7358 static Sema::AssignConvertType
7359 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7360                                     QualType RHSType) {
7361   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7362   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7363 
7364   QualType lhptee, rhptee;
7365 
7366   // get the "pointed to" type (ignoring qualifiers at the top level)
7367   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7368   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7369 
7370   // In C++, the types have to match exactly.
7371   if (S.getLangOpts().CPlusPlus)
7372     return Sema::IncompatibleBlockPointer;
7373 
7374   Sema::AssignConvertType ConvTy = Sema::Compatible;
7375 
7376   // For blocks we enforce that qualifiers are identical.
7377   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7378     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7379 
7380   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7381     return Sema::IncompatibleBlockPointer;
7382 
7383   return ConvTy;
7384 }
7385 
7386 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7387 /// for assignment compatibility.
7388 static Sema::AssignConvertType
7389 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7390                                    QualType RHSType) {
7391   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7392   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7393 
7394   if (LHSType->isObjCBuiltinType()) {
7395     // Class is not compatible with ObjC object pointers.
7396     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7397         !RHSType->isObjCQualifiedClassType())
7398       return Sema::IncompatiblePointer;
7399     return Sema::Compatible;
7400   }
7401   if (RHSType->isObjCBuiltinType()) {
7402     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7403         !LHSType->isObjCQualifiedClassType())
7404       return Sema::IncompatiblePointer;
7405     return Sema::Compatible;
7406   }
7407   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7408   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7409 
7410   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7411       // make an exception for id<P>
7412       !LHSType->isObjCQualifiedIdType())
7413     return Sema::CompatiblePointerDiscardsQualifiers;
7414 
7415   if (S.Context.typesAreCompatible(LHSType, RHSType))
7416     return Sema::Compatible;
7417   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7418     return Sema::IncompatibleObjCQualifiedId;
7419   return Sema::IncompatiblePointer;
7420 }
7421 
7422 Sema::AssignConvertType
7423 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7424                                  QualType LHSType, QualType RHSType) {
7425   // Fake up an opaque expression.  We don't actually care about what
7426   // cast operations are required, so if CheckAssignmentConstraints
7427   // adds casts to this they'll be wasted, but fortunately that doesn't
7428   // usually happen on valid code.
7429   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7430   ExprResult RHSPtr = &RHSExpr;
7431   CastKind K = CK_Invalid;
7432 
7433   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7434 }
7435 
7436 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7437 /// has code to accommodate several GCC extensions when type checking
7438 /// pointers. Here are some objectionable examples that GCC considers warnings:
7439 ///
7440 ///  int a, *pint;
7441 ///  short *pshort;
7442 ///  struct foo *pfoo;
7443 ///
7444 ///  pint = pshort; // warning: assignment from incompatible pointer type
7445 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7446 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7447 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7448 ///
7449 /// As a result, the code for dealing with pointers is more complex than the
7450 /// C99 spec dictates.
7451 ///
7452 /// Sets 'Kind' for any result kind except Incompatible.
7453 Sema::AssignConvertType
7454 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7455                                  CastKind &Kind, bool ConvertRHS) {
7456   QualType RHSType = RHS.get()->getType();
7457   QualType OrigLHSType = LHSType;
7458 
7459   // Get canonical types.  We're not formatting these types, just comparing
7460   // them.
7461   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7462   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7463 
7464   // Common case: no conversion required.
7465   if (LHSType == RHSType) {
7466     Kind = CK_NoOp;
7467     return Compatible;
7468   }
7469 
7470   // If we have an atomic type, try a non-atomic assignment, then just add an
7471   // atomic qualification step.
7472   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7473     Sema::AssignConvertType result =
7474       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7475     if (result != Compatible)
7476       return result;
7477     if (Kind != CK_NoOp && ConvertRHS)
7478       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7479     Kind = CK_NonAtomicToAtomic;
7480     return Compatible;
7481   }
7482 
7483   // If the left-hand side is a reference type, then we are in a
7484   // (rare!) case where we've allowed the use of references in C,
7485   // e.g., as a parameter type in a built-in function. In this case,
7486   // just make sure that the type referenced is compatible with the
7487   // right-hand side type. The caller is responsible for adjusting
7488   // LHSType so that the resulting expression does not have reference
7489   // type.
7490   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7491     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7492       Kind = CK_LValueBitCast;
7493       return Compatible;
7494     }
7495     return Incompatible;
7496   }
7497 
7498   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7499   // to the same ExtVector type.
7500   if (LHSType->isExtVectorType()) {
7501     if (RHSType->isExtVectorType())
7502       return Incompatible;
7503     if (RHSType->isArithmeticType()) {
7504       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7505       if (ConvertRHS)
7506         RHS = prepareVectorSplat(LHSType, RHS.get());
7507       Kind = CK_VectorSplat;
7508       return Compatible;
7509     }
7510   }
7511 
7512   // Conversions to or from vector type.
7513   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7514     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7515       // Allow assignments of an AltiVec vector type to an equivalent GCC
7516       // vector type and vice versa
7517       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7518         Kind = CK_BitCast;
7519         return Compatible;
7520       }
7521 
7522       // If we are allowing lax vector conversions, and LHS and RHS are both
7523       // vectors, the total size only needs to be the same. This is a bitcast;
7524       // no bits are changed but the result type is different.
7525       if (isLaxVectorConversion(RHSType, LHSType)) {
7526         Kind = CK_BitCast;
7527         return IncompatibleVectors;
7528       }
7529     }
7530 
7531     // When the RHS comes from another lax conversion (e.g. binops between
7532     // scalars and vectors) the result is canonicalized as a vector. When the
7533     // LHS is also a vector, the lax is allowed by the condition above. Handle
7534     // the case where LHS is a scalar.
7535     if (LHSType->isScalarType()) {
7536       const VectorType *VecType = RHSType->getAs<VectorType>();
7537       if (VecType && VecType->getNumElements() == 1 &&
7538           isLaxVectorConversion(RHSType, LHSType)) {
7539         ExprResult *VecExpr = &RHS;
7540         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7541         Kind = CK_BitCast;
7542         return Compatible;
7543       }
7544     }
7545 
7546     return Incompatible;
7547   }
7548 
7549   // Diagnose attempts to convert between __float128 and long double where
7550   // such conversions currently can't be handled.
7551   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7552     return Incompatible;
7553 
7554   // Arithmetic conversions.
7555   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7556       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7557     if (ConvertRHS)
7558       Kind = PrepareScalarCast(RHS, LHSType);
7559     return Compatible;
7560   }
7561 
7562   // Conversions to normal pointers.
7563   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7564     // U* -> T*
7565     if (isa<PointerType>(RHSType)) {
7566       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7567       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7568       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7569       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7570     }
7571 
7572     // int -> T*
7573     if (RHSType->isIntegerType()) {
7574       Kind = CK_IntegralToPointer; // FIXME: null?
7575       return IntToPointer;
7576     }
7577 
7578     // C pointers are not compatible with ObjC object pointers,
7579     // with two exceptions:
7580     if (isa<ObjCObjectPointerType>(RHSType)) {
7581       //  - conversions to void*
7582       if (LHSPointer->getPointeeType()->isVoidType()) {
7583         Kind = CK_BitCast;
7584         return Compatible;
7585       }
7586 
7587       //  - conversions from 'Class' to the redefinition type
7588       if (RHSType->isObjCClassType() &&
7589           Context.hasSameType(LHSType,
7590                               Context.getObjCClassRedefinitionType())) {
7591         Kind = CK_BitCast;
7592         return Compatible;
7593       }
7594 
7595       Kind = CK_BitCast;
7596       return IncompatiblePointer;
7597     }
7598 
7599     // U^ -> void*
7600     if (RHSType->getAs<BlockPointerType>()) {
7601       if (LHSPointer->getPointeeType()->isVoidType()) {
7602         Kind = CK_BitCast;
7603         return Compatible;
7604       }
7605     }
7606 
7607     return Incompatible;
7608   }
7609 
7610   // Conversions to block pointers.
7611   if (isa<BlockPointerType>(LHSType)) {
7612     // U^ -> T^
7613     if (RHSType->isBlockPointerType()) {
7614       Kind = CK_BitCast;
7615       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7616     }
7617 
7618     // int or null -> T^
7619     if (RHSType->isIntegerType()) {
7620       Kind = CK_IntegralToPointer; // FIXME: null
7621       return IntToBlockPointer;
7622     }
7623 
7624     // id -> T^
7625     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7626       Kind = CK_AnyPointerToBlockPointerCast;
7627       return Compatible;
7628     }
7629 
7630     // void* -> T^
7631     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7632       if (RHSPT->getPointeeType()->isVoidType()) {
7633         Kind = CK_AnyPointerToBlockPointerCast;
7634         return Compatible;
7635       }
7636 
7637     return Incompatible;
7638   }
7639 
7640   // Conversions to Objective-C pointers.
7641   if (isa<ObjCObjectPointerType>(LHSType)) {
7642     // A* -> B*
7643     if (RHSType->isObjCObjectPointerType()) {
7644       Kind = CK_BitCast;
7645       Sema::AssignConvertType result =
7646         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7647       if (getLangOpts().ObjCAutoRefCount &&
7648           result == Compatible &&
7649           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7650         result = IncompatibleObjCWeakRef;
7651       return result;
7652     }
7653 
7654     // int or null -> A*
7655     if (RHSType->isIntegerType()) {
7656       Kind = CK_IntegralToPointer; // FIXME: null
7657       return IntToPointer;
7658     }
7659 
7660     // In general, C pointers are not compatible with ObjC object pointers,
7661     // with two exceptions:
7662     if (isa<PointerType>(RHSType)) {
7663       Kind = CK_CPointerToObjCPointerCast;
7664 
7665       //  - conversions from 'void*'
7666       if (RHSType->isVoidPointerType()) {
7667         return Compatible;
7668       }
7669 
7670       //  - conversions to 'Class' from its redefinition type
7671       if (LHSType->isObjCClassType() &&
7672           Context.hasSameType(RHSType,
7673                               Context.getObjCClassRedefinitionType())) {
7674         return Compatible;
7675       }
7676 
7677       return IncompatiblePointer;
7678     }
7679 
7680     // Only under strict condition T^ is compatible with an Objective-C pointer.
7681     if (RHSType->isBlockPointerType() &&
7682         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7683       if (ConvertRHS)
7684         maybeExtendBlockObject(RHS);
7685       Kind = CK_BlockPointerToObjCPointerCast;
7686       return Compatible;
7687     }
7688 
7689     return Incompatible;
7690   }
7691 
7692   // Conversions from pointers that are not covered by the above.
7693   if (isa<PointerType>(RHSType)) {
7694     // T* -> _Bool
7695     if (LHSType == Context.BoolTy) {
7696       Kind = CK_PointerToBoolean;
7697       return Compatible;
7698     }
7699 
7700     // T* -> int
7701     if (LHSType->isIntegerType()) {
7702       Kind = CK_PointerToIntegral;
7703       return PointerToInt;
7704     }
7705 
7706     return Incompatible;
7707   }
7708 
7709   // Conversions from Objective-C pointers that are not covered by the above.
7710   if (isa<ObjCObjectPointerType>(RHSType)) {
7711     // T* -> _Bool
7712     if (LHSType == Context.BoolTy) {
7713       Kind = CK_PointerToBoolean;
7714       return Compatible;
7715     }
7716 
7717     // T* -> int
7718     if (LHSType->isIntegerType()) {
7719       Kind = CK_PointerToIntegral;
7720       return PointerToInt;
7721     }
7722 
7723     return Incompatible;
7724   }
7725 
7726   // struct A -> struct B
7727   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7728     if (Context.typesAreCompatible(LHSType, RHSType)) {
7729       Kind = CK_NoOp;
7730       return Compatible;
7731     }
7732   }
7733 
7734   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7735     Kind = CK_IntToOCLSampler;
7736     return Compatible;
7737   }
7738 
7739   return Incompatible;
7740 }
7741 
7742 /// \brief Constructs a transparent union from an expression that is
7743 /// used to initialize the transparent union.
7744 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7745                                       ExprResult &EResult, QualType UnionType,
7746                                       FieldDecl *Field) {
7747   // Build an initializer list that designates the appropriate member
7748   // of the transparent union.
7749   Expr *E = EResult.get();
7750   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7751                                                    E, SourceLocation());
7752   Initializer->setType(UnionType);
7753   Initializer->setInitializedFieldInUnion(Field);
7754 
7755   // Build a compound literal constructing a value of the transparent
7756   // union type from this initializer list.
7757   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7758   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7759                                         VK_RValue, Initializer, false);
7760 }
7761 
7762 Sema::AssignConvertType
7763 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7764                                                ExprResult &RHS) {
7765   QualType RHSType = RHS.get()->getType();
7766 
7767   // If the ArgType is a Union type, we want to handle a potential
7768   // transparent_union GCC extension.
7769   const RecordType *UT = ArgType->getAsUnionType();
7770   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7771     return Incompatible;
7772 
7773   // The field to initialize within the transparent union.
7774   RecordDecl *UD = UT->getDecl();
7775   FieldDecl *InitField = nullptr;
7776   // It's compatible if the expression matches any of the fields.
7777   for (auto *it : UD->fields()) {
7778     if (it->getType()->isPointerType()) {
7779       // If the transparent union contains a pointer type, we allow:
7780       // 1) void pointer
7781       // 2) null pointer constant
7782       if (RHSType->isPointerType())
7783         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7784           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7785           InitField = it;
7786           break;
7787         }
7788 
7789       if (RHS.get()->isNullPointerConstant(Context,
7790                                            Expr::NPC_ValueDependentIsNull)) {
7791         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7792                                 CK_NullToPointer);
7793         InitField = it;
7794         break;
7795       }
7796     }
7797 
7798     CastKind Kind = CK_Invalid;
7799     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7800           == Compatible) {
7801       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7802       InitField = it;
7803       break;
7804     }
7805   }
7806 
7807   if (!InitField)
7808     return Incompatible;
7809 
7810   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7811   return Compatible;
7812 }
7813 
7814 Sema::AssignConvertType
7815 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7816                                        bool Diagnose,
7817                                        bool DiagnoseCFAudited,
7818                                        bool ConvertRHS) {
7819   // We need to be able to tell the caller whether we diagnosed a problem, if
7820   // they ask us to issue diagnostics.
7821   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7822 
7823   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7824   // we can't avoid *all* modifications at the moment, so we need some somewhere
7825   // to put the updated value.
7826   ExprResult LocalRHS = CallerRHS;
7827   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7828 
7829   if (getLangOpts().CPlusPlus) {
7830     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7831       // C++ 5.17p3: If the left operand is not of class type, the
7832       // expression is implicitly converted (C++ 4) to the
7833       // cv-unqualified type of the left operand.
7834       QualType RHSType = RHS.get()->getType();
7835       if (Diagnose) {
7836         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7837                                         AA_Assigning);
7838       } else {
7839         ImplicitConversionSequence ICS =
7840             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7841                                   /*SuppressUserConversions=*/false,
7842                                   /*AllowExplicit=*/false,
7843                                   /*InOverloadResolution=*/false,
7844                                   /*CStyle=*/false,
7845                                   /*AllowObjCWritebackConversion=*/false);
7846         if (ICS.isFailure())
7847           return Incompatible;
7848         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7849                                         ICS, AA_Assigning);
7850       }
7851       if (RHS.isInvalid())
7852         return Incompatible;
7853       Sema::AssignConvertType result = Compatible;
7854       if (getLangOpts().ObjCAutoRefCount &&
7855           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7856         result = IncompatibleObjCWeakRef;
7857       return result;
7858     }
7859 
7860     // FIXME: Currently, we fall through and treat C++ classes like C
7861     // structures.
7862     // FIXME: We also fall through for atomics; not sure what should
7863     // happen there, though.
7864   } else if (RHS.get()->getType() == Context.OverloadTy) {
7865     // As a set of extensions to C, we support overloading on functions. These
7866     // functions need to be resolved here.
7867     DeclAccessPair DAP;
7868     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7869             RHS.get(), LHSType, /*Complain=*/false, DAP))
7870       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7871     else
7872       return Incompatible;
7873   }
7874 
7875   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7876   // a null pointer constant.
7877   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7878        LHSType->isBlockPointerType()) &&
7879       RHS.get()->isNullPointerConstant(Context,
7880                                        Expr::NPC_ValueDependentIsNull)) {
7881     if (Diagnose || ConvertRHS) {
7882       CastKind Kind;
7883       CXXCastPath Path;
7884       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7885                              /*IgnoreBaseAccess=*/false, Diagnose);
7886       if (ConvertRHS)
7887         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7888     }
7889     return Compatible;
7890   }
7891 
7892   // This check seems unnatural, however it is necessary to ensure the proper
7893   // conversion of functions/arrays. If the conversion were done for all
7894   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7895   // expressions that suppress this implicit conversion (&, sizeof).
7896   //
7897   // Suppress this for references: C++ 8.5.3p5.
7898   if (!LHSType->isReferenceType()) {
7899     // FIXME: We potentially allocate here even if ConvertRHS is false.
7900     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7901     if (RHS.isInvalid())
7902       return Incompatible;
7903   }
7904 
7905   Expr *PRE = RHS.get()->IgnoreParenCasts();
7906   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7907     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7908     if (PDecl && !PDecl->hasDefinition()) {
7909       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7910       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7911     }
7912   }
7913 
7914   CastKind Kind = CK_Invalid;
7915   Sema::AssignConvertType result =
7916     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7917 
7918   // C99 6.5.16.1p2: The value of the right operand is converted to the
7919   // type of the assignment expression.
7920   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7921   // so that we can use references in built-in functions even in C.
7922   // The getNonReferenceType() call makes sure that the resulting expression
7923   // does not have reference type.
7924   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7925     QualType Ty = LHSType.getNonLValueExprType(Context);
7926     Expr *E = RHS.get();
7927 
7928     // Check for various Objective-C errors. If we are not reporting
7929     // diagnostics and just checking for errors, e.g., during overload
7930     // resolution, return Incompatible to indicate the failure.
7931     if (getLangOpts().ObjCAutoRefCount &&
7932         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7933                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7934       if (!Diagnose)
7935         return Incompatible;
7936     }
7937     if (getLangOpts().ObjC1 &&
7938         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7939                                            E->getType(), E, Diagnose) ||
7940          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7941       if (!Diagnose)
7942         return Incompatible;
7943       // Replace the expression with a corrected version and continue so we
7944       // can find further errors.
7945       RHS = E;
7946       return Compatible;
7947     }
7948 
7949     if (ConvertRHS)
7950       RHS = ImpCastExprToType(E, Ty, Kind);
7951   }
7952   return result;
7953 }
7954 
7955 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7956                                ExprResult &RHS) {
7957   Diag(Loc, diag::err_typecheck_invalid_operands)
7958     << LHS.get()->getType() << RHS.get()->getType()
7959     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7960   return QualType();
7961 }
7962 
7963 /// Try to convert a value of non-vector type to a vector type by converting
7964 /// the type to the element type of the vector and then performing a splat.
7965 /// If the language is OpenCL, we only use conversions that promote scalar
7966 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7967 /// for float->int.
7968 ///
7969 /// \param scalar - if non-null, actually perform the conversions
7970 /// \return true if the operation fails (but without diagnosing the failure)
7971 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7972                                      QualType scalarTy,
7973                                      QualType vectorEltTy,
7974                                      QualType vectorTy) {
7975   // The conversion to apply to the scalar before splatting it,
7976   // if necessary.
7977   CastKind scalarCast = CK_Invalid;
7978 
7979   if (vectorEltTy->isIntegralType(S.Context)) {
7980     if (!scalarTy->isIntegralType(S.Context))
7981       return true;
7982     if (S.getLangOpts().OpenCL &&
7983         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7984       return true;
7985     scalarCast = CK_IntegralCast;
7986   } else if (vectorEltTy->isRealFloatingType()) {
7987     if (scalarTy->isRealFloatingType()) {
7988       if (S.getLangOpts().OpenCL &&
7989           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7990         return true;
7991       scalarCast = CK_FloatingCast;
7992     }
7993     else if (scalarTy->isIntegralType(S.Context))
7994       scalarCast = CK_IntegralToFloating;
7995     else
7996       return true;
7997   } else {
7998     return true;
7999   }
8000 
8001   // Adjust scalar if desired.
8002   if (scalar) {
8003     if (scalarCast != CK_Invalid)
8004       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8005     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8006   }
8007   return false;
8008 }
8009 
8010 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8011                                    SourceLocation Loc, bool IsCompAssign,
8012                                    bool AllowBothBool,
8013                                    bool AllowBoolConversions) {
8014   if (!IsCompAssign) {
8015     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8016     if (LHS.isInvalid())
8017       return QualType();
8018   }
8019   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8020   if (RHS.isInvalid())
8021     return QualType();
8022 
8023   // For conversion purposes, we ignore any qualifiers.
8024   // For example, "const float" and "float" are equivalent.
8025   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8026   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8027 
8028   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8029   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8030   assert(LHSVecType || RHSVecType);
8031 
8032   // AltiVec-style "vector bool op vector bool" combinations are allowed
8033   // for some operators but not others.
8034   if (!AllowBothBool &&
8035       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8036       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8037     return InvalidOperands(Loc, LHS, RHS);
8038 
8039   // If the vector types are identical, return.
8040   if (Context.hasSameType(LHSType, RHSType))
8041     return LHSType;
8042 
8043   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8044   if (LHSVecType && RHSVecType &&
8045       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8046     if (isa<ExtVectorType>(LHSVecType)) {
8047       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8048       return LHSType;
8049     }
8050 
8051     if (!IsCompAssign)
8052       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8053     return RHSType;
8054   }
8055 
8056   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8057   // can be mixed, with the result being the non-bool type.  The non-bool
8058   // operand must have integer element type.
8059   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8060       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8061       (Context.getTypeSize(LHSVecType->getElementType()) ==
8062        Context.getTypeSize(RHSVecType->getElementType()))) {
8063     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8064         LHSVecType->getElementType()->isIntegerType() &&
8065         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8066       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8067       return LHSType;
8068     }
8069     if (!IsCompAssign &&
8070         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8071         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8072         RHSVecType->getElementType()->isIntegerType()) {
8073       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8074       return RHSType;
8075     }
8076   }
8077 
8078   // If there's an ext-vector type and a scalar, try to convert the scalar to
8079   // the vector element type and splat.
8080   // FIXME: this should also work for regular vector types as supported in GCC.
8081   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8082     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8083                                   LHSVecType->getElementType(), LHSType))
8084       return LHSType;
8085   }
8086   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8087     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8088                                   LHSType, RHSVecType->getElementType(),
8089                                   RHSType))
8090       return RHSType;
8091   }
8092 
8093   // FIXME: The code below also handles convertion between vectors and
8094   // non-scalars, we should break this down into fine grained specific checks
8095   // and emit proper diagnostics.
8096   QualType VecType = LHSVecType ? LHSType : RHSType;
8097   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8098   QualType OtherType = LHSVecType ? RHSType : LHSType;
8099   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8100   if (isLaxVectorConversion(OtherType, VecType)) {
8101     // If we're allowing lax vector conversions, only the total (data) size
8102     // needs to be the same. For non compound assignment, if one of the types is
8103     // scalar, the result is always the vector type.
8104     if (!IsCompAssign) {
8105       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8106       return VecType;
8107     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8108     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8109     // type. Note that this is already done by non-compound assignments in
8110     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8111     // <1 x T> -> T. The result is also a vector type.
8112     } else if (OtherType->isExtVectorType() ||
8113                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8114       ExprResult *RHSExpr = &RHS;
8115       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8116       return VecType;
8117     }
8118   }
8119 
8120   // Okay, the expression is invalid.
8121 
8122   // If there's a non-vector, non-real operand, diagnose that.
8123   if ((!RHSVecType && !RHSType->isRealType()) ||
8124       (!LHSVecType && !LHSType->isRealType())) {
8125     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8126       << LHSType << RHSType
8127       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8128     return QualType();
8129   }
8130 
8131   // OpenCL V1.1 6.2.6.p1:
8132   // If the operands are of more than one vector type, then an error shall
8133   // occur. Implicit conversions between vector types are not permitted, per
8134   // section 6.2.1.
8135   if (getLangOpts().OpenCL &&
8136       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8137       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8138     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8139                                                            << RHSType;
8140     return QualType();
8141   }
8142 
8143   // Otherwise, use the generic diagnostic.
8144   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8145     << LHSType << RHSType
8146     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8147   return QualType();
8148 }
8149 
8150 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8151 // expression.  These are mainly cases where the null pointer is used as an
8152 // integer instead of a pointer.
8153 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8154                                 SourceLocation Loc, bool IsCompare) {
8155   // The canonical way to check for a GNU null is with isNullPointerConstant,
8156   // but we use a bit of a hack here for speed; this is a relatively
8157   // hot path, and isNullPointerConstant is slow.
8158   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8159   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8160 
8161   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8162 
8163   // Avoid analyzing cases where the result will either be invalid (and
8164   // diagnosed as such) or entirely valid and not something to warn about.
8165   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8166       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8167     return;
8168 
8169   // Comparison operations would not make sense with a null pointer no matter
8170   // what the other expression is.
8171   if (!IsCompare) {
8172     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8173         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8174         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8175     return;
8176   }
8177 
8178   // The rest of the operations only make sense with a null pointer
8179   // if the other expression is a pointer.
8180   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8181       NonNullType->canDecayToPointerType())
8182     return;
8183 
8184   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8185       << LHSNull /* LHS is NULL */ << NonNullType
8186       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8187 }
8188 
8189 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8190                                                ExprResult &RHS,
8191                                                SourceLocation Loc, bool IsDiv) {
8192   // Check for division/remainder by zero.
8193   llvm::APSInt RHSValue;
8194   if (!RHS.get()->isValueDependent() &&
8195       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8196     S.DiagRuntimeBehavior(Loc, RHS.get(),
8197                           S.PDiag(diag::warn_remainder_division_by_zero)
8198                             << IsDiv << RHS.get()->getSourceRange());
8199 }
8200 
8201 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8202                                            SourceLocation Loc,
8203                                            bool IsCompAssign, bool IsDiv) {
8204   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8205 
8206   if (LHS.get()->getType()->isVectorType() ||
8207       RHS.get()->getType()->isVectorType())
8208     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8209                                /*AllowBothBool*/getLangOpts().AltiVec,
8210                                /*AllowBoolConversions*/false);
8211 
8212   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8213   if (LHS.isInvalid() || RHS.isInvalid())
8214     return QualType();
8215 
8216 
8217   if (compType.isNull() || !compType->isArithmeticType())
8218     return InvalidOperands(Loc, LHS, RHS);
8219   if (IsDiv)
8220     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8221   return compType;
8222 }
8223 
8224 QualType Sema::CheckRemainderOperands(
8225   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8226   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8227 
8228   if (LHS.get()->getType()->isVectorType() ||
8229       RHS.get()->getType()->isVectorType()) {
8230     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8231         RHS.get()->getType()->hasIntegerRepresentation())
8232       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8233                                  /*AllowBothBool*/getLangOpts().AltiVec,
8234                                  /*AllowBoolConversions*/false);
8235     return InvalidOperands(Loc, LHS, RHS);
8236   }
8237 
8238   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8239   if (LHS.isInvalid() || RHS.isInvalid())
8240     return QualType();
8241 
8242   if (compType.isNull() || !compType->isIntegerType())
8243     return InvalidOperands(Loc, LHS, RHS);
8244   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8245   return compType;
8246 }
8247 
8248 /// \brief Diagnose invalid arithmetic on two void pointers.
8249 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8250                                                 Expr *LHSExpr, Expr *RHSExpr) {
8251   S.Diag(Loc, S.getLangOpts().CPlusPlus
8252                 ? diag::err_typecheck_pointer_arith_void_type
8253                 : diag::ext_gnu_void_ptr)
8254     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8255                             << RHSExpr->getSourceRange();
8256 }
8257 
8258 /// \brief Diagnose invalid arithmetic on a void pointer.
8259 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8260                                             Expr *Pointer) {
8261   S.Diag(Loc, S.getLangOpts().CPlusPlus
8262                 ? diag::err_typecheck_pointer_arith_void_type
8263                 : diag::ext_gnu_void_ptr)
8264     << 0 /* one pointer */ << Pointer->getSourceRange();
8265 }
8266 
8267 /// \brief Diagnose invalid arithmetic on two function pointers.
8268 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8269                                                     Expr *LHS, Expr *RHS) {
8270   assert(LHS->getType()->isAnyPointerType());
8271   assert(RHS->getType()->isAnyPointerType());
8272   S.Diag(Loc, S.getLangOpts().CPlusPlus
8273                 ? diag::err_typecheck_pointer_arith_function_type
8274                 : diag::ext_gnu_ptr_func_arith)
8275     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8276     // We only show the second type if it differs from the first.
8277     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8278                                                    RHS->getType())
8279     << RHS->getType()->getPointeeType()
8280     << LHS->getSourceRange() << RHS->getSourceRange();
8281 }
8282 
8283 /// \brief Diagnose invalid arithmetic on a function pointer.
8284 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8285                                                 Expr *Pointer) {
8286   assert(Pointer->getType()->isAnyPointerType());
8287   S.Diag(Loc, S.getLangOpts().CPlusPlus
8288                 ? diag::err_typecheck_pointer_arith_function_type
8289                 : diag::ext_gnu_ptr_func_arith)
8290     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8291     << 0 /* one pointer, so only one type */
8292     << Pointer->getSourceRange();
8293 }
8294 
8295 /// \brief Emit error if Operand is incomplete pointer type
8296 ///
8297 /// \returns True if pointer has incomplete type
8298 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8299                                                  Expr *Operand) {
8300   QualType ResType = Operand->getType();
8301   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8302     ResType = ResAtomicType->getValueType();
8303 
8304   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8305   QualType PointeeTy = ResType->getPointeeType();
8306   return S.RequireCompleteType(Loc, PointeeTy,
8307                                diag::err_typecheck_arithmetic_incomplete_type,
8308                                PointeeTy, Operand->getSourceRange());
8309 }
8310 
8311 /// \brief Check the validity of an arithmetic pointer operand.
8312 ///
8313 /// If the operand has pointer type, this code will check for pointer types
8314 /// which are invalid in arithmetic operations. These will be diagnosed
8315 /// appropriately, including whether or not the use is supported as an
8316 /// extension.
8317 ///
8318 /// \returns True when the operand is valid to use (even if as an extension).
8319 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8320                                             Expr *Operand) {
8321   QualType ResType = Operand->getType();
8322   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8323     ResType = ResAtomicType->getValueType();
8324 
8325   if (!ResType->isAnyPointerType()) return true;
8326 
8327   QualType PointeeTy = ResType->getPointeeType();
8328   if (PointeeTy->isVoidType()) {
8329     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8330     return !S.getLangOpts().CPlusPlus;
8331   }
8332   if (PointeeTy->isFunctionType()) {
8333     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8334     return !S.getLangOpts().CPlusPlus;
8335   }
8336 
8337   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8338 
8339   return true;
8340 }
8341 
8342 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8343 /// operands.
8344 ///
8345 /// This routine will diagnose any invalid arithmetic on pointer operands much
8346 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8347 /// for emitting a single diagnostic even for operations where both LHS and RHS
8348 /// are (potentially problematic) pointers.
8349 ///
8350 /// \returns True when the operand is valid to use (even if as an extension).
8351 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8352                                                 Expr *LHSExpr, Expr *RHSExpr) {
8353   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8354   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8355   if (!isLHSPointer && !isRHSPointer) return true;
8356 
8357   QualType LHSPointeeTy, RHSPointeeTy;
8358   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8359   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8360 
8361   // if both are pointers check if operation is valid wrt address spaces
8362   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8363     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8364     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8365     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8366       S.Diag(Loc,
8367              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8368           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8369           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8370       return false;
8371     }
8372   }
8373 
8374   // Check for arithmetic on pointers to incomplete types.
8375   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8376   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8377   if (isLHSVoidPtr || isRHSVoidPtr) {
8378     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8379     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8380     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8381 
8382     return !S.getLangOpts().CPlusPlus;
8383   }
8384 
8385   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8386   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8387   if (isLHSFuncPtr || isRHSFuncPtr) {
8388     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8389     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8390                                                                 RHSExpr);
8391     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8392 
8393     return !S.getLangOpts().CPlusPlus;
8394   }
8395 
8396   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8397     return false;
8398   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8399     return false;
8400 
8401   return true;
8402 }
8403 
8404 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8405 /// literal.
8406 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8407                                   Expr *LHSExpr, Expr *RHSExpr) {
8408   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8409   Expr* IndexExpr = RHSExpr;
8410   if (!StrExpr) {
8411     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8412     IndexExpr = LHSExpr;
8413   }
8414 
8415   bool IsStringPlusInt = StrExpr &&
8416       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8417   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8418     return;
8419 
8420   llvm::APSInt index;
8421   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8422     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8423     if (index.isNonNegative() &&
8424         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8425                               index.isUnsigned()))
8426       return;
8427   }
8428 
8429   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8430   Self.Diag(OpLoc, diag::warn_string_plus_int)
8431       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8432 
8433   // Only print a fixit for "str" + int, not for int + "str".
8434   if (IndexExpr == RHSExpr) {
8435     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8436     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8437         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8438         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8439         << FixItHint::CreateInsertion(EndLoc, "]");
8440   } else
8441     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8442 }
8443 
8444 /// \brief Emit a warning when adding a char literal to a string.
8445 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8446                                    Expr *LHSExpr, Expr *RHSExpr) {
8447   const Expr *StringRefExpr = LHSExpr;
8448   const CharacterLiteral *CharExpr =
8449       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8450 
8451   if (!CharExpr) {
8452     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8453     StringRefExpr = RHSExpr;
8454   }
8455 
8456   if (!CharExpr || !StringRefExpr)
8457     return;
8458 
8459   const QualType StringType = StringRefExpr->getType();
8460 
8461   // Return if not a PointerType.
8462   if (!StringType->isAnyPointerType())
8463     return;
8464 
8465   // Return if not a CharacterType.
8466   if (!StringType->getPointeeType()->isAnyCharacterType())
8467     return;
8468 
8469   ASTContext &Ctx = Self.getASTContext();
8470   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8471 
8472   const QualType CharType = CharExpr->getType();
8473   if (!CharType->isAnyCharacterType() &&
8474       CharType->isIntegerType() &&
8475       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8476     Self.Diag(OpLoc, diag::warn_string_plus_char)
8477         << DiagRange << Ctx.CharTy;
8478   } else {
8479     Self.Diag(OpLoc, diag::warn_string_plus_char)
8480         << DiagRange << CharExpr->getType();
8481   }
8482 
8483   // Only print a fixit for str + char, not for char + str.
8484   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8485     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8486     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8487         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8488         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8489         << FixItHint::CreateInsertion(EndLoc, "]");
8490   } else {
8491     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8492   }
8493 }
8494 
8495 /// \brief Emit error when two pointers are incompatible.
8496 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8497                                            Expr *LHSExpr, Expr *RHSExpr) {
8498   assert(LHSExpr->getType()->isAnyPointerType());
8499   assert(RHSExpr->getType()->isAnyPointerType());
8500   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8501     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8502     << RHSExpr->getSourceRange();
8503 }
8504 
8505 // C99 6.5.6
8506 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8507                                      SourceLocation Loc, BinaryOperatorKind Opc,
8508                                      QualType* CompLHSTy) {
8509   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8510 
8511   if (LHS.get()->getType()->isVectorType() ||
8512       RHS.get()->getType()->isVectorType()) {
8513     QualType compType = CheckVectorOperands(
8514         LHS, RHS, Loc, CompLHSTy,
8515         /*AllowBothBool*/getLangOpts().AltiVec,
8516         /*AllowBoolConversions*/getLangOpts().ZVector);
8517     if (CompLHSTy) *CompLHSTy = compType;
8518     return compType;
8519   }
8520 
8521   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8522   if (LHS.isInvalid() || RHS.isInvalid())
8523     return QualType();
8524 
8525   // Diagnose "string literal" '+' int and string '+' "char literal".
8526   if (Opc == BO_Add) {
8527     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8528     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8529   }
8530 
8531   // handle the common case first (both operands are arithmetic).
8532   if (!compType.isNull() && compType->isArithmeticType()) {
8533     if (CompLHSTy) *CompLHSTy = compType;
8534     return compType;
8535   }
8536 
8537   // Type-checking.  Ultimately the pointer's going to be in PExp;
8538   // note that we bias towards the LHS being the pointer.
8539   Expr *PExp = LHS.get(), *IExp = RHS.get();
8540 
8541   bool isObjCPointer;
8542   if (PExp->getType()->isPointerType()) {
8543     isObjCPointer = false;
8544   } else if (PExp->getType()->isObjCObjectPointerType()) {
8545     isObjCPointer = true;
8546   } else {
8547     std::swap(PExp, IExp);
8548     if (PExp->getType()->isPointerType()) {
8549       isObjCPointer = false;
8550     } else if (PExp->getType()->isObjCObjectPointerType()) {
8551       isObjCPointer = true;
8552     } else {
8553       return InvalidOperands(Loc, LHS, RHS);
8554     }
8555   }
8556   assert(PExp->getType()->isAnyPointerType());
8557 
8558   if (!IExp->getType()->isIntegerType())
8559     return InvalidOperands(Loc, LHS, RHS);
8560 
8561   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8562     return QualType();
8563 
8564   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8565     return QualType();
8566 
8567   // Check array bounds for pointer arithemtic
8568   CheckArrayAccess(PExp, IExp);
8569 
8570   if (CompLHSTy) {
8571     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8572     if (LHSTy.isNull()) {
8573       LHSTy = LHS.get()->getType();
8574       if (LHSTy->isPromotableIntegerType())
8575         LHSTy = Context.getPromotedIntegerType(LHSTy);
8576     }
8577     *CompLHSTy = LHSTy;
8578   }
8579 
8580   return PExp->getType();
8581 }
8582 
8583 // C99 6.5.6
8584 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8585                                         SourceLocation Loc,
8586                                         QualType* CompLHSTy) {
8587   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8588 
8589   if (LHS.get()->getType()->isVectorType() ||
8590       RHS.get()->getType()->isVectorType()) {
8591     QualType compType = CheckVectorOperands(
8592         LHS, RHS, Loc, CompLHSTy,
8593         /*AllowBothBool*/getLangOpts().AltiVec,
8594         /*AllowBoolConversions*/getLangOpts().ZVector);
8595     if (CompLHSTy) *CompLHSTy = compType;
8596     return compType;
8597   }
8598 
8599   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8600   if (LHS.isInvalid() || RHS.isInvalid())
8601     return QualType();
8602 
8603   // Enforce type constraints: C99 6.5.6p3.
8604 
8605   // Handle the common case first (both operands are arithmetic).
8606   if (!compType.isNull() && compType->isArithmeticType()) {
8607     if (CompLHSTy) *CompLHSTy = compType;
8608     return compType;
8609   }
8610 
8611   // Either ptr - int   or   ptr - ptr.
8612   if (LHS.get()->getType()->isAnyPointerType()) {
8613     QualType lpointee = LHS.get()->getType()->getPointeeType();
8614 
8615     // Diagnose bad cases where we step over interface counts.
8616     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8617         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8618       return QualType();
8619 
8620     // The result type of a pointer-int computation is the pointer type.
8621     if (RHS.get()->getType()->isIntegerType()) {
8622       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8623         return QualType();
8624 
8625       // Check array bounds for pointer arithemtic
8626       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8627                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8628 
8629       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8630       return LHS.get()->getType();
8631     }
8632 
8633     // Handle pointer-pointer subtractions.
8634     if (const PointerType *RHSPTy
8635           = RHS.get()->getType()->getAs<PointerType>()) {
8636       QualType rpointee = RHSPTy->getPointeeType();
8637 
8638       if (getLangOpts().CPlusPlus) {
8639         // Pointee types must be the same: C++ [expr.add]
8640         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8641           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8642         }
8643       } else {
8644         // Pointee types must be compatible C99 6.5.6p3
8645         if (!Context.typesAreCompatible(
8646                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8647                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8648           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8649           return QualType();
8650         }
8651       }
8652 
8653       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8654                                                LHS.get(), RHS.get()))
8655         return QualType();
8656 
8657       // The pointee type may have zero size.  As an extension, a structure or
8658       // union may have zero size or an array may have zero length.  In this
8659       // case subtraction does not make sense.
8660       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8661         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8662         if (ElementSize.isZero()) {
8663           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8664             << rpointee.getUnqualifiedType()
8665             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8666         }
8667       }
8668 
8669       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8670       return Context.getPointerDiffType();
8671     }
8672   }
8673 
8674   return InvalidOperands(Loc, LHS, RHS);
8675 }
8676 
8677 static bool isScopedEnumerationType(QualType T) {
8678   if (const EnumType *ET = T->getAs<EnumType>())
8679     return ET->getDecl()->isScoped();
8680   return false;
8681 }
8682 
8683 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8684                                    SourceLocation Loc, BinaryOperatorKind Opc,
8685                                    QualType LHSType) {
8686   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8687   // so skip remaining warnings as we don't want to modify values within Sema.
8688   if (S.getLangOpts().OpenCL)
8689     return;
8690 
8691   llvm::APSInt Right;
8692   // Check right/shifter operand
8693   if (RHS.get()->isValueDependent() ||
8694       !RHS.get()->EvaluateAsInt(Right, S.Context))
8695     return;
8696 
8697   if (Right.isNegative()) {
8698     S.DiagRuntimeBehavior(Loc, RHS.get(),
8699                           S.PDiag(diag::warn_shift_negative)
8700                             << RHS.get()->getSourceRange());
8701     return;
8702   }
8703   llvm::APInt LeftBits(Right.getBitWidth(),
8704                        S.Context.getTypeSize(LHS.get()->getType()));
8705   if (Right.uge(LeftBits)) {
8706     S.DiagRuntimeBehavior(Loc, RHS.get(),
8707                           S.PDiag(diag::warn_shift_gt_typewidth)
8708                             << RHS.get()->getSourceRange());
8709     return;
8710   }
8711   if (Opc != BO_Shl)
8712     return;
8713 
8714   // When left shifting an ICE which is signed, we can check for overflow which
8715   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8716   // integers have defined behavior modulo one more than the maximum value
8717   // representable in the result type, so never warn for those.
8718   llvm::APSInt Left;
8719   if (LHS.get()->isValueDependent() ||
8720       LHSType->hasUnsignedIntegerRepresentation() ||
8721       !LHS.get()->EvaluateAsInt(Left, S.Context))
8722     return;
8723 
8724   // If LHS does not have a signed type and non-negative value
8725   // then, the behavior is undefined. Warn about it.
8726   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8727     S.DiagRuntimeBehavior(Loc, LHS.get(),
8728                           S.PDiag(diag::warn_shift_lhs_negative)
8729                             << LHS.get()->getSourceRange());
8730     return;
8731   }
8732 
8733   llvm::APInt ResultBits =
8734       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8735   if (LeftBits.uge(ResultBits))
8736     return;
8737   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8738   Result = Result.shl(Right);
8739 
8740   // Print the bit representation of the signed integer as an unsigned
8741   // hexadecimal number.
8742   SmallString<40> HexResult;
8743   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8744 
8745   // If we are only missing a sign bit, this is less likely to result in actual
8746   // bugs -- if the result is cast back to an unsigned type, it will have the
8747   // expected value. Thus we place this behind a different warning that can be
8748   // turned off separately if needed.
8749   if (LeftBits == ResultBits - 1) {
8750     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8751         << HexResult << LHSType
8752         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8753     return;
8754   }
8755 
8756   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8757     << HexResult.str() << Result.getMinSignedBits() << LHSType
8758     << Left.getBitWidth() << LHS.get()->getSourceRange()
8759     << RHS.get()->getSourceRange();
8760 }
8761 
8762 /// \brief Return the resulting type when a vector is shifted
8763 ///        by a scalar or vector shift amount.
8764 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8765                                  SourceLocation Loc, bool IsCompAssign) {
8766   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8767   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8768       !LHS.get()->getType()->isVectorType()) {
8769     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8770       << RHS.get()->getType() << LHS.get()->getType()
8771       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8772     return QualType();
8773   }
8774 
8775   if (!IsCompAssign) {
8776     LHS = S.UsualUnaryConversions(LHS.get());
8777     if (LHS.isInvalid()) return QualType();
8778   }
8779 
8780   RHS = S.UsualUnaryConversions(RHS.get());
8781   if (RHS.isInvalid()) return QualType();
8782 
8783   QualType LHSType = LHS.get()->getType();
8784   // Note that LHS might be a scalar because the routine calls not only in
8785   // OpenCL case.
8786   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8787   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8788 
8789   // Note that RHS might not be a vector.
8790   QualType RHSType = RHS.get()->getType();
8791   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8792   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8793 
8794   // The operands need to be integers.
8795   if (!LHSEleType->isIntegerType()) {
8796     S.Diag(Loc, diag::err_typecheck_expect_int)
8797       << LHS.get()->getType() << LHS.get()->getSourceRange();
8798     return QualType();
8799   }
8800 
8801   if (!RHSEleType->isIntegerType()) {
8802     S.Diag(Loc, diag::err_typecheck_expect_int)
8803       << RHS.get()->getType() << RHS.get()->getSourceRange();
8804     return QualType();
8805   }
8806 
8807   if (!LHSVecTy) {
8808     assert(RHSVecTy);
8809     if (IsCompAssign)
8810       return RHSType;
8811     if (LHSEleType != RHSEleType) {
8812       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8813       LHSEleType = RHSEleType;
8814     }
8815     QualType VecTy =
8816         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8817     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8818     LHSType = VecTy;
8819   } else if (RHSVecTy) {
8820     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8821     // are applied component-wise. So if RHS is a vector, then ensure
8822     // that the number of elements is the same as LHS...
8823     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8824       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8825         << LHS.get()->getType() << RHS.get()->getType()
8826         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8827       return QualType();
8828     }
8829     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8830       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8831       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8832       if (LHSBT != RHSBT &&
8833           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8834         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8835             << LHS.get()->getType() << RHS.get()->getType()
8836             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8837       }
8838     }
8839   } else {
8840     // ...else expand RHS to match the number of elements in LHS.
8841     QualType VecTy =
8842       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8843     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8844   }
8845 
8846   return LHSType;
8847 }
8848 
8849 // C99 6.5.7
8850 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8851                                   SourceLocation Loc, BinaryOperatorKind Opc,
8852                                   bool IsCompAssign) {
8853   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8854 
8855   // Vector shifts promote their scalar inputs to vector type.
8856   if (LHS.get()->getType()->isVectorType() ||
8857       RHS.get()->getType()->isVectorType()) {
8858     if (LangOpts.ZVector) {
8859       // The shift operators for the z vector extensions work basically
8860       // like general shifts, except that neither the LHS nor the RHS is
8861       // allowed to be a "vector bool".
8862       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8863         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8864           return InvalidOperands(Loc, LHS, RHS);
8865       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8866         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8867           return InvalidOperands(Loc, LHS, RHS);
8868     }
8869     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8870   }
8871 
8872   // Shifts don't perform usual arithmetic conversions, they just do integer
8873   // promotions on each operand. C99 6.5.7p3
8874 
8875   // For the LHS, do usual unary conversions, but then reset them away
8876   // if this is a compound assignment.
8877   ExprResult OldLHS = LHS;
8878   LHS = UsualUnaryConversions(LHS.get());
8879   if (LHS.isInvalid())
8880     return QualType();
8881   QualType LHSType = LHS.get()->getType();
8882   if (IsCompAssign) LHS = OldLHS;
8883 
8884   // The RHS is simpler.
8885   RHS = UsualUnaryConversions(RHS.get());
8886   if (RHS.isInvalid())
8887     return QualType();
8888   QualType RHSType = RHS.get()->getType();
8889 
8890   // C99 6.5.7p2: Each of the operands shall have integer type.
8891   if (!LHSType->hasIntegerRepresentation() ||
8892       !RHSType->hasIntegerRepresentation())
8893     return InvalidOperands(Loc, LHS, RHS);
8894 
8895   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8896   // hasIntegerRepresentation() above instead of this.
8897   if (isScopedEnumerationType(LHSType) ||
8898       isScopedEnumerationType(RHSType)) {
8899     return InvalidOperands(Loc, LHS, RHS);
8900   }
8901   // Sanity-check shift operands
8902   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8903 
8904   // "The type of the result is that of the promoted left operand."
8905   return LHSType;
8906 }
8907 
8908 static bool IsWithinTemplateSpecialization(Decl *D) {
8909   if (DeclContext *DC = D->getDeclContext()) {
8910     if (isa<ClassTemplateSpecializationDecl>(DC))
8911       return true;
8912     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8913       return FD->isFunctionTemplateSpecialization();
8914   }
8915   return false;
8916 }
8917 
8918 /// If two different enums are compared, raise a warning.
8919 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8920                                 Expr *RHS) {
8921   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8922   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8923 
8924   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8925   if (!LHSEnumType)
8926     return;
8927   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8928   if (!RHSEnumType)
8929     return;
8930 
8931   // Ignore anonymous enums.
8932   if (!LHSEnumType->getDecl()->getIdentifier())
8933     return;
8934   if (!RHSEnumType->getDecl()->getIdentifier())
8935     return;
8936 
8937   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8938     return;
8939 
8940   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8941       << LHSStrippedType << RHSStrippedType
8942       << LHS->getSourceRange() << RHS->getSourceRange();
8943 }
8944 
8945 /// \brief Diagnose bad pointer comparisons.
8946 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8947                                               ExprResult &LHS, ExprResult &RHS,
8948                                               bool IsError) {
8949   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8950                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8951     << LHS.get()->getType() << RHS.get()->getType()
8952     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8953 }
8954 
8955 /// \brief Returns false if the pointers are converted to a composite type,
8956 /// true otherwise.
8957 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8958                                            ExprResult &LHS, ExprResult &RHS) {
8959   // C++ [expr.rel]p2:
8960   //   [...] Pointer conversions (4.10) and qualification
8961   //   conversions (4.4) are performed on pointer operands (or on
8962   //   a pointer operand and a null pointer constant) to bring
8963   //   them to their composite pointer type. [...]
8964   //
8965   // C++ [expr.eq]p1 uses the same notion for (in)equality
8966   // comparisons of pointers.
8967 
8968   QualType LHSType = LHS.get()->getType();
8969   QualType RHSType = RHS.get()->getType();
8970   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8971          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8972 
8973   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8974   if (T.isNull()) {
8975     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8976         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8977       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8978     else
8979       S.InvalidOperands(Loc, LHS, RHS);
8980     return true;
8981   }
8982 
8983   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8984   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8985   return false;
8986 }
8987 
8988 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8989                                                     ExprResult &LHS,
8990                                                     ExprResult &RHS,
8991                                                     bool IsError) {
8992   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8993                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8994     << LHS.get()->getType() << RHS.get()->getType()
8995     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8996 }
8997 
8998 static bool isObjCObjectLiteral(ExprResult &E) {
8999   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9000   case Stmt::ObjCArrayLiteralClass:
9001   case Stmt::ObjCDictionaryLiteralClass:
9002   case Stmt::ObjCStringLiteralClass:
9003   case Stmt::ObjCBoxedExprClass:
9004     return true;
9005   default:
9006     // Note that ObjCBoolLiteral is NOT an object literal!
9007     return false;
9008   }
9009 }
9010 
9011 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9012   const ObjCObjectPointerType *Type =
9013     LHS->getType()->getAs<ObjCObjectPointerType>();
9014 
9015   // If this is not actually an Objective-C object, bail out.
9016   if (!Type)
9017     return false;
9018 
9019   // Get the LHS object's interface type.
9020   QualType InterfaceType = Type->getPointeeType();
9021 
9022   // If the RHS isn't an Objective-C object, bail out.
9023   if (!RHS->getType()->isObjCObjectPointerType())
9024     return false;
9025 
9026   // Try to find the -isEqual: method.
9027   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9028   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9029                                                       InterfaceType,
9030                                                       /*instance=*/true);
9031   if (!Method) {
9032     if (Type->isObjCIdType()) {
9033       // For 'id', just check the global pool.
9034       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9035                                                   /*receiverId=*/true);
9036     } else {
9037       // Check protocols.
9038       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9039                                              /*instance=*/true);
9040     }
9041   }
9042 
9043   if (!Method)
9044     return false;
9045 
9046   QualType T = Method->parameters()[0]->getType();
9047   if (!T->isObjCObjectPointerType())
9048     return false;
9049 
9050   QualType R = Method->getReturnType();
9051   if (!R->isScalarType())
9052     return false;
9053 
9054   return true;
9055 }
9056 
9057 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9058   FromE = FromE->IgnoreParenImpCasts();
9059   switch (FromE->getStmtClass()) {
9060     default:
9061       break;
9062     case Stmt::ObjCStringLiteralClass:
9063       // "string literal"
9064       return LK_String;
9065     case Stmt::ObjCArrayLiteralClass:
9066       // "array literal"
9067       return LK_Array;
9068     case Stmt::ObjCDictionaryLiteralClass:
9069       // "dictionary literal"
9070       return LK_Dictionary;
9071     case Stmt::BlockExprClass:
9072       return LK_Block;
9073     case Stmt::ObjCBoxedExprClass: {
9074       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9075       switch (Inner->getStmtClass()) {
9076         case Stmt::IntegerLiteralClass:
9077         case Stmt::FloatingLiteralClass:
9078         case Stmt::CharacterLiteralClass:
9079         case Stmt::ObjCBoolLiteralExprClass:
9080         case Stmt::CXXBoolLiteralExprClass:
9081           // "numeric literal"
9082           return LK_Numeric;
9083         case Stmt::ImplicitCastExprClass: {
9084           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9085           // Boolean literals can be represented by implicit casts.
9086           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9087             return LK_Numeric;
9088           break;
9089         }
9090         default:
9091           break;
9092       }
9093       return LK_Boxed;
9094     }
9095   }
9096   return LK_None;
9097 }
9098 
9099 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9100                                           ExprResult &LHS, ExprResult &RHS,
9101                                           BinaryOperator::Opcode Opc){
9102   Expr *Literal;
9103   Expr *Other;
9104   if (isObjCObjectLiteral(LHS)) {
9105     Literal = LHS.get();
9106     Other = RHS.get();
9107   } else {
9108     Literal = RHS.get();
9109     Other = LHS.get();
9110   }
9111 
9112   // Don't warn on comparisons against nil.
9113   Other = Other->IgnoreParenCasts();
9114   if (Other->isNullPointerConstant(S.getASTContext(),
9115                                    Expr::NPC_ValueDependentIsNotNull))
9116     return;
9117 
9118   // This should be kept in sync with warn_objc_literal_comparison.
9119   // LK_String should always be after the other literals, since it has its own
9120   // warning flag.
9121   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9122   assert(LiteralKind != Sema::LK_Block);
9123   if (LiteralKind == Sema::LK_None) {
9124     llvm_unreachable("Unknown Objective-C object literal kind");
9125   }
9126 
9127   if (LiteralKind == Sema::LK_String)
9128     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9129       << Literal->getSourceRange();
9130   else
9131     S.Diag(Loc, diag::warn_objc_literal_comparison)
9132       << LiteralKind << Literal->getSourceRange();
9133 
9134   if (BinaryOperator::isEqualityOp(Opc) &&
9135       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9136     SourceLocation Start = LHS.get()->getLocStart();
9137     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9138     CharSourceRange OpRange =
9139       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9140 
9141     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9142       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9143       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9144       << FixItHint::CreateInsertion(End, "]");
9145   }
9146 }
9147 
9148 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9149 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9150                                            ExprResult &RHS, SourceLocation Loc,
9151                                            BinaryOperatorKind Opc) {
9152   // Check that left hand side is !something.
9153   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9154   if (!UO || UO->getOpcode() != UO_LNot) return;
9155 
9156   // Only check if the right hand side is non-bool arithmetic type.
9157   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9158 
9159   // Make sure that the something in !something is not bool.
9160   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9161   if (SubExpr->isKnownToHaveBooleanValue()) return;
9162 
9163   // Emit warning.
9164   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9165   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9166       << Loc << IsBitwiseOp;
9167 
9168   // First note suggest !(x < y)
9169   SourceLocation FirstOpen = SubExpr->getLocStart();
9170   SourceLocation FirstClose = RHS.get()->getLocEnd();
9171   FirstClose = S.getLocForEndOfToken(FirstClose);
9172   if (FirstClose.isInvalid())
9173     FirstOpen = SourceLocation();
9174   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9175       << IsBitwiseOp
9176       << FixItHint::CreateInsertion(FirstOpen, "(")
9177       << FixItHint::CreateInsertion(FirstClose, ")");
9178 
9179   // Second note suggests (!x) < y
9180   SourceLocation SecondOpen = LHS.get()->getLocStart();
9181   SourceLocation SecondClose = LHS.get()->getLocEnd();
9182   SecondClose = S.getLocForEndOfToken(SecondClose);
9183   if (SecondClose.isInvalid())
9184     SecondOpen = SourceLocation();
9185   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9186       << FixItHint::CreateInsertion(SecondOpen, "(")
9187       << FixItHint::CreateInsertion(SecondClose, ")");
9188 }
9189 
9190 // Get the decl for a simple expression: a reference to a variable,
9191 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9192 static ValueDecl *getCompareDecl(Expr *E) {
9193   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9194     return DR->getDecl();
9195   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9196     if (Ivar->isFreeIvar())
9197       return Ivar->getDecl();
9198   }
9199   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9200     if (Mem->isImplicitAccess())
9201       return Mem->getMemberDecl();
9202   }
9203   return nullptr;
9204 }
9205 
9206 // C99 6.5.8, C++ [expr.rel]
9207 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9208                                     SourceLocation Loc, BinaryOperatorKind Opc,
9209                                     bool IsRelational) {
9210   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9211 
9212   // Handle vector comparisons separately.
9213   if (LHS.get()->getType()->isVectorType() ||
9214       RHS.get()->getType()->isVectorType())
9215     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9216 
9217   QualType LHSType = LHS.get()->getType();
9218   QualType RHSType = RHS.get()->getType();
9219 
9220   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9221   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9222 
9223   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9224   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9225 
9226   if (!LHSType->hasFloatingRepresentation() &&
9227       !(LHSType->isBlockPointerType() && IsRelational) &&
9228       !LHS.get()->getLocStart().isMacroID() &&
9229       !RHS.get()->getLocStart().isMacroID() &&
9230       ActiveTemplateInstantiations.empty()) {
9231     // For non-floating point types, check for self-comparisons of the form
9232     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9233     // often indicate logic errors in the program.
9234     //
9235     // NOTE: Don't warn about comparison expressions resulting from macro
9236     // expansion. Also don't warn about comparisons which are only self
9237     // comparisons within a template specialization. The warnings should catch
9238     // obvious cases in the definition of the template anyways. The idea is to
9239     // warn when the typed comparison operator will always evaluate to the same
9240     // result.
9241     ValueDecl *DL = getCompareDecl(LHSStripped);
9242     ValueDecl *DR = getCompareDecl(RHSStripped);
9243     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9244       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9245                           << 0 // self-
9246                           << (Opc == BO_EQ
9247                               || Opc == BO_LE
9248                               || Opc == BO_GE));
9249     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9250                !DL->getType()->isReferenceType() &&
9251                !DR->getType()->isReferenceType()) {
9252         // what is it always going to eval to?
9253         char always_evals_to;
9254         switch(Opc) {
9255         case BO_EQ: // e.g. array1 == array2
9256           always_evals_to = 0; // false
9257           break;
9258         case BO_NE: // e.g. array1 != array2
9259           always_evals_to = 1; // true
9260           break;
9261         default:
9262           // best we can say is 'a constant'
9263           always_evals_to = 2; // e.g. array1 <= array2
9264           break;
9265         }
9266         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9267                             << 1 // array
9268                             << always_evals_to);
9269     }
9270 
9271     if (isa<CastExpr>(LHSStripped))
9272       LHSStripped = LHSStripped->IgnoreParenCasts();
9273     if (isa<CastExpr>(RHSStripped))
9274       RHSStripped = RHSStripped->IgnoreParenCasts();
9275 
9276     // Warn about comparisons against a string constant (unless the other
9277     // operand is null), the user probably wants strcmp.
9278     Expr *literalString = nullptr;
9279     Expr *literalStringStripped = nullptr;
9280     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9281         !RHSStripped->isNullPointerConstant(Context,
9282                                             Expr::NPC_ValueDependentIsNull)) {
9283       literalString = LHS.get();
9284       literalStringStripped = LHSStripped;
9285     } else if ((isa<StringLiteral>(RHSStripped) ||
9286                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9287                !LHSStripped->isNullPointerConstant(Context,
9288                                             Expr::NPC_ValueDependentIsNull)) {
9289       literalString = RHS.get();
9290       literalStringStripped = RHSStripped;
9291     }
9292 
9293     if (literalString) {
9294       DiagRuntimeBehavior(Loc, nullptr,
9295         PDiag(diag::warn_stringcompare)
9296           << isa<ObjCEncodeExpr>(literalStringStripped)
9297           << literalString->getSourceRange());
9298     }
9299   }
9300 
9301   // C99 6.5.8p3 / C99 6.5.9p4
9302   UsualArithmeticConversions(LHS, RHS);
9303   if (LHS.isInvalid() || RHS.isInvalid())
9304     return QualType();
9305 
9306   LHSType = LHS.get()->getType();
9307   RHSType = RHS.get()->getType();
9308 
9309   // The result of comparisons is 'bool' in C++, 'int' in C.
9310   QualType ResultTy = Context.getLogicalOperationType();
9311 
9312   if (IsRelational) {
9313     if (LHSType->isRealType() && RHSType->isRealType())
9314       return ResultTy;
9315   } else {
9316     // Check for comparisons of floating point operands using != and ==.
9317     if (LHSType->hasFloatingRepresentation())
9318       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9319 
9320     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9321       return ResultTy;
9322   }
9323 
9324   const Expr::NullPointerConstantKind LHSNullKind =
9325       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9326   const Expr::NullPointerConstantKind RHSNullKind =
9327       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9328   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9329   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9330 
9331   if (!IsRelational && LHSIsNull != RHSIsNull) {
9332     bool IsEquality = Opc == BO_EQ;
9333     if (RHSIsNull)
9334       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9335                                    RHS.get()->getSourceRange());
9336     else
9337       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9338                                    LHS.get()->getSourceRange());
9339   }
9340 
9341   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9342       (RHSType->isIntegerType() && !RHSIsNull)) {
9343     // Skip normal pointer conversion checks in this case; we have better
9344     // diagnostics for this below.
9345   } else if (getLangOpts().CPlusPlus) {
9346     // Equality comparison of a function pointer to a void pointer is invalid,
9347     // but we allow it as an extension.
9348     // FIXME: If we really want to allow this, should it be part of composite
9349     // pointer type computation so it works in conditionals too?
9350     if (!IsRelational &&
9351         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9352          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9353       // This is a gcc extension compatibility comparison.
9354       // In a SFINAE context, we treat this as a hard error to maintain
9355       // conformance with the C++ standard.
9356       diagnoseFunctionPointerToVoidComparison(
9357           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9358 
9359       if (isSFINAEContext())
9360         return QualType();
9361 
9362       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9363       return ResultTy;
9364     }
9365 
9366     // C++ [expr.eq]p2:
9367     //   If at least one operand is a pointer [...] bring them to their
9368     //   composite pointer type.
9369     // C++ [expr.rel]p2:
9370     //   If both operands are pointers, [...] bring them to their composite
9371     //   pointer type.
9372     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9373         (IsRelational ? 2 : 1)) {
9374       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9375         return QualType();
9376       else
9377         return ResultTy;
9378     }
9379   } else if (LHSType->isPointerType() &&
9380              RHSType->isPointerType()) { // C99 6.5.8p2
9381     // All of the following pointer-related warnings are GCC extensions, except
9382     // when handling null pointer constants.
9383     QualType LCanPointeeTy =
9384       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9385     QualType RCanPointeeTy =
9386       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9387 
9388     // C99 6.5.9p2 and C99 6.5.8p2
9389     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9390                                    RCanPointeeTy.getUnqualifiedType())) {
9391       // Valid unless a relational comparison of function pointers
9392       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9393         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9394           << LHSType << RHSType << LHS.get()->getSourceRange()
9395           << RHS.get()->getSourceRange();
9396       }
9397     } else if (!IsRelational &&
9398                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9399       // Valid unless comparison between non-null pointer and function pointer
9400       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9401           && !LHSIsNull && !RHSIsNull)
9402         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9403                                                 /*isError*/false);
9404     } else {
9405       // Invalid
9406       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9407     }
9408     if (LCanPointeeTy != RCanPointeeTy) {
9409       // Treat NULL constant as a special case in OpenCL.
9410       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9411         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9412         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9413           Diag(Loc,
9414                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9415               << LHSType << RHSType << 0 /* comparison */
9416               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9417         }
9418       }
9419       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9420       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9421       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9422                                                : CK_BitCast;
9423       if (LHSIsNull && !RHSIsNull)
9424         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9425       else
9426         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9427     }
9428     return ResultTy;
9429   }
9430 
9431   if (getLangOpts().CPlusPlus) {
9432     // C++ [expr.eq]p4:
9433     //   Two operands of type std::nullptr_t or one operand of type
9434     //   std::nullptr_t and the other a null pointer constant compare equal.
9435     if (!IsRelational && LHSIsNull && RHSIsNull) {
9436       if (LHSType->isNullPtrType()) {
9437         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9438         return ResultTy;
9439       }
9440       if (RHSType->isNullPtrType()) {
9441         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9442         return ResultTy;
9443       }
9444     }
9445 
9446     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9447     // These aren't covered by the composite pointer type rules.
9448     if (!IsRelational && RHSType->isNullPtrType() &&
9449         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9450       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9451       return ResultTy;
9452     }
9453     if (!IsRelational && LHSType->isNullPtrType() &&
9454         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9455       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9456       return ResultTy;
9457     }
9458 
9459     if (IsRelational &&
9460         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9461          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9462       // HACK: Relational comparison of nullptr_t against a pointer type is
9463       // invalid per DR583, but we allow it within std::less<> and friends,
9464       // since otherwise common uses of it break.
9465       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9466       // friends to have std::nullptr_t overload candidates.
9467       DeclContext *DC = CurContext;
9468       if (isa<FunctionDecl>(DC))
9469         DC = DC->getParent();
9470       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9471         if (CTSD->isInStdNamespace() &&
9472             llvm::StringSwitch<bool>(CTSD->getName())
9473                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9474                 .Default(false)) {
9475           if (RHSType->isNullPtrType())
9476             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9477           else
9478             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9479           return ResultTy;
9480         }
9481       }
9482     }
9483 
9484     // C++ [expr.eq]p2:
9485     //   If at least one operand is a pointer to member, [...] bring them to
9486     //   their composite pointer type.
9487     if (!IsRelational &&
9488         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9489       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9490         return QualType();
9491       else
9492         return ResultTy;
9493     }
9494 
9495     // Handle scoped enumeration types specifically, since they don't promote
9496     // to integers.
9497     if (LHS.get()->getType()->isEnumeralType() &&
9498         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9499                                        RHS.get()->getType()))
9500       return ResultTy;
9501   }
9502 
9503   // Handle block pointer types.
9504   if (!IsRelational && LHSType->isBlockPointerType() &&
9505       RHSType->isBlockPointerType()) {
9506     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9507     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9508 
9509     if (!LHSIsNull && !RHSIsNull &&
9510         !Context.typesAreCompatible(lpointee, rpointee)) {
9511       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9512         << LHSType << RHSType << LHS.get()->getSourceRange()
9513         << RHS.get()->getSourceRange();
9514     }
9515     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9516     return ResultTy;
9517   }
9518 
9519   // Allow block pointers to be compared with null pointer constants.
9520   if (!IsRelational
9521       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9522           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9523     if (!LHSIsNull && !RHSIsNull) {
9524       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9525              ->getPointeeType()->isVoidType())
9526             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9527                 ->getPointeeType()->isVoidType())))
9528         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9529           << LHSType << RHSType << LHS.get()->getSourceRange()
9530           << RHS.get()->getSourceRange();
9531     }
9532     if (LHSIsNull && !RHSIsNull)
9533       LHS = ImpCastExprToType(LHS.get(), RHSType,
9534                               RHSType->isPointerType() ? CK_BitCast
9535                                 : CK_AnyPointerToBlockPointerCast);
9536     else
9537       RHS = ImpCastExprToType(RHS.get(), LHSType,
9538                               LHSType->isPointerType() ? CK_BitCast
9539                                 : CK_AnyPointerToBlockPointerCast);
9540     return ResultTy;
9541   }
9542 
9543   if (LHSType->isObjCObjectPointerType() ||
9544       RHSType->isObjCObjectPointerType()) {
9545     const PointerType *LPT = LHSType->getAs<PointerType>();
9546     const PointerType *RPT = RHSType->getAs<PointerType>();
9547     if (LPT || RPT) {
9548       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9549       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9550 
9551       if (!LPtrToVoid && !RPtrToVoid &&
9552           !Context.typesAreCompatible(LHSType, RHSType)) {
9553         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9554                                           /*isError*/false);
9555       }
9556       if (LHSIsNull && !RHSIsNull) {
9557         Expr *E = LHS.get();
9558         if (getLangOpts().ObjCAutoRefCount)
9559           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9560         LHS = ImpCastExprToType(E, RHSType,
9561                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9562       }
9563       else {
9564         Expr *E = RHS.get();
9565         if (getLangOpts().ObjCAutoRefCount)
9566           CheckObjCARCConversion(SourceRange(), LHSType, E,
9567                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9568                                  /*DiagnoseCFAudited=*/false, Opc);
9569         RHS = ImpCastExprToType(E, LHSType,
9570                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9571       }
9572       return ResultTy;
9573     }
9574     if (LHSType->isObjCObjectPointerType() &&
9575         RHSType->isObjCObjectPointerType()) {
9576       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9577         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9578                                           /*isError*/false);
9579       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9580         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9581 
9582       if (LHSIsNull && !RHSIsNull)
9583         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9584       else
9585         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9586       return ResultTy;
9587     }
9588   }
9589   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9590       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9591     unsigned DiagID = 0;
9592     bool isError = false;
9593     if (LangOpts.DebuggerSupport) {
9594       // Under a debugger, allow the comparison of pointers to integers,
9595       // since users tend to want to compare addresses.
9596     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9597                (RHSIsNull && RHSType->isIntegerType())) {
9598       if (IsRelational) {
9599         isError = getLangOpts().CPlusPlus;
9600         DiagID =
9601           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9602                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9603       }
9604     } else if (getLangOpts().CPlusPlus) {
9605       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9606       isError = true;
9607     } else if (IsRelational)
9608       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9609     else
9610       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9611 
9612     if (DiagID) {
9613       Diag(Loc, DiagID)
9614         << LHSType << RHSType << LHS.get()->getSourceRange()
9615         << RHS.get()->getSourceRange();
9616       if (isError)
9617         return QualType();
9618     }
9619 
9620     if (LHSType->isIntegerType())
9621       LHS = ImpCastExprToType(LHS.get(), RHSType,
9622                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9623     else
9624       RHS = ImpCastExprToType(RHS.get(), LHSType,
9625                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9626     return ResultTy;
9627   }
9628 
9629   // Handle block pointers.
9630   if (!IsRelational && RHSIsNull
9631       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9632     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9633     return ResultTy;
9634   }
9635   if (!IsRelational && LHSIsNull
9636       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9637     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9638     return ResultTy;
9639   }
9640 
9641   if (getLangOpts().OpenCLVersion >= 200) {
9642     if (LHSIsNull && RHSType->isQueueT()) {
9643       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9644       return ResultTy;
9645     }
9646 
9647     if (LHSType->isQueueT() && RHSIsNull) {
9648       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9649       return ResultTy;
9650     }
9651   }
9652 
9653   return InvalidOperands(Loc, LHS, RHS);
9654 }
9655 
9656 
9657 // Return a signed type that is of identical size and number of elements.
9658 // For floating point vectors, return an integer type of identical size
9659 // and number of elements.
9660 QualType Sema::GetSignedVectorType(QualType V) {
9661   const VectorType *VTy = V->getAs<VectorType>();
9662   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9663   if (TypeSize == Context.getTypeSize(Context.CharTy))
9664     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9665   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9666     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9667   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9668     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9669   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9670     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9671   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9672          "Unhandled vector element size in vector compare");
9673   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9674 }
9675 
9676 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9677 /// operates on extended vector types.  Instead of producing an IntTy result,
9678 /// like a scalar comparison, a vector comparison produces a vector of integer
9679 /// types.
9680 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9681                                           SourceLocation Loc,
9682                                           bool IsRelational) {
9683   // Check to make sure we're operating on vectors of the same type and width,
9684   // Allowing one side to be a scalar of element type.
9685   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9686                               /*AllowBothBool*/true,
9687                               /*AllowBoolConversions*/getLangOpts().ZVector);
9688   if (vType.isNull())
9689     return vType;
9690 
9691   QualType LHSType = LHS.get()->getType();
9692 
9693   // If AltiVec, the comparison results in a numeric type, i.e.
9694   // bool for C++, int for C
9695   if (getLangOpts().AltiVec &&
9696       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9697     return Context.getLogicalOperationType();
9698 
9699   // For non-floating point types, check for self-comparisons of the form
9700   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9701   // often indicate logic errors in the program.
9702   if (!LHSType->hasFloatingRepresentation() &&
9703       ActiveTemplateInstantiations.empty()) {
9704     if (DeclRefExpr* DRL
9705           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9706       if (DeclRefExpr* DRR
9707             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9708         if (DRL->getDecl() == DRR->getDecl())
9709           DiagRuntimeBehavior(Loc, nullptr,
9710                               PDiag(diag::warn_comparison_always)
9711                                 << 0 // self-
9712                                 << 2 // "a constant"
9713                               );
9714   }
9715 
9716   // Check for comparisons of floating point operands using != and ==.
9717   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9718     assert (RHS.get()->getType()->hasFloatingRepresentation());
9719     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9720   }
9721 
9722   // Return a signed type for the vector.
9723   return GetSignedVectorType(vType);
9724 }
9725 
9726 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9727                                           SourceLocation Loc) {
9728   // Ensure that either both operands are of the same vector type, or
9729   // one operand is of a vector type and the other is of its element type.
9730   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9731                                        /*AllowBothBool*/true,
9732                                        /*AllowBoolConversions*/false);
9733   if (vType.isNull())
9734     return InvalidOperands(Loc, LHS, RHS);
9735   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9736       vType->hasFloatingRepresentation())
9737     return InvalidOperands(Loc, LHS, RHS);
9738 
9739   return GetSignedVectorType(LHS.get()->getType());
9740 }
9741 
9742 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9743                                            SourceLocation Loc,
9744                                            BinaryOperatorKind Opc) {
9745   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9746 
9747   bool IsCompAssign =
9748       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9749 
9750   if (LHS.get()->getType()->isVectorType() ||
9751       RHS.get()->getType()->isVectorType()) {
9752     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9753         RHS.get()->getType()->hasIntegerRepresentation())
9754       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9755                         /*AllowBothBool*/true,
9756                         /*AllowBoolConversions*/getLangOpts().ZVector);
9757     return InvalidOperands(Loc, LHS, RHS);
9758   }
9759 
9760   if (Opc == BO_And)
9761     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9762 
9763   ExprResult LHSResult = LHS, RHSResult = RHS;
9764   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9765                                                  IsCompAssign);
9766   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9767     return QualType();
9768   LHS = LHSResult.get();
9769   RHS = RHSResult.get();
9770 
9771   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9772     return compType;
9773   return InvalidOperands(Loc, LHS, RHS);
9774 }
9775 
9776 // C99 6.5.[13,14]
9777 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9778                                            SourceLocation Loc,
9779                                            BinaryOperatorKind Opc) {
9780   // Check vector operands differently.
9781   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9782     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9783 
9784   // Diagnose cases where the user write a logical and/or but probably meant a
9785   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9786   // is a constant.
9787   if (LHS.get()->getType()->isIntegerType() &&
9788       !LHS.get()->getType()->isBooleanType() &&
9789       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9790       // Don't warn in macros or template instantiations.
9791       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9792     // If the RHS can be constant folded, and if it constant folds to something
9793     // that isn't 0 or 1 (which indicate a potential logical operation that
9794     // happened to fold to true/false) then warn.
9795     // Parens on the RHS are ignored.
9796     llvm::APSInt Result;
9797     if (RHS.get()->EvaluateAsInt(Result, Context))
9798       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9799            !RHS.get()->getExprLoc().isMacroID()) ||
9800           (Result != 0 && Result != 1)) {
9801         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9802           << RHS.get()->getSourceRange()
9803           << (Opc == BO_LAnd ? "&&" : "||");
9804         // Suggest replacing the logical operator with the bitwise version
9805         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9806             << (Opc == BO_LAnd ? "&" : "|")
9807             << FixItHint::CreateReplacement(SourceRange(
9808                                                  Loc, getLocForEndOfToken(Loc)),
9809                                             Opc == BO_LAnd ? "&" : "|");
9810         if (Opc == BO_LAnd)
9811           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9812           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9813               << FixItHint::CreateRemoval(
9814                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9815                               RHS.get()->getLocEnd()));
9816       }
9817   }
9818 
9819   if (!Context.getLangOpts().CPlusPlus) {
9820     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9821     // not operate on the built-in scalar and vector float types.
9822     if (Context.getLangOpts().OpenCL &&
9823         Context.getLangOpts().OpenCLVersion < 120) {
9824       if (LHS.get()->getType()->isFloatingType() ||
9825           RHS.get()->getType()->isFloatingType())
9826         return InvalidOperands(Loc, LHS, RHS);
9827     }
9828 
9829     LHS = UsualUnaryConversions(LHS.get());
9830     if (LHS.isInvalid())
9831       return QualType();
9832 
9833     RHS = UsualUnaryConversions(RHS.get());
9834     if (RHS.isInvalid())
9835       return QualType();
9836 
9837     if (!LHS.get()->getType()->isScalarType() ||
9838         !RHS.get()->getType()->isScalarType())
9839       return InvalidOperands(Loc, LHS, RHS);
9840 
9841     return Context.IntTy;
9842   }
9843 
9844   // The following is safe because we only use this method for
9845   // non-overloadable operands.
9846 
9847   // C++ [expr.log.and]p1
9848   // C++ [expr.log.or]p1
9849   // The operands are both contextually converted to type bool.
9850   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9851   if (LHSRes.isInvalid())
9852     return InvalidOperands(Loc, LHS, RHS);
9853   LHS = LHSRes;
9854 
9855   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9856   if (RHSRes.isInvalid())
9857     return InvalidOperands(Loc, LHS, RHS);
9858   RHS = RHSRes;
9859 
9860   // C++ [expr.log.and]p2
9861   // C++ [expr.log.or]p2
9862   // The result is a bool.
9863   return Context.BoolTy;
9864 }
9865 
9866 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9867   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9868   if (!ME) return false;
9869   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9870   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9871       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9872   if (!Base) return false;
9873   return Base->getMethodDecl() != nullptr;
9874 }
9875 
9876 /// Is the given expression (which must be 'const') a reference to a
9877 /// variable which was originally non-const, but which has become
9878 /// 'const' due to being captured within a block?
9879 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9880 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9881   assert(E->isLValue() && E->getType().isConstQualified());
9882   E = E->IgnoreParens();
9883 
9884   // Must be a reference to a declaration from an enclosing scope.
9885   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9886   if (!DRE) return NCCK_None;
9887   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9888 
9889   // The declaration must be a variable which is not declared 'const'.
9890   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9891   if (!var) return NCCK_None;
9892   if (var->getType().isConstQualified()) return NCCK_None;
9893   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9894 
9895   // Decide whether the first capture was for a block or a lambda.
9896   DeclContext *DC = S.CurContext, *Prev = nullptr;
9897   // Decide whether the first capture was for a block or a lambda.
9898   while (DC) {
9899     // For init-capture, it is possible that the variable belongs to the
9900     // template pattern of the current context.
9901     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9902       if (var->isInitCapture() &&
9903           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9904         break;
9905     if (DC == var->getDeclContext())
9906       break;
9907     Prev = DC;
9908     DC = DC->getParent();
9909   }
9910   // Unless we have an init-capture, we've gone one step too far.
9911   if (!var->isInitCapture())
9912     DC = Prev;
9913   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9914 }
9915 
9916 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9917   Ty = Ty.getNonReferenceType();
9918   if (IsDereference && Ty->isPointerType())
9919     Ty = Ty->getPointeeType();
9920   return !Ty.isConstQualified();
9921 }
9922 
9923 /// Emit the "read-only variable not assignable" error and print notes to give
9924 /// more information about why the variable is not assignable, such as pointing
9925 /// to the declaration of a const variable, showing that a method is const, or
9926 /// that the function is returning a const reference.
9927 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9928                                     SourceLocation Loc) {
9929   // Update err_typecheck_assign_const and note_typecheck_assign_const
9930   // when this enum is changed.
9931   enum {
9932     ConstFunction,
9933     ConstVariable,
9934     ConstMember,
9935     ConstMethod,
9936     ConstUnknown,  // Keep as last element
9937   };
9938 
9939   SourceRange ExprRange = E->getSourceRange();
9940 
9941   // Only emit one error on the first const found.  All other consts will emit
9942   // a note to the error.
9943   bool DiagnosticEmitted = false;
9944 
9945   // Track if the current expression is the result of a dereference, and if the
9946   // next checked expression is the result of a dereference.
9947   bool IsDereference = false;
9948   bool NextIsDereference = false;
9949 
9950   // Loop to process MemberExpr chains.
9951   while (true) {
9952     IsDereference = NextIsDereference;
9953 
9954     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9955     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9956       NextIsDereference = ME->isArrow();
9957       const ValueDecl *VD = ME->getMemberDecl();
9958       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9959         // Mutable fields can be modified even if the class is const.
9960         if (Field->isMutable()) {
9961           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9962           break;
9963         }
9964 
9965         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9966           if (!DiagnosticEmitted) {
9967             S.Diag(Loc, diag::err_typecheck_assign_const)
9968                 << ExprRange << ConstMember << false /*static*/ << Field
9969                 << Field->getType();
9970             DiagnosticEmitted = true;
9971           }
9972           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9973               << ConstMember << false /*static*/ << Field << Field->getType()
9974               << Field->getSourceRange();
9975         }
9976         E = ME->getBase();
9977         continue;
9978       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9979         if (VDecl->getType().isConstQualified()) {
9980           if (!DiagnosticEmitted) {
9981             S.Diag(Loc, diag::err_typecheck_assign_const)
9982                 << ExprRange << ConstMember << true /*static*/ << VDecl
9983                 << VDecl->getType();
9984             DiagnosticEmitted = true;
9985           }
9986           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9987               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9988               << VDecl->getSourceRange();
9989         }
9990         // Static fields do not inherit constness from parents.
9991         break;
9992       }
9993       break;
9994     } // End MemberExpr
9995     break;
9996   }
9997 
9998   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9999     // Function calls
10000     const FunctionDecl *FD = CE->getDirectCallee();
10001     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10002       if (!DiagnosticEmitted) {
10003         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10004                                                       << ConstFunction << FD;
10005         DiagnosticEmitted = true;
10006       }
10007       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10008              diag::note_typecheck_assign_const)
10009           << ConstFunction << FD << FD->getReturnType()
10010           << FD->getReturnTypeSourceRange();
10011     }
10012   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10013     // Point to variable declaration.
10014     if (const ValueDecl *VD = DRE->getDecl()) {
10015       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10016         if (!DiagnosticEmitted) {
10017           S.Diag(Loc, diag::err_typecheck_assign_const)
10018               << ExprRange << ConstVariable << VD << VD->getType();
10019           DiagnosticEmitted = true;
10020         }
10021         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10022             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10023       }
10024     }
10025   } else if (isa<CXXThisExpr>(E)) {
10026     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10027       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10028         if (MD->isConst()) {
10029           if (!DiagnosticEmitted) {
10030             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10031                                                           << ConstMethod << MD;
10032             DiagnosticEmitted = true;
10033           }
10034           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10035               << ConstMethod << MD << MD->getSourceRange();
10036         }
10037       }
10038     }
10039   }
10040 
10041   if (DiagnosticEmitted)
10042     return;
10043 
10044   // Can't determine a more specific message, so display the generic error.
10045   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10046 }
10047 
10048 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10049 /// emit an error and return true.  If so, return false.
10050 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10051   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10052 
10053   S.CheckShadowingDeclModification(E, Loc);
10054 
10055   SourceLocation OrigLoc = Loc;
10056   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10057                                                               &Loc);
10058   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10059     IsLV = Expr::MLV_InvalidMessageExpression;
10060   if (IsLV == Expr::MLV_Valid)
10061     return false;
10062 
10063   unsigned DiagID = 0;
10064   bool NeedType = false;
10065   switch (IsLV) { // C99 6.5.16p2
10066   case Expr::MLV_ConstQualified:
10067     // Use a specialized diagnostic when we're assigning to an object
10068     // from an enclosing function or block.
10069     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10070       if (NCCK == NCCK_Block)
10071         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10072       else
10073         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10074       break;
10075     }
10076 
10077     // In ARC, use some specialized diagnostics for occasions where we
10078     // infer 'const'.  These are always pseudo-strong variables.
10079     if (S.getLangOpts().ObjCAutoRefCount) {
10080       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10081       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10082         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10083 
10084         // Use the normal diagnostic if it's pseudo-__strong but the
10085         // user actually wrote 'const'.
10086         if (var->isARCPseudoStrong() &&
10087             (!var->getTypeSourceInfo() ||
10088              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10089           // There are two pseudo-strong cases:
10090           //  - self
10091           ObjCMethodDecl *method = S.getCurMethodDecl();
10092           if (method && var == method->getSelfDecl())
10093             DiagID = method->isClassMethod()
10094               ? diag::err_typecheck_arc_assign_self_class_method
10095               : diag::err_typecheck_arc_assign_self;
10096 
10097           //  - fast enumeration variables
10098           else
10099             DiagID = diag::err_typecheck_arr_assign_enumeration;
10100 
10101           SourceRange Assign;
10102           if (Loc != OrigLoc)
10103             Assign = SourceRange(OrigLoc, OrigLoc);
10104           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10105           // We need to preserve the AST regardless, so migration tool
10106           // can do its job.
10107           return false;
10108         }
10109       }
10110     }
10111 
10112     // If none of the special cases above are triggered, then this is a
10113     // simple const assignment.
10114     if (DiagID == 0) {
10115       DiagnoseConstAssignment(S, E, Loc);
10116       return true;
10117     }
10118 
10119     break;
10120   case Expr::MLV_ConstAddrSpace:
10121     DiagnoseConstAssignment(S, E, Loc);
10122     return true;
10123   case Expr::MLV_ArrayType:
10124   case Expr::MLV_ArrayTemporary:
10125     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10126     NeedType = true;
10127     break;
10128   case Expr::MLV_NotObjectType:
10129     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10130     NeedType = true;
10131     break;
10132   case Expr::MLV_LValueCast:
10133     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10134     break;
10135   case Expr::MLV_Valid:
10136     llvm_unreachable("did not take early return for MLV_Valid");
10137   case Expr::MLV_InvalidExpression:
10138   case Expr::MLV_MemberFunction:
10139   case Expr::MLV_ClassTemporary:
10140     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10141     break;
10142   case Expr::MLV_IncompleteType:
10143   case Expr::MLV_IncompleteVoidType:
10144     return S.RequireCompleteType(Loc, E->getType(),
10145              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10146   case Expr::MLV_DuplicateVectorComponents:
10147     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10148     break;
10149   case Expr::MLV_NoSetterProperty:
10150     llvm_unreachable("readonly properties should be processed differently");
10151   case Expr::MLV_InvalidMessageExpression:
10152     DiagID = diag::err_readonly_message_assignment;
10153     break;
10154   case Expr::MLV_SubObjCPropertySetting:
10155     DiagID = diag::err_no_subobject_property_setting;
10156     break;
10157   }
10158 
10159   SourceRange Assign;
10160   if (Loc != OrigLoc)
10161     Assign = SourceRange(OrigLoc, OrigLoc);
10162   if (NeedType)
10163     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10164   else
10165     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10166   return true;
10167 }
10168 
10169 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10170                                          SourceLocation Loc,
10171                                          Sema &Sema) {
10172   // C / C++ fields
10173   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10174   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10175   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10176     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10177       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10178   }
10179 
10180   // Objective-C instance variables
10181   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10182   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10183   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10184     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10185     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10186     if (RL && RR && RL->getDecl() == RR->getDecl())
10187       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10188   }
10189 }
10190 
10191 // C99 6.5.16.1
10192 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10193                                        SourceLocation Loc,
10194                                        QualType CompoundType) {
10195   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10196 
10197   // Verify that LHS is a modifiable lvalue, and emit error if not.
10198   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10199     return QualType();
10200 
10201   QualType LHSType = LHSExpr->getType();
10202   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10203                                              CompoundType;
10204   // OpenCL v1.2 s6.1.1.1 p2:
10205   // The half data type can only be used to declare a pointer to a buffer that
10206   // contains half values
10207   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10208     LHSType->isHalfType()) {
10209     Diag(Loc, diag::err_opencl_half_load_store) << 1
10210         << LHSType.getUnqualifiedType();
10211     return QualType();
10212   }
10213 
10214   AssignConvertType ConvTy;
10215   if (CompoundType.isNull()) {
10216     Expr *RHSCheck = RHS.get();
10217 
10218     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10219 
10220     QualType LHSTy(LHSType);
10221     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10222     if (RHS.isInvalid())
10223       return QualType();
10224     // Special case of NSObject attributes on c-style pointer types.
10225     if (ConvTy == IncompatiblePointer &&
10226         ((Context.isObjCNSObjectType(LHSType) &&
10227           RHSType->isObjCObjectPointerType()) ||
10228          (Context.isObjCNSObjectType(RHSType) &&
10229           LHSType->isObjCObjectPointerType())))
10230       ConvTy = Compatible;
10231 
10232     if (ConvTy == Compatible &&
10233         LHSType->isObjCObjectType())
10234         Diag(Loc, diag::err_objc_object_assignment)
10235           << LHSType;
10236 
10237     // If the RHS is a unary plus or minus, check to see if they = and + are
10238     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10239     // instead of "x += 4".
10240     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10241       RHSCheck = ICE->getSubExpr();
10242     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10243       if ((UO->getOpcode() == UO_Plus ||
10244            UO->getOpcode() == UO_Minus) &&
10245           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10246           // Only if the two operators are exactly adjacent.
10247           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10248           // And there is a space or other character before the subexpr of the
10249           // unary +/-.  We don't want to warn on "x=-1".
10250           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10251           UO->getSubExpr()->getLocStart().isFileID()) {
10252         Diag(Loc, diag::warn_not_compound_assign)
10253           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10254           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10255       }
10256     }
10257 
10258     if (ConvTy == Compatible) {
10259       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10260         // Warn about retain cycles where a block captures the LHS, but
10261         // not if the LHS is a simple variable into which the block is
10262         // being stored...unless that variable can be captured by reference!
10263         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10264         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10265         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10266           checkRetainCycles(LHSExpr, RHS.get());
10267 
10268         // It is safe to assign a weak reference into a strong variable.
10269         // Although this code can still have problems:
10270         //   id x = self.weakProp;
10271         //   id y = self.weakProp;
10272         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10273         // paths through the function. This should be revisited if
10274         // -Wrepeated-use-of-weak is made flow-sensitive.
10275         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10276                              RHS.get()->getLocStart()))
10277           getCurFunction()->markSafeWeakUse(RHS.get());
10278 
10279       } else if (getLangOpts().ObjCAutoRefCount) {
10280         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10281       }
10282     }
10283   } else {
10284     // Compound assignment "x += y"
10285     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10286   }
10287 
10288   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10289                                RHS.get(), AA_Assigning))
10290     return QualType();
10291 
10292   CheckForNullPointerDereference(*this, LHSExpr);
10293 
10294   // C99 6.5.16p3: The type of an assignment expression is the type of the
10295   // left operand unless the left operand has qualified type, in which case
10296   // it is the unqualified version of the type of the left operand.
10297   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10298   // is converted to the type of the assignment expression (above).
10299   // C++ 5.17p1: the type of the assignment expression is that of its left
10300   // operand.
10301   return (getLangOpts().CPlusPlus
10302           ? LHSType : LHSType.getUnqualifiedType());
10303 }
10304 
10305 // Only ignore explicit casts to void.
10306 static bool IgnoreCommaOperand(const Expr *E) {
10307   E = E->IgnoreParens();
10308 
10309   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10310     if (CE->getCastKind() == CK_ToVoid) {
10311       return true;
10312     }
10313   }
10314 
10315   return false;
10316 }
10317 
10318 // Look for instances where it is likely the comma operator is confused with
10319 // another operator.  There is a whitelist of acceptable expressions for the
10320 // left hand side of the comma operator, otherwise emit a warning.
10321 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10322   // No warnings in macros
10323   if (Loc.isMacroID())
10324     return;
10325 
10326   // Don't warn in template instantiations.
10327   if (!ActiveTemplateInstantiations.empty())
10328     return;
10329 
10330   // Scope isn't fine-grained enough to whitelist the specific cases, so
10331   // instead, skip more than needed, then call back into here with the
10332   // CommaVisitor in SemaStmt.cpp.
10333   // The whitelisted locations are the initialization and increment portions
10334   // of a for loop.  The additional checks are on the condition of
10335   // if statements, do/while loops, and for loops.
10336   const unsigned ForIncrementFlags =
10337       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10338   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10339   const unsigned ScopeFlags = getCurScope()->getFlags();
10340   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10341       (ScopeFlags & ForInitFlags) == ForInitFlags)
10342     return;
10343 
10344   // If there are multiple comma operators used together, get the RHS of the
10345   // of the comma operator as the LHS.
10346   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10347     if (BO->getOpcode() != BO_Comma)
10348       break;
10349     LHS = BO->getRHS();
10350   }
10351 
10352   // Only allow some expressions on LHS to not warn.
10353   if (IgnoreCommaOperand(LHS))
10354     return;
10355 
10356   Diag(Loc, diag::warn_comma_operator);
10357   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10358       << LHS->getSourceRange()
10359       << FixItHint::CreateInsertion(LHS->getLocStart(),
10360                                     LangOpts.CPlusPlus ? "static_cast<void>("
10361                                                        : "(void)(")
10362       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10363                                     ")");
10364 }
10365 
10366 // C99 6.5.17
10367 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10368                                    SourceLocation Loc) {
10369   LHS = S.CheckPlaceholderExpr(LHS.get());
10370   RHS = S.CheckPlaceholderExpr(RHS.get());
10371   if (LHS.isInvalid() || RHS.isInvalid())
10372     return QualType();
10373 
10374   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10375   // operands, but not unary promotions.
10376   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10377 
10378   // So we treat the LHS as a ignored value, and in C++ we allow the
10379   // containing site to determine what should be done with the RHS.
10380   LHS = S.IgnoredValueConversions(LHS.get());
10381   if (LHS.isInvalid())
10382     return QualType();
10383 
10384   S.DiagnoseUnusedExprResult(LHS.get());
10385 
10386   if (!S.getLangOpts().CPlusPlus) {
10387     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10388     if (RHS.isInvalid())
10389       return QualType();
10390     if (!RHS.get()->getType()->isVoidType())
10391       S.RequireCompleteType(Loc, RHS.get()->getType(),
10392                             diag::err_incomplete_type);
10393   }
10394 
10395   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10396     S.DiagnoseCommaOperator(LHS.get(), Loc);
10397 
10398   return RHS.get()->getType();
10399 }
10400 
10401 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10402 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10403 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10404                                                ExprValueKind &VK,
10405                                                ExprObjectKind &OK,
10406                                                SourceLocation OpLoc,
10407                                                bool IsInc, bool IsPrefix) {
10408   if (Op->isTypeDependent())
10409     return S.Context.DependentTy;
10410 
10411   QualType ResType = Op->getType();
10412   // Atomic types can be used for increment / decrement where the non-atomic
10413   // versions can, so ignore the _Atomic() specifier for the purpose of
10414   // checking.
10415   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10416     ResType = ResAtomicType->getValueType();
10417 
10418   assert(!ResType.isNull() && "no type for increment/decrement expression");
10419 
10420   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10421     // Decrement of bool is not allowed.
10422     if (!IsInc) {
10423       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10424       return QualType();
10425     }
10426     // Increment of bool sets it to true, but is deprecated.
10427     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10428                                               : diag::warn_increment_bool)
10429       << Op->getSourceRange();
10430   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10431     // Error on enum increments and decrements in C++ mode
10432     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10433     return QualType();
10434   } else if (ResType->isRealType()) {
10435     // OK!
10436   } else if (ResType->isPointerType()) {
10437     // C99 6.5.2.4p2, 6.5.6p2
10438     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10439       return QualType();
10440   } else if (ResType->isObjCObjectPointerType()) {
10441     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10442     // Otherwise, we just need a complete type.
10443     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10444         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10445       return QualType();
10446   } else if (ResType->isAnyComplexType()) {
10447     // C99 does not support ++/-- on complex types, we allow as an extension.
10448     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10449       << ResType << Op->getSourceRange();
10450   } else if (ResType->isPlaceholderType()) {
10451     ExprResult PR = S.CheckPlaceholderExpr(Op);
10452     if (PR.isInvalid()) return QualType();
10453     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10454                                           IsInc, IsPrefix);
10455   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10456     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10457   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10458              (ResType->getAs<VectorType>()->getVectorKind() !=
10459               VectorType::AltiVecBool)) {
10460     // The z vector extensions allow ++ and -- for non-bool vectors.
10461   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10462             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10463     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10464   } else {
10465     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10466       << ResType << int(IsInc) << Op->getSourceRange();
10467     return QualType();
10468   }
10469   // At this point, we know we have a real, complex or pointer type.
10470   // Now make sure the operand is a modifiable lvalue.
10471   if (CheckForModifiableLvalue(Op, OpLoc, S))
10472     return QualType();
10473   // In C++, a prefix increment is the same type as the operand. Otherwise
10474   // (in C or with postfix), the increment is the unqualified type of the
10475   // operand.
10476   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10477     VK = VK_LValue;
10478     OK = Op->getObjectKind();
10479     return ResType;
10480   } else {
10481     VK = VK_RValue;
10482     return ResType.getUnqualifiedType();
10483   }
10484 }
10485 
10486 
10487 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10488 /// This routine allows us to typecheck complex/recursive expressions
10489 /// where the declaration is needed for type checking. We only need to
10490 /// handle cases when the expression references a function designator
10491 /// or is an lvalue. Here are some examples:
10492 ///  - &(x) => x
10493 ///  - &*****f => f for f a function designator.
10494 ///  - &s.xx => s
10495 ///  - &s.zz[1].yy -> s, if zz is an array
10496 ///  - *(x + 1) -> x, if x is an array
10497 ///  - &"123"[2] -> 0
10498 ///  - & __real__ x -> x
10499 static ValueDecl *getPrimaryDecl(Expr *E) {
10500   switch (E->getStmtClass()) {
10501   case Stmt::DeclRefExprClass:
10502     return cast<DeclRefExpr>(E)->getDecl();
10503   case Stmt::MemberExprClass:
10504     // If this is an arrow operator, the address is an offset from
10505     // the base's value, so the object the base refers to is
10506     // irrelevant.
10507     if (cast<MemberExpr>(E)->isArrow())
10508       return nullptr;
10509     // Otherwise, the expression refers to a part of the base
10510     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10511   case Stmt::ArraySubscriptExprClass: {
10512     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10513     // promotion of register arrays earlier.
10514     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10515     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10516       if (ICE->getSubExpr()->getType()->isArrayType())
10517         return getPrimaryDecl(ICE->getSubExpr());
10518     }
10519     return nullptr;
10520   }
10521   case Stmt::UnaryOperatorClass: {
10522     UnaryOperator *UO = cast<UnaryOperator>(E);
10523 
10524     switch(UO->getOpcode()) {
10525     case UO_Real:
10526     case UO_Imag:
10527     case UO_Extension:
10528       return getPrimaryDecl(UO->getSubExpr());
10529     default:
10530       return nullptr;
10531     }
10532   }
10533   case Stmt::ParenExprClass:
10534     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10535   case Stmt::ImplicitCastExprClass:
10536     // If the result of an implicit cast is an l-value, we care about
10537     // the sub-expression; otherwise, the result here doesn't matter.
10538     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10539   default:
10540     return nullptr;
10541   }
10542 }
10543 
10544 namespace {
10545   enum {
10546     AO_Bit_Field = 0,
10547     AO_Vector_Element = 1,
10548     AO_Property_Expansion = 2,
10549     AO_Register_Variable = 3,
10550     AO_No_Error = 4
10551   };
10552 }
10553 /// \brief Diagnose invalid operand for address of operations.
10554 ///
10555 /// \param Type The type of operand which cannot have its address taken.
10556 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10557                                          Expr *E, unsigned Type) {
10558   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10559 }
10560 
10561 /// CheckAddressOfOperand - The operand of & must be either a function
10562 /// designator or an lvalue designating an object. If it is an lvalue, the
10563 /// object cannot be declared with storage class register or be a bit field.
10564 /// Note: The usual conversions are *not* applied to the operand of the &
10565 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10566 /// In C++, the operand might be an overloaded function name, in which case
10567 /// we allow the '&' but retain the overloaded-function type.
10568 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10569   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10570     if (PTy->getKind() == BuiltinType::Overload) {
10571       Expr *E = OrigOp.get()->IgnoreParens();
10572       if (!isa<OverloadExpr>(E)) {
10573         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10574         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10575           << OrigOp.get()->getSourceRange();
10576         return QualType();
10577       }
10578 
10579       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10580       if (isa<UnresolvedMemberExpr>(Ovl))
10581         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10582           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10583             << OrigOp.get()->getSourceRange();
10584           return QualType();
10585         }
10586 
10587       return Context.OverloadTy;
10588     }
10589 
10590     if (PTy->getKind() == BuiltinType::UnknownAny)
10591       return Context.UnknownAnyTy;
10592 
10593     if (PTy->getKind() == BuiltinType::BoundMember) {
10594       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10595         << OrigOp.get()->getSourceRange();
10596       return QualType();
10597     }
10598 
10599     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10600     if (OrigOp.isInvalid()) return QualType();
10601   }
10602 
10603   if (OrigOp.get()->isTypeDependent())
10604     return Context.DependentTy;
10605 
10606   assert(!OrigOp.get()->getType()->isPlaceholderType());
10607 
10608   // Make sure to ignore parentheses in subsequent checks
10609   Expr *op = OrigOp.get()->IgnoreParens();
10610 
10611   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10612   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10613     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10614     return QualType();
10615   }
10616 
10617   if (getLangOpts().C99) {
10618     // Implement C99-only parts of addressof rules.
10619     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10620       if (uOp->getOpcode() == UO_Deref)
10621         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10622         // (assuming the deref expression is valid).
10623         return uOp->getSubExpr()->getType();
10624     }
10625     // Technically, there should be a check for array subscript
10626     // expressions here, but the result of one is always an lvalue anyway.
10627   }
10628   ValueDecl *dcl = getPrimaryDecl(op);
10629 
10630   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10631     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10632                                            op->getLocStart()))
10633       return QualType();
10634 
10635   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10636   unsigned AddressOfError = AO_No_Error;
10637 
10638   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10639     bool sfinae = (bool)isSFINAEContext();
10640     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10641                                   : diag::ext_typecheck_addrof_temporary)
10642       << op->getType() << op->getSourceRange();
10643     if (sfinae)
10644       return QualType();
10645     // Materialize the temporary as an lvalue so that we can take its address.
10646     OrigOp = op =
10647         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10648   } else if (isa<ObjCSelectorExpr>(op)) {
10649     return Context.getPointerType(op->getType());
10650   } else if (lval == Expr::LV_MemberFunction) {
10651     // If it's an instance method, make a member pointer.
10652     // The expression must have exactly the form &A::foo.
10653 
10654     // If the underlying expression isn't a decl ref, give up.
10655     if (!isa<DeclRefExpr>(op)) {
10656       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10657         << OrigOp.get()->getSourceRange();
10658       return QualType();
10659     }
10660     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10661     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10662 
10663     // The id-expression was parenthesized.
10664     if (OrigOp.get() != DRE) {
10665       Diag(OpLoc, diag::err_parens_pointer_member_function)
10666         << OrigOp.get()->getSourceRange();
10667 
10668     // The method was named without a qualifier.
10669     } else if (!DRE->getQualifier()) {
10670       if (MD->getParent()->getName().empty())
10671         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10672           << op->getSourceRange();
10673       else {
10674         SmallString<32> Str;
10675         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10676         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10677           << op->getSourceRange()
10678           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10679       }
10680     }
10681 
10682     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10683     if (isa<CXXDestructorDecl>(MD))
10684       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10685 
10686     QualType MPTy = Context.getMemberPointerType(
10687         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10688     // Under the MS ABI, lock down the inheritance model now.
10689     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10690       (void)isCompleteType(OpLoc, MPTy);
10691     return MPTy;
10692   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10693     // C99 6.5.3.2p1
10694     // The operand must be either an l-value or a function designator
10695     if (!op->getType()->isFunctionType()) {
10696       // Use a special diagnostic for loads from property references.
10697       if (isa<PseudoObjectExpr>(op)) {
10698         AddressOfError = AO_Property_Expansion;
10699       } else {
10700         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10701           << op->getType() << op->getSourceRange();
10702         return QualType();
10703       }
10704     }
10705   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10706     // The operand cannot be a bit-field
10707     AddressOfError = AO_Bit_Field;
10708   } else if (op->getObjectKind() == OK_VectorComponent) {
10709     // The operand cannot be an element of a vector
10710     AddressOfError = AO_Vector_Element;
10711   } else if (dcl) { // C99 6.5.3.2p1
10712     // We have an lvalue with a decl. Make sure the decl is not declared
10713     // with the register storage-class specifier.
10714     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10715       // in C++ it is not error to take address of a register
10716       // variable (c++03 7.1.1P3)
10717       if (vd->getStorageClass() == SC_Register &&
10718           !getLangOpts().CPlusPlus) {
10719         AddressOfError = AO_Register_Variable;
10720       }
10721     } else if (isa<MSPropertyDecl>(dcl)) {
10722       AddressOfError = AO_Property_Expansion;
10723     } else if (isa<FunctionTemplateDecl>(dcl)) {
10724       return Context.OverloadTy;
10725     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10726       // Okay: we can take the address of a field.
10727       // Could be a pointer to member, though, if there is an explicit
10728       // scope qualifier for the class.
10729       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10730         DeclContext *Ctx = dcl->getDeclContext();
10731         if (Ctx && Ctx->isRecord()) {
10732           if (dcl->getType()->isReferenceType()) {
10733             Diag(OpLoc,
10734                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10735               << dcl->getDeclName() << dcl->getType();
10736             return QualType();
10737           }
10738 
10739           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10740             Ctx = Ctx->getParent();
10741 
10742           QualType MPTy = Context.getMemberPointerType(
10743               op->getType(),
10744               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10745           // Under the MS ABI, lock down the inheritance model now.
10746           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10747             (void)isCompleteType(OpLoc, MPTy);
10748           return MPTy;
10749         }
10750       }
10751     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10752                !isa<BindingDecl>(dcl))
10753       llvm_unreachable("Unknown/unexpected decl type");
10754   }
10755 
10756   if (AddressOfError != AO_No_Error) {
10757     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10758     return QualType();
10759   }
10760 
10761   if (lval == Expr::LV_IncompleteVoidType) {
10762     // Taking the address of a void variable is technically illegal, but we
10763     // allow it in cases which are otherwise valid.
10764     // Example: "extern void x; void* y = &x;".
10765     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10766   }
10767 
10768   // If the operand has type "type", the result has type "pointer to type".
10769   if (op->getType()->isObjCObjectType())
10770     return Context.getObjCObjectPointerType(op->getType());
10771 
10772   CheckAddressOfPackedMember(op);
10773 
10774   return Context.getPointerType(op->getType());
10775 }
10776 
10777 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10778   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10779   if (!DRE)
10780     return;
10781   const Decl *D = DRE->getDecl();
10782   if (!D)
10783     return;
10784   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10785   if (!Param)
10786     return;
10787   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10788     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10789       return;
10790   if (FunctionScopeInfo *FD = S.getCurFunction())
10791     if (!FD->ModifiedNonNullParams.count(Param))
10792       FD->ModifiedNonNullParams.insert(Param);
10793 }
10794 
10795 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10796 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10797                                         SourceLocation OpLoc) {
10798   if (Op->isTypeDependent())
10799     return S.Context.DependentTy;
10800 
10801   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10802   if (ConvResult.isInvalid())
10803     return QualType();
10804   Op = ConvResult.get();
10805   QualType OpTy = Op->getType();
10806   QualType Result;
10807 
10808   if (isa<CXXReinterpretCastExpr>(Op)) {
10809     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10810     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10811                                      Op->getSourceRange());
10812   }
10813 
10814   if (const PointerType *PT = OpTy->getAs<PointerType>())
10815   {
10816     Result = PT->getPointeeType();
10817   }
10818   else if (const ObjCObjectPointerType *OPT =
10819              OpTy->getAs<ObjCObjectPointerType>())
10820     Result = OPT->getPointeeType();
10821   else {
10822     ExprResult PR = S.CheckPlaceholderExpr(Op);
10823     if (PR.isInvalid()) return QualType();
10824     if (PR.get() != Op)
10825       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10826   }
10827 
10828   if (Result.isNull()) {
10829     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10830       << OpTy << Op->getSourceRange();
10831     return QualType();
10832   }
10833 
10834   // Note that per both C89 and C99, indirection is always legal, even if Result
10835   // is an incomplete type or void.  It would be possible to warn about
10836   // dereferencing a void pointer, but it's completely well-defined, and such a
10837   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10838   // for pointers to 'void' but is fine for any other pointer type:
10839   //
10840   // C++ [expr.unary.op]p1:
10841   //   [...] the expression to which [the unary * operator] is applied shall
10842   //   be a pointer to an object type, or a pointer to a function type
10843   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10844     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10845       << OpTy << Op->getSourceRange();
10846 
10847   // Dereferences are usually l-values...
10848   VK = VK_LValue;
10849 
10850   // ...except that certain expressions are never l-values in C.
10851   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10852     VK = VK_RValue;
10853 
10854   return Result;
10855 }
10856 
10857 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10858   BinaryOperatorKind Opc;
10859   switch (Kind) {
10860   default: llvm_unreachable("Unknown binop!");
10861   case tok::periodstar:           Opc = BO_PtrMemD; break;
10862   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10863   case tok::star:                 Opc = BO_Mul; break;
10864   case tok::slash:                Opc = BO_Div; break;
10865   case tok::percent:              Opc = BO_Rem; break;
10866   case tok::plus:                 Opc = BO_Add; break;
10867   case tok::minus:                Opc = BO_Sub; break;
10868   case tok::lessless:             Opc = BO_Shl; break;
10869   case tok::greatergreater:       Opc = BO_Shr; break;
10870   case tok::lessequal:            Opc = BO_LE; break;
10871   case tok::less:                 Opc = BO_LT; break;
10872   case tok::greaterequal:         Opc = BO_GE; break;
10873   case tok::greater:              Opc = BO_GT; break;
10874   case tok::exclaimequal:         Opc = BO_NE; break;
10875   case tok::equalequal:           Opc = BO_EQ; break;
10876   case tok::amp:                  Opc = BO_And; break;
10877   case tok::caret:                Opc = BO_Xor; break;
10878   case tok::pipe:                 Opc = BO_Or; break;
10879   case tok::ampamp:               Opc = BO_LAnd; break;
10880   case tok::pipepipe:             Opc = BO_LOr; break;
10881   case tok::equal:                Opc = BO_Assign; break;
10882   case tok::starequal:            Opc = BO_MulAssign; break;
10883   case tok::slashequal:           Opc = BO_DivAssign; break;
10884   case tok::percentequal:         Opc = BO_RemAssign; break;
10885   case tok::plusequal:            Opc = BO_AddAssign; break;
10886   case tok::minusequal:           Opc = BO_SubAssign; break;
10887   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10888   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10889   case tok::ampequal:             Opc = BO_AndAssign; break;
10890   case tok::caretequal:           Opc = BO_XorAssign; break;
10891   case tok::pipeequal:            Opc = BO_OrAssign; break;
10892   case tok::comma:                Opc = BO_Comma; break;
10893   }
10894   return Opc;
10895 }
10896 
10897 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10898   tok::TokenKind Kind) {
10899   UnaryOperatorKind Opc;
10900   switch (Kind) {
10901   default: llvm_unreachable("Unknown unary op!");
10902   case tok::plusplus:     Opc = UO_PreInc; break;
10903   case tok::minusminus:   Opc = UO_PreDec; break;
10904   case tok::amp:          Opc = UO_AddrOf; break;
10905   case tok::star:         Opc = UO_Deref; break;
10906   case tok::plus:         Opc = UO_Plus; break;
10907   case tok::minus:        Opc = UO_Minus; break;
10908   case tok::tilde:        Opc = UO_Not; break;
10909   case tok::exclaim:      Opc = UO_LNot; break;
10910   case tok::kw___real:    Opc = UO_Real; break;
10911   case tok::kw___imag:    Opc = UO_Imag; break;
10912   case tok::kw___extension__: Opc = UO_Extension; break;
10913   }
10914   return Opc;
10915 }
10916 
10917 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10918 /// This warning is only emitted for builtin assignment operations. It is also
10919 /// suppressed in the event of macro expansions.
10920 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10921                                    SourceLocation OpLoc) {
10922   if (!S.ActiveTemplateInstantiations.empty())
10923     return;
10924   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10925     return;
10926   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10927   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10928   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10929   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10930   if (!LHSDeclRef || !RHSDeclRef ||
10931       LHSDeclRef->getLocation().isMacroID() ||
10932       RHSDeclRef->getLocation().isMacroID())
10933     return;
10934   const ValueDecl *LHSDecl =
10935     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10936   const ValueDecl *RHSDecl =
10937     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10938   if (LHSDecl != RHSDecl)
10939     return;
10940   if (LHSDecl->getType().isVolatileQualified())
10941     return;
10942   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10943     if (RefTy->getPointeeType().isVolatileQualified())
10944       return;
10945 
10946   S.Diag(OpLoc, diag::warn_self_assignment)
10947       << LHSDeclRef->getType()
10948       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10949 }
10950 
10951 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10952 /// is usually indicative of introspection within the Objective-C pointer.
10953 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10954                                           SourceLocation OpLoc) {
10955   if (!S.getLangOpts().ObjC1)
10956     return;
10957 
10958   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10959   const Expr *LHS = L.get();
10960   const Expr *RHS = R.get();
10961 
10962   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10963     ObjCPointerExpr = LHS;
10964     OtherExpr = RHS;
10965   }
10966   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10967     ObjCPointerExpr = RHS;
10968     OtherExpr = LHS;
10969   }
10970 
10971   // This warning is deliberately made very specific to reduce false
10972   // positives with logic that uses '&' for hashing.  This logic mainly
10973   // looks for code trying to introspect into tagged pointers, which
10974   // code should generally never do.
10975   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10976     unsigned Diag = diag::warn_objc_pointer_masking;
10977     // Determine if we are introspecting the result of performSelectorXXX.
10978     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10979     // Special case messages to -performSelector and friends, which
10980     // can return non-pointer values boxed in a pointer value.
10981     // Some clients may wish to silence warnings in this subcase.
10982     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10983       Selector S = ME->getSelector();
10984       StringRef SelArg0 = S.getNameForSlot(0);
10985       if (SelArg0.startswith("performSelector"))
10986         Diag = diag::warn_objc_pointer_masking_performSelector;
10987     }
10988 
10989     S.Diag(OpLoc, Diag)
10990       << ObjCPointerExpr->getSourceRange();
10991   }
10992 }
10993 
10994 static NamedDecl *getDeclFromExpr(Expr *E) {
10995   if (!E)
10996     return nullptr;
10997   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10998     return DRE->getDecl();
10999   if (auto *ME = dyn_cast<MemberExpr>(E))
11000     return ME->getMemberDecl();
11001   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11002     return IRE->getDecl();
11003   return nullptr;
11004 }
11005 
11006 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11007 /// operator @p Opc at location @c TokLoc. This routine only supports
11008 /// built-in operations; ActOnBinOp handles overloaded operators.
11009 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11010                                     BinaryOperatorKind Opc,
11011                                     Expr *LHSExpr, Expr *RHSExpr) {
11012   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11013     // The syntax only allows initializer lists on the RHS of assignment,
11014     // so we don't need to worry about accepting invalid code for
11015     // non-assignment operators.
11016     // C++11 5.17p9:
11017     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11018     //   of x = {} is x = T().
11019     InitializationKind Kind =
11020         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11021     InitializedEntity Entity =
11022         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11023     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11024     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11025     if (Init.isInvalid())
11026       return Init;
11027     RHSExpr = Init.get();
11028   }
11029 
11030   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11031   QualType ResultTy;     // Result type of the binary operator.
11032   // The following two variables are used for compound assignment operators
11033   QualType CompLHSTy;    // Type of LHS after promotions for computation
11034   QualType CompResultTy; // Type of computation result
11035   ExprValueKind VK = VK_RValue;
11036   ExprObjectKind OK = OK_Ordinary;
11037 
11038   if (!getLangOpts().CPlusPlus) {
11039     // C cannot handle TypoExpr nodes on either side of a binop because it
11040     // doesn't handle dependent types properly, so make sure any TypoExprs have
11041     // been dealt with before checking the operands.
11042     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11043     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11044       if (Opc != BO_Assign)
11045         return ExprResult(E);
11046       // Avoid correcting the RHS to the same Expr as the LHS.
11047       Decl *D = getDeclFromExpr(E);
11048       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11049     });
11050     if (!LHS.isUsable() || !RHS.isUsable())
11051       return ExprError();
11052   }
11053 
11054   if (getLangOpts().OpenCL) {
11055     QualType LHSTy = LHSExpr->getType();
11056     QualType RHSTy = RHSExpr->getType();
11057     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11058     // the ATOMIC_VAR_INIT macro.
11059     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11060       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11061       if (BO_Assign == Opc)
11062         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11063       else
11064         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11065       return ExprError();
11066     }
11067 
11068     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11069     // only with a builtin functions and therefore should be disallowed here.
11070     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11071         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11072         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11073         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11074       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11075       return ExprError();
11076     }
11077   }
11078 
11079   switch (Opc) {
11080   case BO_Assign:
11081     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11082     if (getLangOpts().CPlusPlus &&
11083         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11084       VK = LHS.get()->getValueKind();
11085       OK = LHS.get()->getObjectKind();
11086     }
11087     if (!ResultTy.isNull()) {
11088       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11089       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11090     }
11091     RecordModifiableNonNullParam(*this, LHS.get());
11092     break;
11093   case BO_PtrMemD:
11094   case BO_PtrMemI:
11095     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11096                                             Opc == BO_PtrMemI);
11097     break;
11098   case BO_Mul:
11099   case BO_Div:
11100     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11101                                            Opc == BO_Div);
11102     break;
11103   case BO_Rem:
11104     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11105     break;
11106   case BO_Add:
11107     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11108     break;
11109   case BO_Sub:
11110     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11111     break;
11112   case BO_Shl:
11113   case BO_Shr:
11114     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11115     break;
11116   case BO_LE:
11117   case BO_LT:
11118   case BO_GE:
11119   case BO_GT:
11120     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11121     break;
11122   case BO_EQ:
11123   case BO_NE:
11124     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11125     break;
11126   case BO_And:
11127     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11128   case BO_Xor:
11129   case BO_Or:
11130     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11131     break;
11132   case BO_LAnd:
11133   case BO_LOr:
11134     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11135     break;
11136   case BO_MulAssign:
11137   case BO_DivAssign:
11138     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11139                                                Opc == BO_DivAssign);
11140     CompLHSTy = CompResultTy;
11141     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11142       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11143     break;
11144   case BO_RemAssign:
11145     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11146     CompLHSTy = CompResultTy;
11147     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11148       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11149     break;
11150   case BO_AddAssign:
11151     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11152     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11153       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11154     break;
11155   case BO_SubAssign:
11156     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11157     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11158       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11159     break;
11160   case BO_ShlAssign:
11161   case BO_ShrAssign:
11162     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11163     CompLHSTy = CompResultTy;
11164     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11165       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11166     break;
11167   case BO_AndAssign:
11168   case BO_OrAssign: // fallthrough
11169     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11170   case BO_XorAssign:
11171     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11172     CompLHSTy = CompResultTy;
11173     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11174       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11175     break;
11176   case BO_Comma:
11177     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11178     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11179       VK = RHS.get()->getValueKind();
11180       OK = RHS.get()->getObjectKind();
11181     }
11182     break;
11183   }
11184   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11185     return ExprError();
11186 
11187   // Check for array bounds violations for both sides of the BinaryOperator
11188   CheckArrayAccess(LHS.get());
11189   CheckArrayAccess(RHS.get());
11190 
11191   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11192     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11193                                                  &Context.Idents.get("object_setClass"),
11194                                                  SourceLocation(), LookupOrdinaryName);
11195     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11196       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11197       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11198       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11199       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11200       FixItHint::CreateInsertion(RHSLocEnd, ")");
11201     }
11202     else
11203       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11204   }
11205   else if (const ObjCIvarRefExpr *OIRE =
11206            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11207     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11208 
11209   if (CompResultTy.isNull())
11210     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11211                                         OK, OpLoc, FPFeatures.fp_contract);
11212   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11213       OK_ObjCProperty) {
11214     VK = VK_LValue;
11215     OK = LHS.get()->getObjectKind();
11216   }
11217   return new (Context) CompoundAssignOperator(
11218       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11219       OpLoc, FPFeatures.fp_contract);
11220 }
11221 
11222 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11223 /// operators are mixed in a way that suggests that the programmer forgot that
11224 /// comparison operators have higher precedence. The most typical example of
11225 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11226 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11227                                       SourceLocation OpLoc, Expr *LHSExpr,
11228                                       Expr *RHSExpr) {
11229   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11230   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11231 
11232   // Check that one of the sides is a comparison operator and the other isn't.
11233   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11234   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11235   if (isLeftComp == isRightComp)
11236     return;
11237 
11238   // Bitwise operations are sometimes used as eager logical ops.
11239   // Don't diagnose this.
11240   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11241   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11242   if (isLeftBitwise || isRightBitwise)
11243     return;
11244 
11245   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11246                                                    OpLoc)
11247                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11248   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11249   SourceRange ParensRange = isLeftComp ?
11250       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11251     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11252 
11253   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11254     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11255   SuggestParentheses(Self, OpLoc,
11256     Self.PDiag(diag::note_precedence_silence) << OpStr,
11257     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11258   SuggestParentheses(Self, OpLoc,
11259     Self.PDiag(diag::note_precedence_bitwise_first)
11260       << BinaryOperator::getOpcodeStr(Opc),
11261     ParensRange);
11262 }
11263 
11264 /// \brief It accepts a '&&' expr that is inside a '||' one.
11265 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11266 /// in parentheses.
11267 static void
11268 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11269                                        BinaryOperator *Bop) {
11270   assert(Bop->getOpcode() == BO_LAnd);
11271   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11272       << Bop->getSourceRange() << OpLoc;
11273   SuggestParentheses(Self, Bop->getOperatorLoc(),
11274     Self.PDiag(diag::note_precedence_silence)
11275       << Bop->getOpcodeStr(),
11276     Bop->getSourceRange());
11277 }
11278 
11279 /// \brief Returns true if the given expression can be evaluated as a constant
11280 /// 'true'.
11281 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11282   bool Res;
11283   return !E->isValueDependent() &&
11284          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11285 }
11286 
11287 /// \brief Returns true if the given expression can be evaluated as a constant
11288 /// 'false'.
11289 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11290   bool Res;
11291   return !E->isValueDependent() &&
11292          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11293 }
11294 
11295 /// \brief Look for '&&' in the left hand of a '||' expr.
11296 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11297                                              Expr *LHSExpr, Expr *RHSExpr) {
11298   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11299     if (Bop->getOpcode() == BO_LAnd) {
11300       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11301       if (EvaluatesAsFalse(S, RHSExpr))
11302         return;
11303       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11304       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11305         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11306     } else if (Bop->getOpcode() == BO_LOr) {
11307       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11308         // If it's "a || b && 1 || c" we didn't warn earlier for
11309         // "a || b && 1", but warn now.
11310         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11311           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11312       }
11313     }
11314   }
11315 }
11316 
11317 /// \brief Look for '&&' in the right hand of a '||' expr.
11318 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11319                                              Expr *LHSExpr, Expr *RHSExpr) {
11320   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11321     if (Bop->getOpcode() == BO_LAnd) {
11322       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11323       if (EvaluatesAsFalse(S, LHSExpr))
11324         return;
11325       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11326       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11327         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11328     }
11329   }
11330 }
11331 
11332 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11333 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11334 /// the '&' expression in parentheses.
11335 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11336                                          SourceLocation OpLoc, Expr *SubExpr) {
11337   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11338     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11339       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11340         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11341         << Bop->getSourceRange() << OpLoc;
11342       SuggestParentheses(S, Bop->getOperatorLoc(),
11343         S.PDiag(diag::note_precedence_silence)
11344           << Bop->getOpcodeStr(),
11345         Bop->getSourceRange());
11346     }
11347   }
11348 }
11349 
11350 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11351                                     Expr *SubExpr, StringRef Shift) {
11352   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11353     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11354       StringRef Op = Bop->getOpcodeStr();
11355       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11356           << Bop->getSourceRange() << OpLoc << Shift << Op;
11357       SuggestParentheses(S, Bop->getOperatorLoc(),
11358           S.PDiag(diag::note_precedence_silence) << Op,
11359           Bop->getSourceRange());
11360     }
11361   }
11362 }
11363 
11364 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11365                                  Expr *LHSExpr, Expr *RHSExpr) {
11366   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11367   if (!OCE)
11368     return;
11369 
11370   FunctionDecl *FD = OCE->getDirectCallee();
11371   if (!FD || !FD->isOverloadedOperator())
11372     return;
11373 
11374   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11375   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11376     return;
11377 
11378   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11379       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11380       << (Kind == OO_LessLess);
11381   SuggestParentheses(S, OCE->getOperatorLoc(),
11382                      S.PDiag(diag::note_precedence_silence)
11383                          << (Kind == OO_LessLess ? "<<" : ">>"),
11384                      OCE->getSourceRange());
11385   SuggestParentheses(S, OpLoc,
11386                      S.PDiag(diag::note_evaluate_comparison_first),
11387                      SourceRange(OCE->getArg(1)->getLocStart(),
11388                                  RHSExpr->getLocEnd()));
11389 }
11390 
11391 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11392 /// precedence.
11393 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11394                                     SourceLocation OpLoc, Expr *LHSExpr,
11395                                     Expr *RHSExpr){
11396   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11397   if (BinaryOperator::isBitwiseOp(Opc))
11398     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11399 
11400   // Diagnose "arg1 & arg2 | arg3"
11401   if ((Opc == BO_Or || Opc == BO_Xor) &&
11402       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11403     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11404     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11405   }
11406 
11407   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11408   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11409   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11410     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11411     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11412   }
11413 
11414   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11415       || Opc == BO_Shr) {
11416     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11417     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11418     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11419   }
11420 
11421   // Warn on overloaded shift operators and comparisons, such as:
11422   // cout << 5 == 4;
11423   if (BinaryOperator::isComparisonOp(Opc))
11424     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11425 }
11426 
11427 // Binary Operators.  'Tok' is the token for the operator.
11428 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11429                             tok::TokenKind Kind,
11430                             Expr *LHSExpr, Expr *RHSExpr) {
11431   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11432   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11433   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11434 
11435   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11436   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11437 
11438   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11439 }
11440 
11441 /// Build an overloaded binary operator expression in the given scope.
11442 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11443                                        BinaryOperatorKind Opc,
11444                                        Expr *LHS, Expr *RHS) {
11445   // Find all of the overloaded operators visible from this
11446   // point. We perform both an operator-name lookup from the local
11447   // scope and an argument-dependent lookup based on the types of
11448   // the arguments.
11449   UnresolvedSet<16> Functions;
11450   OverloadedOperatorKind OverOp
11451     = BinaryOperator::getOverloadedOperator(Opc);
11452   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11453     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11454                                    RHS->getType(), Functions);
11455 
11456   // Build the (potentially-overloaded, potentially-dependent)
11457   // binary operation.
11458   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11459 }
11460 
11461 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11462                             BinaryOperatorKind Opc,
11463                             Expr *LHSExpr, Expr *RHSExpr) {
11464   // We want to end up calling one of checkPseudoObjectAssignment
11465   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11466   // both expressions are overloadable or either is type-dependent),
11467   // or CreateBuiltinBinOp (in any other case).  We also want to get
11468   // any placeholder types out of the way.
11469 
11470   // Handle pseudo-objects in the LHS.
11471   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11472     // Assignments with a pseudo-object l-value need special analysis.
11473     if (pty->getKind() == BuiltinType::PseudoObject &&
11474         BinaryOperator::isAssignmentOp(Opc))
11475       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11476 
11477     // Don't resolve overloads if the other type is overloadable.
11478     if (pty->getKind() == BuiltinType::Overload) {
11479       // We can't actually test that if we still have a placeholder,
11480       // though.  Fortunately, none of the exceptions we see in that
11481       // code below are valid when the LHS is an overload set.  Note
11482       // that an overload set can be dependently-typed, but it never
11483       // instantiates to having an overloadable type.
11484       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11485       if (resolvedRHS.isInvalid()) return ExprError();
11486       RHSExpr = resolvedRHS.get();
11487 
11488       if (RHSExpr->isTypeDependent() ||
11489           RHSExpr->getType()->isOverloadableType())
11490         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11491     }
11492 
11493     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11494     if (LHS.isInvalid()) return ExprError();
11495     LHSExpr = LHS.get();
11496   }
11497 
11498   // Handle pseudo-objects in the RHS.
11499   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11500     // An overload in the RHS can potentially be resolved by the type
11501     // being assigned to.
11502     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11503       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11504         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11505 
11506       if (LHSExpr->getType()->isOverloadableType())
11507         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11508 
11509       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11510     }
11511 
11512     // Don't resolve overloads if the other type is overloadable.
11513     if (pty->getKind() == BuiltinType::Overload &&
11514         LHSExpr->getType()->isOverloadableType())
11515       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11516 
11517     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11518     if (!resolvedRHS.isUsable()) return ExprError();
11519     RHSExpr = resolvedRHS.get();
11520   }
11521 
11522   if (getLangOpts().CPlusPlus) {
11523     // If either expression is type-dependent, always build an
11524     // overloaded op.
11525     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11526       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11527 
11528     // Otherwise, build an overloaded op if either expression has an
11529     // overloadable type.
11530     if (LHSExpr->getType()->isOverloadableType() ||
11531         RHSExpr->getType()->isOverloadableType())
11532       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11533   }
11534 
11535   // Build a built-in binary operation.
11536   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11537 }
11538 
11539 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11540                                       UnaryOperatorKind Opc,
11541                                       Expr *InputExpr) {
11542   ExprResult Input = InputExpr;
11543   ExprValueKind VK = VK_RValue;
11544   ExprObjectKind OK = OK_Ordinary;
11545   QualType resultType;
11546   if (getLangOpts().OpenCL) {
11547     QualType Ty = InputExpr->getType();
11548     // The only legal unary operation for atomics is '&'.
11549     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11550     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11551     // only with a builtin functions and therefore should be disallowed here.
11552         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11553         || Ty->isBlockPointerType())) {
11554       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11555                        << InputExpr->getType()
11556                        << Input.get()->getSourceRange());
11557     }
11558   }
11559   switch (Opc) {
11560   case UO_PreInc:
11561   case UO_PreDec:
11562   case UO_PostInc:
11563   case UO_PostDec:
11564     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11565                                                 OpLoc,
11566                                                 Opc == UO_PreInc ||
11567                                                 Opc == UO_PostInc,
11568                                                 Opc == UO_PreInc ||
11569                                                 Opc == UO_PreDec);
11570     break;
11571   case UO_AddrOf:
11572     resultType = CheckAddressOfOperand(Input, OpLoc);
11573     RecordModifiableNonNullParam(*this, InputExpr);
11574     break;
11575   case UO_Deref: {
11576     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11577     if (Input.isInvalid()) return ExprError();
11578     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11579     break;
11580   }
11581   case UO_Plus:
11582   case UO_Minus:
11583     Input = UsualUnaryConversions(Input.get());
11584     if (Input.isInvalid()) return ExprError();
11585     resultType = Input.get()->getType();
11586     if (resultType->isDependentType())
11587       break;
11588     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11589       break;
11590     else if (resultType->isVectorType() &&
11591              // The z vector extensions don't allow + or - with bool vectors.
11592              (!Context.getLangOpts().ZVector ||
11593               resultType->getAs<VectorType>()->getVectorKind() !=
11594               VectorType::AltiVecBool))
11595       break;
11596     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11597              Opc == UO_Plus &&
11598              resultType->isPointerType())
11599       break;
11600 
11601     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11602       << resultType << Input.get()->getSourceRange());
11603 
11604   case UO_Not: // bitwise complement
11605     Input = UsualUnaryConversions(Input.get());
11606     if (Input.isInvalid())
11607       return ExprError();
11608     resultType = Input.get()->getType();
11609     if (resultType->isDependentType())
11610       break;
11611     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11612     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11613       // C99 does not support '~' for complex conjugation.
11614       Diag(OpLoc, diag::ext_integer_complement_complex)
11615           << resultType << Input.get()->getSourceRange();
11616     else if (resultType->hasIntegerRepresentation())
11617       break;
11618     else if (resultType->isExtVectorType()) {
11619       if (Context.getLangOpts().OpenCL) {
11620         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11621         // on vector float types.
11622         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11623         if (!T->isIntegerType())
11624           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11625                            << resultType << Input.get()->getSourceRange());
11626       }
11627       break;
11628     } else {
11629       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11630                        << resultType << Input.get()->getSourceRange());
11631     }
11632     break;
11633 
11634   case UO_LNot: // logical negation
11635     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11636     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11637     if (Input.isInvalid()) return ExprError();
11638     resultType = Input.get()->getType();
11639 
11640     // Though we still have to promote half FP to float...
11641     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11642       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11643       resultType = Context.FloatTy;
11644     }
11645 
11646     if (resultType->isDependentType())
11647       break;
11648     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11649       // C99 6.5.3.3p1: ok, fallthrough;
11650       if (Context.getLangOpts().CPlusPlus) {
11651         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11652         // operand contextually converted to bool.
11653         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11654                                   ScalarTypeToBooleanCastKind(resultType));
11655       } else if (Context.getLangOpts().OpenCL &&
11656                  Context.getLangOpts().OpenCLVersion < 120) {
11657         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11658         // operate on scalar float types.
11659         if (!resultType->isIntegerType())
11660           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11661                            << resultType << Input.get()->getSourceRange());
11662       }
11663     } else if (resultType->isExtVectorType()) {
11664       if (Context.getLangOpts().OpenCL &&
11665           Context.getLangOpts().OpenCLVersion < 120) {
11666         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11667         // operate on vector float types.
11668         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11669         if (!T->isIntegerType())
11670           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11671                            << resultType << Input.get()->getSourceRange());
11672       }
11673       // Vector logical not returns the signed variant of the operand type.
11674       resultType = GetSignedVectorType(resultType);
11675       break;
11676     } else {
11677       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11678         << resultType << Input.get()->getSourceRange());
11679     }
11680 
11681     // LNot always has type int. C99 6.5.3.3p5.
11682     // In C++, it's bool. C++ 5.3.1p8
11683     resultType = Context.getLogicalOperationType();
11684     break;
11685   case UO_Real:
11686   case UO_Imag:
11687     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11688     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11689     // complex l-values to ordinary l-values and all other values to r-values.
11690     if (Input.isInvalid()) return ExprError();
11691     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11692       if (Input.get()->getValueKind() != VK_RValue &&
11693           Input.get()->getObjectKind() == OK_Ordinary)
11694         VK = Input.get()->getValueKind();
11695     } else if (!getLangOpts().CPlusPlus) {
11696       // In C, a volatile scalar is read by __imag. In C++, it is not.
11697       Input = DefaultLvalueConversion(Input.get());
11698     }
11699     break;
11700   case UO_Extension:
11701   case UO_Coawait:
11702     resultType = Input.get()->getType();
11703     VK = Input.get()->getValueKind();
11704     OK = Input.get()->getObjectKind();
11705     break;
11706   }
11707   if (resultType.isNull() || Input.isInvalid())
11708     return ExprError();
11709 
11710   // Check for array bounds violations in the operand of the UnaryOperator,
11711   // except for the '*' and '&' operators that have to be handled specially
11712   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11713   // that are explicitly defined as valid by the standard).
11714   if (Opc != UO_AddrOf && Opc != UO_Deref)
11715     CheckArrayAccess(Input.get());
11716 
11717   return new (Context)
11718       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11719 }
11720 
11721 /// \brief Determine whether the given expression is a qualified member
11722 /// access expression, of a form that could be turned into a pointer to member
11723 /// with the address-of operator.
11724 static bool isQualifiedMemberAccess(Expr *E) {
11725   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11726     if (!DRE->getQualifier())
11727       return false;
11728 
11729     ValueDecl *VD = DRE->getDecl();
11730     if (!VD->isCXXClassMember())
11731       return false;
11732 
11733     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11734       return true;
11735     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11736       return Method->isInstance();
11737 
11738     return false;
11739   }
11740 
11741   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11742     if (!ULE->getQualifier())
11743       return false;
11744 
11745     for (NamedDecl *D : ULE->decls()) {
11746       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11747         if (Method->isInstance())
11748           return true;
11749       } else {
11750         // Overload set does not contain methods.
11751         break;
11752       }
11753     }
11754 
11755     return false;
11756   }
11757 
11758   return false;
11759 }
11760 
11761 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11762                               UnaryOperatorKind Opc, Expr *Input) {
11763   // First things first: handle placeholders so that the
11764   // overloaded-operator check considers the right type.
11765   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11766     // Increment and decrement of pseudo-object references.
11767     if (pty->getKind() == BuiltinType::PseudoObject &&
11768         UnaryOperator::isIncrementDecrementOp(Opc))
11769       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11770 
11771     // extension is always a builtin operator.
11772     if (Opc == UO_Extension)
11773       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11774 
11775     // & gets special logic for several kinds of placeholder.
11776     // The builtin code knows what to do.
11777     if (Opc == UO_AddrOf &&
11778         (pty->getKind() == BuiltinType::Overload ||
11779          pty->getKind() == BuiltinType::UnknownAny ||
11780          pty->getKind() == BuiltinType::BoundMember))
11781       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11782 
11783     // Anything else needs to be handled now.
11784     ExprResult Result = CheckPlaceholderExpr(Input);
11785     if (Result.isInvalid()) return ExprError();
11786     Input = Result.get();
11787   }
11788 
11789   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11790       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11791       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11792     // Find all of the overloaded operators visible from this
11793     // point. We perform both an operator-name lookup from the local
11794     // scope and an argument-dependent lookup based on the types of
11795     // the arguments.
11796     UnresolvedSet<16> Functions;
11797     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11798     if (S && OverOp != OO_None)
11799       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11800                                    Functions);
11801 
11802     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11803   }
11804 
11805   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11806 }
11807 
11808 // Unary Operators.  'Tok' is the token for the operator.
11809 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11810                               tok::TokenKind Op, Expr *Input) {
11811   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11812 }
11813 
11814 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11815 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11816                                 LabelDecl *TheDecl) {
11817   TheDecl->markUsed(Context);
11818   // Create the AST node.  The address of a label always has type 'void*'.
11819   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11820                                      Context.getPointerType(Context.VoidTy));
11821 }
11822 
11823 /// Given the last statement in a statement-expression, check whether
11824 /// the result is a producing expression (like a call to an
11825 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11826 /// release out of the full-expression.  Otherwise, return null.
11827 /// Cannot fail.
11828 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11829   // Should always be wrapped with one of these.
11830   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11831   if (!cleanups) return nullptr;
11832 
11833   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11834   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11835     return nullptr;
11836 
11837   // Splice out the cast.  This shouldn't modify any interesting
11838   // features of the statement.
11839   Expr *producer = cast->getSubExpr();
11840   assert(producer->getType() == cast->getType());
11841   assert(producer->getValueKind() == cast->getValueKind());
11842   cleanups->setSubExpr(producer);
11843   return cleanups;
11844 }
11845 
11846 void Sema::ActOnStartStmtExpr() {
11847   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11848 }
11849 
11850 void Sema::ActOnStmtExprError() {
11851   // Note that function is also called by TreeTransform when leaving a
11852   // StmtExpr scope without rebuilding anything.
11853 
11854   DiscardCleanupsInEvaluationContext();
11855   PopExpressionEvaluationContext();
11856 }
11857 
11858 ExprResult
11859 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11860                     SourceLocation RPLoc) { // "({..})"
11861   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11862   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11863 
11864   if (hasAnyUnrecoverableErrorsInThisFunction())
11865     DiscardCleanupsInEvaluationContext();
11866   assert(!Cleanup.exprNeedsCleanups() &&
11867          "cleanups within StmtExpr not correctly bound!");
11868   PopExpressionEvaluationContext();
11869 
11870   // FIXME: there are a variety of strange constraints to enforce here, for
11871   // example, it is not possible to goto into a stmt expression apparently.
11872   // More semantic analysis is needed.
11873 
11874   // If there are sub-stmts in the compound stmt, take the type of the last one
11875   // as the type of the stmtexpr.
11876   QualType Ty = Context.VoidTy;
11877   bool StmtExprMayBindToTemp = false;
11878   if (!Compound->body_empty()) {
11879     Stmt *LastStmt = Compound->body_back();
11880     LabelStmt *LastLabelStmt = nullptr;
11881     // If LastStmt is a label, skip down through into the body.
11882     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11883       LastLabelStmt = Label;
11884       LastStmt = Label->getSubStmt();
11885     }
11886 
11887     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11888       // Do function/array conversion on the last expression, but not
11889       // lvalue-to-rvalue.  However, initialize an unqualified type.
11890       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11891       if (LastExpr.isInvalid())
11892         return ExprError();
11893       Ty = LastExpr.get()->getType().getUnqualifiedType();
11894 
11895       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11896         // In ARC, if the final expression ends in a consume, splice
11897         // the consume out and bind it later.  In the alternate case
11898         // (when dealing with a retainable type), the result
11899         // initialization will create a produce.  In both cases the
11900         // result will be +1, and we'll need to balance that out with
11901         // a bind.
11902         if (Expr *rebuiltLastStmt
11903               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11904           LastExpr = rebuiltLastStmt;
11905         } else {
11906           LastExpr = PerformCopyInitialization(
11907                             InitializedEntity::InitializeResult(LPLoc,
11908                                                                 Ty,
11909                                                                 false),
11910                                                    SourceLocation(),
11911                                                LastExpr);
11912         }
11913 
11914         if (LastExpr.isInvalid())
11915           return ExprError();
11916         if (LastExpr.get() != nullptr) {
11917           if (!LastLabelStmt)
11918             Compound->setLastStmt(LastExpr.get());
11919           else
11920             LastLabelStmt->setSubStmt(LastExpr.get());
11921           StmtExprMayBindToTemp = true;
11922         }
11923       }
11924     }
11925   }
11926 
11927   // FIXME: Check that expression type is complete/non-abstract; statement
11928   // expressions are not lvalues.
11929   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11930   if (StmtExprMayBindToTemp)
11931     return MaybeBindToTemporary(ResStmtExpr);
11932   return ResStmtExpr;
11933 }
11934 
11935 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11936                                       TypeSourceInfo *TInfo,
11937                                       ArrayRef<OffsetOfComponent> Components,
11938                                       SourceLocation RParenLoc) {
11939   QualType ArgTy = TInfo->getType();
11940   bool Dependent = ArgTy->isDependentType();
11941   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11942 
11943   // We must have at least one component that refers to the type, and the first
11944   // one is known to be a field designator.  Verify that the ArgTy represents
11945   // a struct/union/class.
11946   if (!Dependent && !ArgTy->isRecordType())
11947     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11948                        << ArgTy << TypeRange);
11949 
11950   // Type must be complete per C99 7.17p3 because a declaring a variable
11951   // with an incomplete type would be ill-formed.
11952   if (!Dependent
11953       && RequireCompleteType(BuiltinLoc, ArgTy,
11954                              diag::err_offsetof_incomplete_type, TypeRange))
11955     return ExprError();
11956 
11957   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11958   // GCC extension, diagnose them.
11959   // FIXME: This diagnostic isn't actually visible because the location is in
11960   // a system header!
11961   if (Components.size() != 1)
11962     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11963       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11964 
11965   bool DidWarnAboutNonPOD = false;
11966   QualType CurrentType = ArgTy;
11967   SmallVector<OffsetOfNode, 4> Comps;
11968   SmallVector<Expr*, 4> Exprs;
11969   for (const OffsetOfComponent &OC : Components) {
11970     if (OC.isBrackets) {
11971       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11972       if (!CurrentType->isDependentType()) {
11973         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11974         if(!AT)
11975           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11976                            << CurrentType);
11977         CurrentType = AT->getElementType();
11978       } else
11979         CurrentType = Context.DependentTy;
11980 
11981       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11982       if (IdxRval.isInvalid())
11983         return ExprError();
11984       Expr *Idx = IdxRval.get();
11985 
11986       // The expression must be an integral expression.
11987       // FIXME: An integral constant expression?
11988       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11989           !Idx->getType()->isIntegerType())
11990         return ExprError(Diag(Idx->getLocStart(),
11991                               diag::err_typecheck_subscript_not_integer)
11992                          << Idx->getSourceRange());
11993 
11994       // Record this array index.
11995       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11996       Exprs.push_back(Idx);
11997       continue;
11998     }
11999 
12000     // Offset of a field.
12001     if (CurrentType->isDependentType()) {
12002       // We have the offset of a field, but we can't look into the dependent
12003       // type. Just record the identifier of the field.
12004       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12005       CurrentType = Context.DependentTy;
12006       continue;
12007     }
12008 
12009     // We need to have a complete type to look into.
12010     if (RequireCompleteType(OC.LocStart, CurrentType,
12011                             diag::err_offsetof_incomplete_type))
12012       return ExprError();
12013 
12014     // Look for the designated field.
12015     const RecordType *RC = CurrentType->getAs<RecordType>();
12016     if (!RC)
12017       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12018                        << CurrentType);
12019     RecordDecl *RD = RC->getDecl();
12020 
12021     // C++ [lib.support.types]p5:
12022     //   The macro offsetof accepts a restricted set of type arguments in this
12023     //   International Standard. type shall be a POD structure or a POD union
12024     //   (clause 9).
12025     // C++11 [support.types]p4:
12026     //   If type is not a standard-layout class (Clause 9), the results are
12027     //   undefined.
12028     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12029       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12030       unsigned DiagID =
12031         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12032                             : diag::ext_offsetof_non_pod_type;
12033 
12034       if (!IsSafe && !DidWarnAboutNonPOD &&
12035           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12036                               PDiag(DiagID)
12037                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12038                               << CurrentType))
12039         DidWarnAboutNonPOD = true;
12040     }
12041 
12042     // Look for the field.
12043     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12044     LookupQualifiedName(R, RD);
12045     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12046     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12047     if (!MemberDecl) {
12048       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12049         MemberDecl = IndirectMemberDecl->getAnonField();
12050     }
12051 
12052     if (!MemberDecl)
12053       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12054                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12055                                                               OC.LocEnd));
12056 
12057     // C99 7.17p3:
12058     //   (If the specified member is a bit-field, the behavior is undefined.)
12059     //
12060     // We diagnose this as an error.
12061     if (MemberDecl->isBitField()) {
12062       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12063         << MemberDecl->getDeclName()
12064         << SourceRange(BuiltinLoc, RParenLoc);
12065       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12066       return ExprError();
12067     }
12068 
12069     RecordDecl *Parent = MemberDecl->getParent();
12070     if (IndirectMemberDecl)
12071       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12072 
12073     // If the member was found in a base class, introduce OffsetOfNodes for
12074     // the base class indirections.
12075     CXXBasePaths Paths;
12076     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12077                       Paths)) {
12078       if (Paths.getDetectedVirtual()) {
12079         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12080           << MemberDecl->getDeclName()
12081           << SourceRange(BuiltinLoc, RParenLoc);
12082         return ExprError();
12083       }
12084 
12085       CXXBasePath &Path = Paths.front();
12086       for (const CXXBasePathElement &B : Path)
12087         Comps.push_back(OffsetOfNode(B.Base));
12088     }
12089 
12090     if (IndirectMemberDecl) {
12091       for (auto *FI : IndirectMemberDecl->chain()) {
12092         assert(isa<FieldDecl>(FI));
12093         Comps.push_back(OffsetOfNode(OC.LocStart,
12094                                      cast<FieldDecl>(FI), OC.LocEnd));
12095       }
12096     } else
12097       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12098 
12099     CurrentType = MemberDecl->getType().getNonReferenceType();
12100   }
12101 
12102   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12103                               Comps, Exprs, RParenLoc);
12104 }
12105 
12106 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12107                                       SourceLocation BuiltinLoc,
12108                                       SourceLocation TypeLoc,
12109                                       ParsedType ParsedArgTy,
12110                                       ArrayRef<OffsetOfComponent> Components,
12111                                       SourceLocation RParenLoc) {
12112 
12113   TypeSourceInfo *ArgTInfo;
12114   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12115   if (ArgTy.isNull())
12116     return ExprError();
12117 
12118   if (!ArgTInfo)
12119     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12120 
12121   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12122 }
12123 
12124 
12125 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12126                                  Expr *CondExpr,
12127                                  Expr *LHSExpr, Expr *RHSExpr,
12128                                  SourceLocation RPLoc) {
12129   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12130 
12131   ExprValueKind VK = VK_RValue;
12132   ExprObjectKind OK = OK_Ordinary;
12133   QualType resType;
12134   bool ValueDependent = false;
12135   bool CondIsTrue = false;
12136   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12137     resType = Context.DependentTy;
12138     ValueDependent = true;
12139   } else {
12140     // The conditional expression is required to be a constant expression.
12141     llvm::APSInt condEval(32);
12142     ExprResult CondICE
12143       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12144           diag::err_typecheck_choose_expr_requires_constant, false);
12145     if (CondICE.isInvalid())
12146       return ExprError();
12147     CondExpr = CondICE.get();
12148     CondIsTrue = condEval.getZExtValue();
12149 
12150     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12151     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12152 
12153     resType = ActiveExpr->getType();
12154     ValueDependent = ActiveExpr->isValueDependent();
12155     VK = ActiveExpr->getValueKind();
12156     OK = ActiveExpr->getObjectKind();
12157   }
12158 
12159   return new (Context)
12160       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12161                  CondIsTrue, resType->isDependentType(), ValueDependent);
12162 }
12163 
12164 //===----------------------------------------------------------------------===//
12165 // Clang Extensions.
12166 //===----------------------------------------------------------------------===//
12167 
12168 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12169 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12170   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12171 
12172   if (LangOpts.CPlusPlus) {
12173     Decl *ManglingContextDecl;
12174     if (MangleNumberingContext *MCtx =
12175             getCurrentMangleNumberContext(Block->getDeclContext(),
12176                                           ManglingContextDecl)) {
12177       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12178       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12179     }
12180   }
12181 
12182   PushBlockScope(CurScope, Block);
12183   CurContext->addDecl(Block);
12184   if (CurScope)
12185     PushDeclContext(CurScope, Block);
12186   else
12187     CurContext = Block;
12188 
12189   getCurBlock()->HasImplicitReturnType = true;
12190 
12191   // Enter a new evaluation context to insulate the block from any
12192   // cleanups from the enclosing full-expression.
12193   PushExpressionEvaluationContext(PotentiallyEvaluated);
12194 }
12195 
12196 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12197                                Scope *CurScope) {
12198   assert(ParamInfo.getIdentifier() == nullptr &&
12199          "block-id should have no identifier!");
12200   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12201   BlockScopeInfo *CurBlock = getCurBlock();
12202 
12203   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12204   QualType T = Sig->getType();
12205 
12206   // FIXME: We should allow unexpanded parameter packs here, but that would,
12207   // in turn, make the block expression contain unexpanded parameter packs.
12208   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12209     // Drop the parameters.
12210     FunctionProtoType::ExtProtoInfo EPI;
12211     EPI.HasTrailingReturn = false;
12212     EPI.TypeQuals |= DeclSpec::TQ_const;
12213     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12214     Sig = Context.getTrivialTypeSourceInfo(T);
12215   }
12216 
12217   // GetTypeForDeclarator always produces a function type for a block
12218   // literal signature.  Furthermore, it is always a FunctionProtoType
12219   // unless the function was written with a typedef.
12220   assert(T->isFunctionType() &&
12221          "GetTypeForDeclarator made a non-function block signature");
12222 
12223   // Look for an explicit signature in that function type.
12224   FunctionProtoTypeLoc ExplicitSignature;
12225 
12226   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12227   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12228 
12229     // Check whether that explicit signature was synthesized by
12230     // GetTypeForDeclarator.  If so, don't save that as part of the
12231     // written signature.
12232     if (ExplicitSignature.getLocalRangeBegin() ==
12233         ExplicitSignature.getLocalRangeEnd()) {
12234       // This would be much cheaper if we stored TypeLocs instead of
12235       // TypeSourceInfos.
12236       TypeLoc Result = ExplicitSignature.getReturnLoc();
12237       unsigned Size = Result.getFullDataSize();
12238       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12239       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12240 
12241       ExplicitSignature = FunctionProtoTypeLoc();
12242     }
12243   }
12244 
12245   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12246   CurBlock->FunctionType = T;
12247 
12248   const FunctionType *Fn = T->getAs<FunctionType>();
12249   QualType RetTy = Fn->getReturnType();
12250   bool isVariadic =
12251     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12252 
12253   CurBlock->TheDecl->setIsVariadic(isVariadic);
12254 
12255   // Context.DependentTy is used as a placeholder for a missing block
12256   // return type.  TODO:  what should we do with declarators like:
12257   //   ^ * { ... }
12258   // If the answer is "apply template argument deduction"....
12259   if (RetTy != Context.DependentTy) {
12260     CurBlock->ReturnType = RetTy;
12261     CurBlock->TheDecl->setBlockMissingReturnType(false);
12262     CurBlock->HasImplicitReturnType = false;
12263   }
12264 
12265   // Push block parameters from the declarator if we had them.
12266   SmallVector<ParmVarDecl*, 8> Params;
12267   if (ExplicitSignature) {
12268     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12269       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12270       if (Param->getIdentifier() == nullptr &&
12271           !Param->isImplicit() &&
12272           !Param->isInvalidDecl() &&
12273           !getLangOpts().CPlusPlus)
12274         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12275       Params.push_back(Param);
12276     }
12277 
12278   // Fake up parameter variables if we have a typedef, like
12279   //   ^ fntype { ... }
12280   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12281     for (const auto &I : Fn->param_types()) {
12282       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12283           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12284       Params.push_back(Param);
12285     }
12286   }
12287 
12288   // Set the parameters on the block decl.
12289   if (!Params.empty()) {
12290     CurBlock->TheDecl->setParams(Params);
12291     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12292                              /*CheckParameterNames=*/false);
12293   }
12294 
12295   // Finally we can process decl attributes.
12296   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12297 
12298   // Put the parameter variables in scope.
12299   for (auto AI : CurBlock->TheDecl->parameters()) {
12300     AI->setOwningFunction(CurBlock->TheDecl);
12301 
12302     // If this has an identifier, add it to the scope stack.
12303     if (AI->getIdentifier()) {
12304       CheckShadow(CurBlock->TheScope, AI);
12305 
12306       PushOnScopeChains(AI, CurBlock->TheScope);
12307     }
12308   }
12309 }
12310 
12311 /// ActOnBlockError - If there is an error parsing a block, this callback
12312 /// is invoked to pop the information about the block from the action impl.
12313 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12314   // Leave the expression-evaluation context.
12315   DiscardCleanupsInEvaluationContext();
12316   PopExpressionEvaluationContext();
12317 
12318   // Pop off CurBlock, handle nested blocks.
12319   PopDeclContext();
12320   PopFunctionScopeInfo();
12321 }
12322 
12323 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12324 /// literal was successfully completed.  ^(int x){...}
12325 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12326                                     Stmt *Body, Scope *CurScope) {
12327   // If blocks are disabled, emit an error.
12328   if (!LangOpts.Blocks)
12329     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12330 
12331   // Leave the expression-evaluation context.
12332   if (hasAnyUnrecoverableErrorsInThisFunction())
12333     DiscardCleanupsInEvaluationContext();
12334   assert(!Cleanup.exprNeedsCleanups() &&
12335          "cleanups within block not correctly bound!");
12336   PopExpressionEvaluationContext();
12337 
12338   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12339 
12340   if (BSI->HasImplicitReturnType)
12341     deduceClosureReturnType(*BSI);
12342 
12343   PopDeclContext();
12344 
12345   QualType RetTy = Context.VoidTy;
12346   if (!BSI->ReturnType.isNull())
12347     RetTy = BSI->ReturnType;
12348 
12349   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12350   QualType BlockTy;
12351 
12352   // Set the captured variables on the block.
12353   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12354   SmallVector<BlockDecl::Capture, 4> Captures;
12355   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12356     if (Cap.isThisCapture())
12357       continue;
12358     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12359                               Cap.isNested(), Cap.getInitExpr());
12360     Captures.push_back(NewCap);
12361   }
12362   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12363 
12364   // If the user wrote a function type in some form, try to use that.
12365   if (!BSI->FunctionType.isNull()) {
12366     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12367 
12368     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12369     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12370 
12371     // Turn protoless block types into nullary block types.
12372     if (isa<FunctionNoProtoType>(FTy)) {
12373       FunctionProtoType::ExtProtoInfo EPI;
12374       EPI.ExtInfo = Ext;
12375       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12376 
12377     // Otherwise, if we don't need to change anything about the function type,
12378     // preserve its sugar structure.
12379     } else if (FTy->getReturnType() == RetTy &&
12380                (!NoReturn || FTy->getNoReturnAttr())) {
12381       BlockTy = BSI->FunctionType;
12382 
12383     // Otherwise, make the minimal modifications to the function type.
12384     } else {
12385       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12386       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12387       EPI.TypeQuals = 0; // FIXME: silently?
12388       EPI.ExtInfo = Ext;
12389       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12390     }
12391 
12392   // If we don't have a function type, just build one from nothing.
12393   } else {
12394     FunctionProtoType::ExtProtoInfo EPI;
12395     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12396     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12397   }
12398 
12399   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12400   BlockTy = Context.getBlockPointerType(BlockTy);
12401 
12402   // If needed, diagnose invalid gotos and switches in the block.
12403   if (getCurFunction()->NeedsScopeChecking() &&
12404       !PP.isCodeCompletionEnabled())
12405     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12406 
12407   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12408 
12409   // Try to apply the named return value optimization. We have to check again
12410   // if we can do this, though, because blocks keep return statements around
12411   // to deduce an implicit return type.
12412   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12413       !BSI->TheDecl->isDependentContext())
12414     computeNRVO(Body, BSI);
12415 
12416   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12417   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12418   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12419 
12420   // If the block isn't obviously global, i.e. it captures anything at
12421   // all, then we need to do a few things in the surrounding context:
12422   if (Result->getBlockDecl()->hasCaptures()) {
12423     // First, this expression has a new cleanup object.
12424     ExprCleanupObjects.push_back(Result->getBlockDecl());
12425     Cleanup.setExprNeedsCleanups(true);
12426 
12427     // It also gets a branch-protected scope if any of the captured
12428     // variables needs destruction.
12429     for (const auto &CI : Result->getBlockDecl()->captures()) {
12430       const VarDecl *var = CI.getVariable();
12431       if (var->getType().isDestructedType() != QualType::DK_none) {
12432         getCurFunction()->setHasBranchProtectedScope();
12433         break;
12434       }
12435     }
12436   }
12437 
12438   return Result;
12439 }
12440 
12441 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12442                             SourceLocation RPLoc) {
12443   TypeSourceInfo *TInfo;
12444   GetTypeFromParser(Ty, &TInfo);
12445   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12446 }
12447 
12448 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12449                                 Expr *E, TypeSourceInfo *TInfo,
12450                                 SourceLocation RPLoc) {
12451   Expr *OrigExpr = E;
12452   bool IsMS = false;
12453 
12454   // CUDA device code does not support varargs.
12455   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12456     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12457       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12458       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12459         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12460     }
12461   }
12462 
12463   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12464   // as Microsoft ABI on an actual Microsoft platform, where
12465   // __builtin_ms_va_list and __builtin_va_list are the same.)
12466   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12467       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12468     QualType MSVaListType = Context.getBuiltinMSVaListType();
12469     if (Context.hasSameType(MSVaListType, E->getType())) {
12470       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12471         return ExprError();
12472       IsMS = true;
12473     }
12474   }
12475 
12476   // Get the va_list type
12477   QualType VaListType = Context.getBuiltinVaListType();
12478   if (!IsMS) {
12479     if (VaListType->isArrayType()) {
12480       // Deal with implicit array decay; for example, on x86-64,
12481       // va_list is an array, but it's supposed to decay to
12482       // a pointer for va_arg.
12483       VaListType = Context.getArrayDecayedType(VaListType);
12484       // Make sure the input expression also decays appropriately.
12485       ExprResult Result = UsualUnaryConversions(E);
12486       if (Result.isInvalid())
12487         return ExprError();
12488       E = Result.get();
12489     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12490       // If va_list is a record type and we are compiling in C++ mode,
12491       // check the argument using reference binding.
12492       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12493           Context, Context.getLValueReferenceType(VaListType), false);
12494       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12495       if (Init.isInvalid())
12496         return ExprError();
12497       E = Init.getAs<Expr>();
12498     } else {
12499       // Otherwise, the va_list argument must be an l-value because
12500       // it is modified by va_arg.
12501       if (!E->isTypeDependent() &&
12502           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12503         return ExprError();
12504     }
12505   }
12506 
12507   if (!IsMS && !E->isTypeDependent() &&
12508       !Context.hasSameType(VaListType, E->getType()))
12509     return ExprError(Diag(E->getLocStart(),
12510                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12511       << OrigExpr->getType() << E->getSourceRange());
12512 
12513   if (!TInfo->getType()->isDependentType()) {
12514     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12515                             diag::err_second_parameter_to_va_arg_incomplete,
12516                             TInfo->getTypeLoc()))
12517       return ExprError();
12518 
12519     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12520                                TInfo->getType(),
12521                                diag::err_second_parameter_to_va_arg_abstract,
12522                                TInfo->getTypeLoc()))
12523       return ExprError();
12524 
12525     if (!TInfo->getType().isPODType(Context)) {
12526       Diag(TInfo->getTypeLoc().getBeginLoc(),
12527            TInfo->getType()->isObjCLifetimeType()
12528              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12529              : diag::warn_second_parameter_to_va_arg_not_pod)
12530         << TInfo->getType()
12531         << TInfo->getTypeLoc().getSourceRange();
12532     }
12533 
12534     // Check for va_arg where arguments of the given type will be promoted
12535     // (i.e. this va_arg is guaranteed to have undefined behavior).
12536     QualType PromoteType;
12537     if (TInfo->getType()->isPromotableIntegerType()) {
12538       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12539       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12540         PromoteType = QualType();
12541     }
12542     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12543       PromoteType = Context.DoubleTy;
12544     if (!PromoteType.isNull())
12545       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12546                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12547                           << TInfo->getType()
12548                           << PromoteType
12549                           << TInfo->getTypeLoc().getSourceRange());
12550   }
12551 
12552   QualType T = TInfo->getType().getNonLValueExprType(Context);
12553   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12554 }
12555 
12556 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12557   // The type of __null will be int or long, depending on the size of
12558   // pointers on the target.
12559   QualType Ty;
12560   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12561   if (pw == Context.getTargetInfo().getIntWidth())
12562     Ty = Context.IntTy;
12563   else if (pw == Context.getTargetInfo().getLongWidth())
12564     Ty = Context.LongTy;
12565   else if (pw == Context.getTargetInfo().getLongLongWidth())
12566     Ty = Context.LongLongTy;
12567   else {
12568     llvm_unreachable("I don't know size of pointer!");
12569   }
12570 
12571   return new (Context) GNUNullExpr(Ty, TokenLoc);
12572 }
12573 
12574 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12575                                               bool Diagnose) {
12576   if (!getLangOpts().ObjC1)
12577     return false;
12578 
12579   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12580   if (!PT)
12581     return false;
12582 
12583   if (!PT->isObjCIdType()) {
12584     // Check if the destination is the 'NSString' interface.
12585     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12586     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12587       return false;
12588   }
12589 
12590   // Ignore any parens, implicit casts (should only be
12591   // array-to-pointer decays), and not-so-opaque values.  The last is
12592   // important for making this trigger for property assignments.
12593   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12594   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12595     if (OV->getSourceExpr())
12596       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12597 
12598   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12599   if (!SL || !SL->isAscii())
12600     return false;
12601   if (Diagnose) {
12602     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12603       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12604     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12605   }
12606   return true;
12607 }
12608 
12609 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12610                                               const Expr *SrcExpr) {
12611   if (!DstType->isFunctionPointerType() ||
12612       !SrcExpr->getType()->isFunctionType())
12613     return false;
12614 
12615   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12616   if (!DRE)
12617     return false;
12618 
12619   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12620   if (!FD)
12621     return false;
12622 
12623   return !S.checkAddressOfFunctionIsAvailable(FD,
12624                                               /*Complain=*/true,
12625                                               SrcExpr->getLocStart());
12626 }
12627 
12628 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12629                                     SourceLocation Loc,
12630                                     QualType DstType, QualType SrcType,
12631                                     Expr *SrcExpr, AssignmentAction Action,
12632                                     bool *Complained) {
12633   if (Complained)
12634     *Complained = false;
12635 
12636   // Decode the result (notice that AST's are still created for extensions).
12637   bool CheckInferredResultType = false;
12638   bool isInvalid = false;
12639   unsigned DiagKind = 0;
12640   FixItHint Hint;
12641   ConversionFixItGenerator ConvHints;
12642   bool MayHaveConvFixit = false;
12643   bool MayHaveFunctionDiff = false;
12644   const ObjCInterfaceDecl *IFace = nullptr;
12645   const ObjCProtocolDecl *PDecl = nullptr;
12646 
12647   switch (ConvTy) {
12648   case Compatible:
12649       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12650       return false;
12651 
12652   case PointerToInt:
12653     DiagKind = diag::ext_typecheck_convert_pointer_int;
12654     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12655     MayHaveConvFixit = true;
12656     break;
12657   case IntToPointer:
12658     DiagKind = diag::ext_typecheck_convert_int_pointer;
12659     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12660     MayHaveConvFixit = true;
12661     break;
12662   case IncompatiblePointer:
12663     if (Action == AA_Passing_CFAudited)
12664       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12665     else if (SrcType->isFunctionPointerType() &&
12666              DstType->isFunctionPointerType())
12667       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12668     else
12669       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12670 
12671     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12672       SrcType->isObjCObjectPointerType();
12673     if (Hint.isNull() && !CheckInferredResultType) {
12674       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12675     }
12676     else if (CheckInferredResultType) {
12677       SrcType = SrcType.getUnqualifiedType();
12678       DstType = DstType.getUnqualifiedType();
12679     }
12680     MayHaveConvFixit = true;
12681     break;
12682   case IncompatiblePointerSign:
12683     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12684     break;
12685   case FunctionVoidPointer:
12686     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12687     break;
12688   case IncompatiblePointerDiscardsQualifiers: {
12689     // Perform array-to-pointer decay if necessary.
12690     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12691 
12692     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12693     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12694     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12695       DiagKind = diag::err_typecheck_incompatible_address_space;
12696       break;
12697 
12698 
12699     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12700       DiagKind = diag::err_typecheck_incompatible_ownership;
12701       break;
12702     }
12703 
12704     llvm_unreachable("unknown error case for discarding qualifiers!");
12705     // fallthrough
12706   }
12707   case CompatiblePointerDiscardsQualifiers:
12708     // If the qualifiers lost were because we were applying the
12709     // (deprecated) C++ conversion from a string literal to a char*
12710     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12711     // Ideally, this check would be performed in
12712     // checkPointerTypesForAssignment. However, that would require a
12713     // bit of refactoring (so that the second argument is an
12714     // expression, rather than a type), which should be done as part
12715     // of a larger effort to fix checkPointerTypesForAssignment for
12716     // C++ semantics.
12717     if (getLangOpts().CPlusPlus &&
12718         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12719       return false;
12720     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12721     break;
12722   case IncompatibleNestedPointerQualifiers:
12723     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12724     break;
12725   case IntToBlockPointer:
12726     DiagKind = diag::err_int_to_block_pointer;
12727     break;
12728   case IncompatibleBlockPointer:
12729     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12730     break;
12731   case IncompatibleObjCQualifiedId: {
12732     if (SrcType->isObjCQualifiedIdType()) {
12733       const ObjCObjectPointerType *srcOPT =
12734                 SrcType->getAs<ObjCObjectPointerType>();
12735       for (auto *srcProto : srcOPT->quals()) {
12736         PDecl = srcProto;
12737         break;
12738       }
12739       if (const ObjCInterfaceType *IFaceT =
12740             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12741         IFace = IFaceT->getDecl();
12742     }
12743     else if (DstType->isObjCQualifiedIdType()) {
12744       const ObjCObjectPointerType *dstOPT =
12745         DstType->getAs<ObjCObjectPointerType>();
12746       for (auto *dstProto : dstOPT->quals()) {
12747         PDecl = dstProto;
12748         break;
12749       }
12750       if (const ObjCInterfaceType *IFaceT =
12751             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12752         IFace = IFaceT->getDecl();
12753     }
12754     DiagKind = diag::warn_incompatible_qualified_id;
12755     break;
12756   }
12757   case IncompatibleVectors:
12758     DiagKind = diag::warn_incompatible_vectors;
12759     break;
12760   case IncompatibleObjCWeakRef:
12761     DiagKind = diag::err_arc_weak_unavailable_assign;
12762     break;
12763   case Incompatible:
12764     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12765       if (Complained)
12766         *Complained = true;
12767       return true;
12768     }
12769 
12770     DiagKind = diag::err_typecheck_convert_incompatible;
12771     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12772     MayHaveConvFixit = true;
12773     isInvalid = true;
12774     MayHaveFunctionDiff = true;
12775     break;
12776   }
12777 
12778   QualType FirstType, SecondType;
12779   switch (Action) {
12780   case AA_Assigning:
12781   case AA_Initializing:
12782     // The destination type comes first.
12783     FirstType = DstType;
12784     SecondType = SrcType;
12785     break;
12786 
12787   case AA_Returning:
12788   case AA_Passing:
12789   case AA_Passing_CFAudited:
12790   case AA_Converting:
12791   case AA_Sending:
12792   case AA_Casting:
12793     // The source type comes first.
12794     FirstType = SrcType;
12795     SecondType = DstType;
12796     break;
12797   }
12798 
12799   PartialDiagnostic FDiag = PDiag(DiagKind);
12800   if (Action == AA_Passing_CFAudited)
12801     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12802   else
12803     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12804 
12805   // If we can fix the conversion, suggest the FixIts.
12806   assert(ConvHints.isNull() || Hint.isNull());
12807   if (!ConvHints.isNull()) {
12808     for (FixItHint &H : ConvHints.Hints)
12809       FDiag << H;
12810   } else {
12811     FDiag << Hint;
12812   }
12813   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12814 
12815   if (MayHaveFunctionDiff)
12816     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12817 
12818   Diag(Loc, FDiag);
12819   if (DiagKind == diag::warn_incompatible_qualified_id &&
12820       PDecl && IFace && !IFace->hasDefinition())
12821       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12822         << IFace->getName() << PDecl->getName();
12823 
12824   if (SecondType == Context.OverloadTy)
12825     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12826                               FirstType, /*TakingAddress=*/true);
12827 
12828   if (CheckInferredResultType)
12829     EmitRelatedResultTypeNote(SrcExpr);
12830 
12831   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12832     EmitRelatedResultTypeNoteForReturn(DstType);
12833 
12834   if (Complained)
12835     *Complained = true;
12836   return isInvalid;
12837 }
12838 
12839 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12840                                                  llvm::APSInt *Result) {
12841   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12842   public:
12843     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12844       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12845     }
12846   } Diagnoser;
12847 
12848   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12849 }
12850 
12851 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12852                                                  llvm::APSInt *Result,
12853                                                  unsigned DiagID,
12854                                                  bool AllowFold) {
12855   class IDDiagnoser : public VerifyICEDiagnoser {
12856     unsigned DiagID;
12857 
12858   public:
12859     IDDiagnoser(unsigned DiagID)
12860       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12861 
12862     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12863       S.Diag(Loc, DiagID) << SR;
12864     }
12865   } Diagnoser(DiagID);
12866 
12867   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12868 }
12869 
12870 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12871                                             SourceRange SR) {
12872   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12873 }
12874 
12875 ExprResult
12876 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12877                                       VerifyICEDiagnoser &Diagnoser,
12878                                       bool AllowFold) {
12879   SourceLocation DiagLoc = E->getLocStart();
12880 
12881   if (getLangOpts().CPlusPlus11) {
12882     // C++11 [expr.const]p5:
12883     //   If an expression of literal class type is used in a context where an
12884     //   integral constant expression is required, then that class type shall
12885     //   have a single non-explicit conversion function to an integral or
12886     //   unscoped enumeration type
12887     ExprResult Converted;
12888     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12889     public:
12890       CXX11ConvertDiagnoser(bool Silent)
12891           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12892                                 Silent, true) {}
12893 
12894       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12895                                            QualType T) override {
12896         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12897       }
12898 
12899       SemaDiagnosticBuilder diagnoseIncomplete(
12900           Sema &S, SourceLocation Loc, QualType T) override {
12901         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12902       }
12903 
12904       SemaDiagnosticBuilder diagnoseExplicitConv(
12905           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12906         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12907       }
12908 
12909       SemaDiagnosticBuilder noteExplicitConv(
12910           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12911         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12912                  << ConvTy->isEnumeralType() << ConvTy;
12913       }
12914 
12915       SemaDiagnosticBuilder diagnoseAmbiguous(
12916           Sema &S, SourceLocation Loc, QualType T) override {
12917         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12918       }
12919 
12920       SemaDiagnosticBuilder noteAmbiguous(
12921           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12922         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12923                  << ConvTy->isEnumeralType() << ConvTy;
12924       }
12925 
12926       SemaDiagnosticBuilder diagnoseConversion(
12927           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12928         llvm_unreachable("conversion functions are permitted");
12929       }
12930     } ConvertDiagnoser(Diagnoser.Suppress);
12931 
12932     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12933                                                     ConvertDiagnoser);
12934     if (Converted.isInvalid())
12935       return Converted;
12936     E = Converted.get();
12937     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12938       return ExprError();
12939   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12940     // An ICE must be of integral or unscoped enumeration type.
12941     if (!Diagnoser.Suppress)
12942       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12943     return ExprError();
12944   }
12945 
12946   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12947   // in the non-ICE case.
12948   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12949     if (Result)
12950       *Result = E->EvaluateKnownConstInt(Context);
12951     return E;
12952   }
12953 
12954   Expr::EvalResult EvalResult;
12955   SmallVector<PartialDiagnosticAt, 8> Notes;
12956   EvalResult.Diag = &Notes;
12957 
12958   // Try to evaluate the expression, and produce diagnostics explaining why it's
12959   // not a constant expression as a side-effect.
12960   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12961                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12962 
12963   // In C++11, we can rely on diagnostics being produced for any expression
12964   // which is not a constant expression. If no diagnostics were produced, then
12965   // this is a constant expression.
12966   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12967     if (Result)
12968       *Result = EvalResult.Val.getInt();
12969     return E;
12970   }
12971 
12972   // If our only note is the usual "invalid subexpression" note, just point
12973   // the caret at its location rather than producing an essentially
12974   // redundant note.
12975   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12976         diag::note_invalid_subexpr_in_const_expr) {
12977     DiagLoc = Notes[0].first;
12978     Notes.clear();
12979   }
12980 
12981   if (!Folded || !AllowFold) {
12982     if (!Diagnoser.Suppress) {
12983       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12984       for (const PartialDiagnosticAt &Note : Notes)
12985         Diag(Note.first, Note.second);
12986     }
12987 
12988     return ExprError();
12989   }
12990 
12991   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12992   for (const PartialDiagnosticAt &Note : Notes)
12993     Diag(Note.first, Note.second);
12994 
12995   if (Result)
12996     *Result = EvalResult.Val.getInt();
12997   return E;
12998 }
12999 
13000 namespace {
13001   // Handle the case where we conclude a expression which we speculatively
13002   // considered to be unevaluated is actually evaluated.
13003   class TransformToPE : public TreeTransform<TransformToPE> {
13004     typedef TreeTransform<TransformToPE> BaseTransform;
13005 
13006   public:
13007     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13008 
13009     // Make sure we redo semantic analysis
13010     bool AlwaysRebuild() { return true; }
13011 
13012     // Make sure we handle LabelStmts correctly.
13013     // FIXME: This does the right thing, but maybe we need a more general
13014     // fix to TreeTransform?
13015     StmtResult TransformLabelStmt(LabelStmt *S) {
13016       S->getDecl()->setStmt(nullptr);
13017       return BaseTransform::TransformLabelStmt(S);
13018     }
13019 
13020     // We need to special-case DeclRefExprs referring to FieldDecls which
13021     // are not part of a member pointer formation; normal TreeTransforming
13022     // doesn't catch this case because of the way we represent them in the AST.
13023     // FIXME: This is a bit ugly; is it really the best way to handle this
13024     // case?
13025     //
13026     // Error on DeclRefExprs referring to FieldDecls.
13027     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13028       if (isa<FieldDecl>(E->getDecl()) &&
13029           !SemaRef.isUnevaluatedContext())
13030         return SemaRef.Diag(E->getLocation(),
13031                             diag::err_invalid_non_static_member_use)
13032             << E->getDecl() << E->getSourceRange();
13033 
13034       return BaseTransform::TransformDeclRefExpr(E);
13035     }
13036 
13037     // Exception: filter out member pointer formation
13038     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13039       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13040         return E;
13041 
13042       return BaseTransform::TransformUnaryOperator(E);
13043     }
13044 
13045     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13046       // Lambdas never need to be transformed.
13047       return E;
13048     }
13049   };
13050 }
13051 
13052 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13053   assert(isUnevaluatedContext() &&
13054          "Should only transform unevaluated expressions");
13055   ExprEvalContexts.back().Context =
13056       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13057   if (isUnevaluatedContext())
13058     return E;
13059   return TransformToPE(*this).TransformExpr(E);
13060 }
13061 
13062 void
13063 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13064                                       Decl *LambdaContextDecl,
13065                                       bool IsDecltype) {
13066   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13067                                 LambdaContextDecl, IsDecltype);
13068   Cleanup.reset();
13069   if (!MaybeODRUseExprs.empty())
13070     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13071 }
13072 
13073 void
13074 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13075                                       ReuseLambdaContextDecl_t,
13076                                       bool IsDecltype) {
13077   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13078   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13079 }
13080 
13081 void Sema::PopExpressionEvaluationContext() {
13082   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13083   unsigned NumTypos = Rec.NumTypos;
13084 
13085   if (!Rec.Lambdas.empty()) {
13086     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13087       unsigned D;
13088       if (Rec.isUnevaluated()) {
13089         // C++11 [expr.prim.lambda]p2:
13090         //   A lambda-expression shall not appear in an unevaluated operand
13091         //   (Clause 5).
13092         D = diag::err_lambda_unevaluated_operand;
13093       } else {
13094         // C++1y [expr.const]p2:
13095         //   A conditional-expression e is a core constant expression unless the
13096         //   evaluation of e, following the rules of the abstract machine, would
13097         //   evaluate [...] a lambda-expression.
13098         D = diag::err_lambda_in_constant_expression;
13099       }
13100       for (const auto *L : Rec.Lambdas)
13101         Diag(L->getLocStart(), D);
13102     } else {
13103       // Mark the capture expressions odr-used. This was deferred
13104       // during lambda expression creation.
13105       for (auto *Lambda : Rec.Lambdas) {
13106         for (auto *C : Lambda->capture_inits())
13107           MarkDeclarationsReferencedInExpr(C);
13108       }
13109     }
13110   }
13111 
13112   // When are coming out of an unevaluated context, clear out any
13113   // temporaries that we may have created as part of the evaluation of
13114   // the expression in that context: they aren't relevant because they
13115   // will never be constructed.
13116   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13117     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13118                              ExprCleanupObjects.end());
13119     Cleanup = Rec.ParentCleanup;
13120     CleanupVarDeclMarking();
13121     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13122   // Otherwise, merge the contexts together.
13123   } else {
13124     Cleanup.mergeFrom(Rec.ParentCleanup);
13125     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13126                             Rec.SavedMaybeODRUseExprs.end());
13127   }
13128 
13129   // Pop the current expression evaluation context off the stack.
13130   ExprEvalContexts.pop_back();
13131 
13132   if (!ExprEvalContexts.empty())
13133     ExprEvalContexts.back().NumTypos += NumTypos;
13134   else
13135     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13136                             "last ExpressionEvaluationContextRecord");
13137 }
13138 
13139 void Sema::DiscardCleanupsInEvaluationContext() {
13140   ExprCleanupObjects.erase(
13141          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13142          ExprCleanupObjects.end());
13143   Cleanup.reset();
13144   MaybeODRUseExprs.clear();
13145 }
13146 
13147 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13148   if (!E->getType()->isVariablyModifiedType())
13149     return E;
13150   return TransformToPotentiallyEvaluated(E);
13151 }
13152 
13153 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13154   // Do not mark anything as "used" within a dependent context; wait for
13155   // an instantiation.
13156   if (SemaRef.CurContext->isDependentContext())
13157     return false;
13158 
13159   switch (SemaRef.ExprEvalContexts.back().Context) {
13160     case Sema::Unevaluated:
13161     case Sema::UnevaluatedAbstract:
13162       // We are in an expression that is not potentially evaluated; do nothing.
13163       // (Depending on how you read the standard, we actually do need to do
13164       // something here for null pointer constants, but the standard's
13165       // definition of a null pointer constant is completely crazy.)
13166       return false;
13167 
13168     case Sema::DiscardedStatement:
13169       // These are technically a potentially evaluated but they have the effect
13170       // of suppressing use marking.
13171       return false;
13172 
13173     case Sema::ConstantEvaluated:
13174     case Sema::PotentiallyEvaluated:
13175       // We are in a potentially evaluated expression (or a constant-expression
13176       // in C++03); we need to do implicit template instantiation, implicitly
13177       // define class members, and mark most declarations as used.
13178       return true;
13179 
13180     case Sema::PotentiallyEvaluatedIfUsed:
13181       // Referenced declarations will only be used if the construct in the
13182       // containing expression is used.
13183       return false;
13184   }
13185   llvm_unreachable("Invalid context");
13186 }
13187 
13188 /// \brief Mark a function referenced, and check whether it is odr-used
13189 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13190 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13191                                   bool MightBeOdrUse) {
13192   assert(Func && "No function?");
13193 
13194   Func->setReferenced();
13195 
13196   // C++11 [basic.def.odr]p3:
13197   //   A function whose name appears as a potentially-evaluated expression is
13198   //   odr-used if it is the unique lookup result or the selected member of a
13199   //   set of overloaded functions [...].
13200   //
13201   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13202   // can just check that here.
13203   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13204 
13205   // Determine whether we require a function definition to exist, per
13206   // C++11 [temp.inst]p3:
13207   //   Unless a function template specialization has been explicitly
13208   //   instantiated or explicitly specialized, the function template
13209   //   specialization is implicitly instantiated when the specialization is
13210   //   referenced in a context that requires a function definition to exist.
13211   //
13212   // We consider constexpr function templates to be referenced in a context
13213   // that requires a definition to exist whenever they are referenced.
13214   //
13215   // FIXME: This instantiates constexpr functions too frequently. If this is
13216   // really an unevaluated context (and we're not just in the definition of a
13217   // function template or overload resolution or other cases which we
13218   // incorrectly consider to be unevaluated contexts), and we're not in a
13219   // subexpression which we actually need to evaluate (for instance, a
13220   // template argument, array bound or an expression in a braced-init-list),
13221   // we are not permitted to instantiate this constexpr function definition.
13222   //
13223   // FIXME: This also implicitly defines special members too frequently. They
13224   // are only supposed to be implicitly defined if they are odr-used, but they
13225   // are not odr-used from constant expressions in unevaluated contexts.
13226   // However, they cannot be referenced if they are deleted, and they are
13227   // deleted whenever the implicit definition of the special member would
13228   // fail (with very few exceptions).
13229   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13230   bool NeedDefinition =
13231       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13232                                          (MD && !MD->isUserProvided())));
13233 
13234   // C++14 [temp.expl.spec]p6:
13235   //   If a template [...] is explicitly specialized then that specialization
13236   //   shall be declared before the first use of that specialization that would
13237   //   cause an implicit instantiation to take place, in every translation unit
13238   //   in which such a use occurs
13239   if (NeedDefinition &&
13240       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13241        Func->getMemberSpecializationInfo()))
13242     checkSpecializationVisibility(Loc, Func);
13243 
13244   // C++14 [except.spec]p17:
13245   //   An exception-specification is considered to be needed when:
13246   //   - the function is odr-used or, if it appears in an unevaluated operand,
13247   //     would be odr-used if the expression were potentially-evaluated;
13248   //
13249   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13250   // function is a pure virtual function we're calling, and in that case the
13251   // function was selected by overload resolution and we need to resolve its
13252   // exception specification for a different reason.
13253   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13254   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13255     ResolveExceptionSpec(Loc, FPT);
13256 
13257   // If we don't need to mark the function as used, and we don't need to
13258   // try to provide a definition, there's nothing more to do.
13259   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13260       (!NeedDefinition || Func->getBody()))
13261     return;
13262 
13263   // Note that this declaration has been used.
13264   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13265     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13266     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13267       if (Constructor->isDefaultConstructor()) {
13268         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13269           return;
13270         DefineImplicitDefaultConstructor(Loc, Constructor);
13271       } else if (Constructor->isCopyConstructor()) {
13272         DefineImplicitCopyConstructor(Loc, Constructor);
13273       } else if (Constructor->isMoveConstructor()) {
13274         DefineImplicitMoveConstructor(Loc, Constructor);
13275       }
13276     } else if (Constructor->getInheritedConstructor()) {
13277       DefineInheritingConstructor(Loc, Constructor);
13278     }
13279   } else if (CXXDestructorDecl *Destructor =
13280                  dyn_cast<CXXDestructorDecl>(Func)) {
13281     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13282     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13283       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13284         return;
13285       DefineImplicitDestructor(Loc, Destructor);
13286     }
13287     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13288       MarkVTableUsed(Loc, Destructor->getParent());
13289   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13290     if (MethodDecl->isOverloadedOperator() &&
13291         MethodDecl->getOverloadedOperator() == OO_Equal) {
13292       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13293       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13294         if (MethodDecl->isCopyAssignmentOperator())
13295           DefineImplicitCopyAssignment(Loc, MethodDecl);
13296         else if (MethodDecl->isMoveAssignmentOperator())
13297           DefineImplicitMoveAssignment(Loc, MethodDecl);
13298       }
13299     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13300                MethodDecl->getParent()->isLambda()) {
13301       CXXConversionDecl *Conversion =
13302           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13303       if (Conversion->isLambdaToBlockPointerConversion())
13304         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13305       else
13306         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13307     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13308       MarkVTableUsed(Loc, MethodDecl->getParent());
13309   }
13310 
13311   // Recursive functions should be marked when used from another function.
13312   // FIXME: Is this really right?
13313   if (CurContext == Func) return;
13314 
13315   // Implicit instantiation of function templates and member functions of
13316   // class templates.
13317   if (Func->isImplicitlyInstantiable()) {
13318     bool AlreadyInstantiated = false;
13319     SourceLocation PointOfInstantiation = Loc;
13320     if (FunctionTemplateSpecializationInfo *SpecInfo
13321                               = Func->getTemplateSpecializationInfo()) {
13322       if (SpecInfo->getPointOfInstantiation().isInvalid())
13323         SpecInfo->setPointOfInstantiation(Loc);
13324       else if (SpecInfo->getTemplateSpecializationKind()
13325                  == TSK_ImplicitInstantiation) {
13326         AlreadyInstantiated = true;
13327         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13328       }
13329     } else if (MemberSpecializationInfo *MSInfo
13330                                 = Func->getMemberSpecializationInfo()) {
13331       if (MSInfo->getPointOfInstantiation().isInvalid())
13332         MSInfo->setPointOfInstantiation(Loc);
13333       else if (MSInfo->getTemplateSpecializationKind()
13334                  == TSK_ImplicitInstantiation) {
13335         AlreadyInstantiated = true;
13336         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13337       }
13338     }
13339 
13340     if (!AlreadyInstantiated || Func->isConstexpr()) {
13341       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13342           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13343           ActiveTemplateInstantiations.size())
13344         PendingLocalImplicitInstantiations.push_back(
13345             std::make_pair(Func, PointOfInstantiation));
13346       else if (Func->isConstexpr())
13347         // Do not defer instantiations of constexpr functions, to avoid the
13348         // expression evaluator needing to call back into Sema if it sees a
13349         // call to such a function.
13350         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13351       else {
13352         PendingInstantiations.push_back(std::make_pair(Func,
13353                                                        PointOfInstantiation));
13354         // Notify the consumer that a function was implicitly instantiated.
13355         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13356       }
13357     }
13358   } else {
13359     // Walk redefinitions, as some of them may be instantiable.
13360     for (auto i : Func->redecls()) {
13361       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13362         MarkFunctionReferenced(Loc, i, OdrUse);
13363     }
13364   }
13365 
13366   if (!OdrUse) return;
13367 
13368   // Keep track of used but undefined functions.
13369   if (!Func->isDefined()) {
13370     if (mightHaveNonExternalLinkage(Func))
13371       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13372     else if (Func->getMostRecentDecl()->isInlined() &&
13373              !LangOpts.GNUInline &&
13374              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13375       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13376   }
13377 
13378   Func->markUsed(Context);
13379 }
13380 
13381 static void
13382 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13383                                    ValueDecl *var, DeclContext *DC) {
13384   DeclContext *VarDC = var->getDeclContext();
13385 
13386   //  If the parameter still belongs to the translation unit, then
13387   //  we're actually just using one parameter in the declaration of
13388   //  the next.
13389   if (isa<ParmVarDecl>(var) &&
13390       isa<TranslationUnitDecl>(VarDC))
13391     return;
13392 
13393   // For C code, don't diagnose about capture if we're not actually in code
13394   // right now; it's impossible to write a non-constant expression outside of
13395   // function context, so we'll get other (more useful) diagnostics later.
13396   //
13397   // For C++, things get a bit more nasty... it would be nice to suppress this
13398   // diagnostic for certain cases like using a local variable in an array bound
13399   // for a member of a local class, but the correct predicate is not obvious.
13400   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13401     return;
13402 
13403   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13404   unsigned ContextKind = 3; // unknown
13405   if (isa<CXXMethodDecl>(VarDC) &&
13406       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13407     ContextKind = 2;
13408   } else if (isa<FunctionDecl>(VarDC)) {
13409     ContextKind = 0;
13410   } else if (isa<BlockDecl>(VarDC)) {
13411     ContextKind = 1;
13412   }
13413 
13414   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13415     << var << ValueKind << ContextKind << VarDC;
13416   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13417       << var;
13418 
13419   // FIXME: Add additional diagnostic info about class etc. which prevents
13420   // capture.
13421 }
13422 
13423 
13424 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13425                                       bool &SubCapturesAreNested,
13426                                       QualType &CaptureType,
13427                                       QualType &DeclRefType) {
13428    // Check whether we've already captured it.
13429   if (CSI->CaptureMap.count(Var)) {
13430     // If we found a capture, any subcaptures are nested.
13431     SubCapturesAreNested = true;
13432 
13433     // Retrieve the capture type for this variable.
13434     CaptureType = CSI->getCapture(Var).getCaptureType();
13435 
13436     // Compute the type of an expression that refers to this variable.
13437     DeclRefType = CaptureType.getNonReferenceType();
13438 
13439     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13440     // are mutable in the sense that user can change their value - they are
13441     // private instances of the captured declarations.
13442     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13443     if (Cap.isCopyCapture() &&
13444         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13445         !(isa<CapturedRegionScopeInfo>(CSI) &&
13446           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13447       DeclRefType.addConst();
13448     return true;
13449   }
13450   return false;
13451 }
13452 
13453 // Only block literals, captured statements, and lambda expressions can
13454 // capture; other scopes don't work.
13455 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13456                                  SourceLocation Loc,
13457                                  const bool Diagnose, Sema &S) {
13458   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13459     return getLambdaAwareParentOfDeclContext(DC);
13460   else if (Var->hasLocalStorage()) {
13461     if (Diagnose)
13462        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13463   }
13464   return nullptr;
13465 }
13466 
13467 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13468 // certain types of variables (unnamed, variably modified types etc.)
13469 // so check for eligibility.
13470 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13471                                  SourceLocation Loc,
13472                                  const bool Diagnose, Sema &S) {
13473 
13474   bool IsBlock = isa<BlockScopeInfo>(CSI);
13475   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13476 
13477   // Lambdas are not allowed to capture unnamed variables
13478   // (e.g. anonymous unions).
13479   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13480   // assuming that's the intent.
13481   if (IsLambda && !Var->getDeclName()) {
13482     if (Diagnose) {
13483       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13484       S.Diag(Var->getLocation(), diag::note_declared_at);
13485     }
13486     return false;
13487   }
13488 
13489   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13490   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13491     if (Diagnose) {
13492       S.Diag(Loc, diag::err_ref_vm_type);
13493       S.Diag(Var->getLocation(), diag::note_previous_decl)
13494         << Var->getDeclName();
13495     }
13496     return false;
13497   }
13498   // Prohibit structs with flexible array members too.
13499   // We cannot capture what is in the tail end of the struct.
13500   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13501     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13502       if (Diagnose) {
13503         if (IsBlock)
13504           S.Diag(Loc, diag::err_ref_flexarray_type);
13505         else
13506           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13507             << Var->getDeclName();
13508         S.Diag(Var->getLocation(), diag::note_previous_decl)
13509           << Var->getDeclName();
13510       }
13511       return false;
13512     }
13513   }
13514   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13515   // Lambdas and captured statements are not allowed to capture __block
13516   // variables; they don't support the expected semantics.
13517   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13518     if (Diagnose) {
13519       S.Diag(Loc, diag::err_capture_block_variable)
13520         << Var->getDeclName() << !IsLambda;
13521       S.Diag(Var->getLocation(), diag::note_previous_decl)
13522         << Var->getDeclName();
13523     }
13524     return false;
13525   }
13526 
13527   return true;
13528 }
13529 
13530 // Returns true if the capture by block was successful.
13531 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13532                                  SourceLocation Loc,
13533                                  const bool BuildAndDiagnose,
13534                                  QualType &CaptureType,
13535                                  QualType &DeclRefType,
13536                                  const bool Nested,
13537                                  Sema &S) {
13538   Expr *CopyExpr = nullptr;
13539   bool ByRef = false;
13540 
13541   // Blocks are not allowed to capture arrays.
13542   if (CaptureType->isArrayType()) {
13543     if (BuildAndDiagnose) {
13544       S.Diag(Loc, diag::err_ref_array_type);
13545       S.Diag(Var->getLocation(), diag::note_previous_decl)
13546       << Var->getDeclName();
13547     }
13548     return false;
13549   }
13550 
13551   // Forbid the block-capture of autoreleasing variables.
13552   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13553     if (BuildAndDiagnose) {
13554       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13555         << /*block*/ 0;
13556       S.Diag(Var->getLocation(), diag::note_previous_decl)
13557         << Var->getDeclName();
13558     }
13559     return false;
13560   }
13561 
13562   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13563   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13564     QualType PointeeTy = PT->getPointeeType();
13565     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13566         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13567         !isa<AttributedType>(PointeeTy)) {
13568       if (BuildAndDiagnose) {
13569         SourceLocation VarLoc = Var->getLocation();
13570         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13571         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13572             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13573         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13574       }
13575     }
13576   }
13577 
13578   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13579   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13580       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13581     // Block capture by reference does not change the capture or
13582     // declaration reference types.
13583     ByRef = true;
13584   } else {
13585     // Block capture by copy introduces 'const'.
13586     CaptureType = CaptureType.getNonReferenceType().withConst();
13587     DeclRefType = CaptureType;
13588 
13589     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13590       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13591         // The capture logic needs the destructor, so make sure we mark it.
13592         // Usually this is unnecessary because most local variables have
13593         // their destructors marked at declaration time, but parameters are
13594         // an exception because it's technically only the call site that
13595         // actually requires the destructor.
13596         if (isa<ParmVarDecl>(Var))
13597           S.FinalizeVarWithDestructor(Var, Record);
13598 
13599         // Enter a new evaluation context to insulate the copy
13600         // full-expression.
13601         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13602 
13603         // According to the blocks spec, the capture of a variable from
13604         // the stack requires a const copy constructor.  This is not true
13605         // of the copy/move done to move a __block variable to the heap.
13606         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13607                                                   DeclRefType.withConst(),
13608                                                   VK_LValue, Loc);
13609 
13610         ExprResult Result
13611           = S.PerformCopyInitialization(
13612               InitializedEntity::InitializeBlock(Var->getLocation(),
13613                                                   CaptureType, false),
13614               Loc, DeclRef);
13615 
13616         // Build a full-expression copy expression if initialization
13617         // succeeded and used a non-trivial constructor.  Recover from
13618         // errors by pretending that the copy isn't necessary.
13619         if (!Result.isInvalid() &&
13620             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13621                 ->isTrivial()) {
13622           Result = S.MaybeCreateExprWithCleanups(Result);
13623           CopyExpr = Result.get();
13624         }
13625       }
13626     }
13627   }
13628 
13629   // Actually capture the variable.
13630   if (BuildAndDiagnose)
13631     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13632                     SourceLocation(), CaptureType, CopyExpr);
13633 
13634   return true;
13635 
13636 }
13637 
13638 
13639 /// \brief Capture the given variable in the captured region.
13640 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13641                                     VarDecl *Var,
13642                                     SourceLocation Loc,
13643                                     const bool BuildAndDiagnose,
13644                                     QualType &CaptureType,
13645                                     QualType &DeclRefType,
13646                                     const bool RefersToCapturedVariable,
13647                                     Sema &S) {
13648   // By default, capture variables by reference.
13649   bool ByRef = true;
13650   // Using an LValue reference type is consistent with Lambdas (see below).
13651   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13652     if (S.IsOpenMPCapturedDecl(Var))
13653       DeclRefType = DeclRefType.getUnqualifiedType();
13654     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13655   }
13656 
13657   if (ByRef)
13658     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13659   else
13660     CaptureType = DeclRefType;
13661 
13662   Expr *CopyExpr = nullptr;
13663   if (BuildAndDiagnose) {
13664     // The current implementation assumes that all variables are captured
13665     // by references. Since there is no capture by copy, no expression
13666     // evaluation will be needed.
13667     RecordDecl *RD = RSI->TheRecordDecl;
13668 
13669     FieldDecl *Field
13670       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13671                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13672                           nullptr, false, ICIS_NoInit);
13673     Field->setImplicit(true);
13674     Field->setAccess(AS_private);
13675     RD->addDecl(Field);
13676 
13677     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13678                                             DeclRefType, VK_LValue, Loc);
13679     Var->setReferenced(true);
13680     Var->markUsed(S.Context);
13681   }
13682 
13683   // Actually capture the variable.
13684   if (BuildAndDiagnose)
13685     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13686                     SourceLocation(), CaptureType, CopyExpr);
13687 
13688 
13689   return true;
13690 }
13691 
13692 /// \brief Create a field within the lambda class for the variable
13693 /// being captured.
13694 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13695                                     QualType FieldType, QualType DeclRefType,
13696                                     SourceLocation Loc,
13697                                     bool RefersToCapturedVariable) {
13698   CXXRecordDecl *Lambda = LSI->Lambda;
13699 
13700   // Build the non-static data member.
13701   FieldDecl *Field
13702     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13703                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13704                         nullptr, false, ICIS_NoInit);
13705   Field->setImplicit(true);
13706   Field->setAccess(AS_private);
13707   Lambda->addDecl(Field);
13708 }
13709 
13710 /// \brief Capture the given variable in the lambda.
13711 static bool captureInLambda(LambdaScopeInfo *LSI,
13712                             VarDecl *Var,
13713                             SourceLocation Loc,
13714                             const bool BuildAndDiagnose,
13715                             QualType &CaptureType,
13716                             QualType &DeclRefType,
13717                             const bool RefersToCapturedVariable,
13718                             const Sema::TryCaptureKind Kind,
13719                             SourceLocation EllipsisLoc,
13720                             const bool IsTopScope,
13721                             Sema &S) {
13722 
13723   // Determine whether we are capturing by reference or by value.
13724   bool ByRef = false;
13725   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13726     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13727   } else {
13728     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13729   }
13730 
13731   // Compute the type of the field that will capture this variable.
13732   if (ByRef) {
13733     // C++11 [expr.prim.lambda]p15:
13734     //   An entity is captured by reference if it is implicitly or
13735     //   explicitly captured but not captured by copy. It is
13736     //   unspecified whether additional unnamed non-static data
13737     //   members are declared in the closure type for entities
13738     //   captured by reference.
13739     //
13740     // FIXME: It is not clear whether we want to build an lvalue reference
13741     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13742     // to do the former, while EDG does the latter. Core issue 1249 will
13743     // clarify, but for now we follow GCC because it's a more permissive and
13744     // easily defensible position.
13745     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13746   } else {
13747     // C++11 [expr.prim.lambda]p14:
13748     //   For each entity captured by copy, an unnamed non-static
13749     //   data member is declared in the closure type. The
13750     //   declaration order of these members is unspecified. The type
13751     //   of such a data member is the type of the corresponding
13752     //   captured entity if the entity is not a reference to an
13753     //   object, or the referenced type otherwise. [Note: If the
13754     //   captured entity is a reference to a function, the
13755     //   corresponding data member is also a reference to a
13756     //   function. - end note ]
13757     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13758       if (!RefType->getPointeeType()->isFunctionType())
13759         CaptureType = RefType->getPointeeType();
13760     }
13761 
13762     // Forbid the lambda copy-capture of autoreleasing variables.
13763     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13764       if (BuildAndDiagnose) {
13765         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13766         S.Diag(Var->getLocation(), diag::note_previous_decl)
13767           << Var->getDeclName();
13768       }
13769       return false;
13770     }
13771 
13772     // Make sure that by-copy captures are of a complete and non-abstract type.
13773     if (BuildAndDiagnose) {
13774       if (!CaptureType->isDependentType() &&
13775           S.RequireCompleteType(Loc, CaptureType,
13776                                 diag::err_capture_of_incomplete_type,
13777                                 Var->getDeclName()))
13778         return false;
13779 
13780       if (S.RequireNonAbstractType(Loc, CaptureType,
13781                                    diag::err_capture_of_abstract_type))
13782         return false;
13783     }
13784   }
13785 
13786   // Capture this variable in the lambda.
13787   if (BuildAndDiagnose)
13788     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13789                             RefersToCapturedVariable);
13790 
13791   // Compute the type of a reference to this captured variable.
13792   if (ByRef)
13793     DeclRefType = CaptureType.getNonReferenceType();
13794   else {
13795     // C++ [expr.prim.lambda]p5:
13796     //   The closure type for a lambda-expression has a public inline
13797     //   function call operator [...]. This function call operator is
13798     //   declared const (9.3.1) if and only if the lambda-expression's
13799     //   parameter-declaration-clause is not followed by mutable.
13800     DeclRefType = CaptureType.getNonReferenceType();
13801     if (!LSI->Mutable && !CaptureType->isReferenceType())
13802       DeclRefType.addConst();
13803   }
13804 
13805   // Add the capture.
13806   if (BuildAndDiagnose)
13807     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13808                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13809 
13810   return true;
13811 }
13812 
13813 bool Sema::tryCaptureVariable(
13814     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13815     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13816     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13817   // An init-capture is notionally from the context surrounding its
13818   // declaration, but its parent DC is the lambda class.
13819   DeclContext *VarDC = Var->getDeclContext();
13820   if (Var->isInitCapture())
13821     VarDC = VarDC->getParent();
13822 
13823   DeclContext *DC = CurContext;
13824   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13825       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13826   // We need to sync up the Declaration Context with the
13827   // FunctionScopeIndexToStopAt
13828   if (FunctionScopeIndexToStopAt) {
13829     unsigned FSIndex = FunctionScopes.size() - 1;
13830     while (FSIndex != MaxFunctionScopesIndex) {
13831       DC = getLambdaAwareParentOfDeclContext(DC);
13832       --FSIndex;
13833     }
13834   }
13835 
13836 
13837   // If the variable is declared in the current context, there is no need to
13838   // capture it.
13839   if (VarDC == DC) return true;
13840 
13841   // Capture global variables if it is required to use private copy of this
13842   // variable.
13843   bool IsGlobal = !Var->hasLocalStorage();
13844   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13845     return true;
13846 
13847   // Walk up the stack to determine whether we can capture the variable,
13848   // performing the "simple" checks that don't depend on type. We stop when
13849   // we've either hit the declared scope of the variable or find an existing
13850   // capture of that variable.  We start from the innermost capturing-entity
13851   // (the DC) and ensure that all intervening capturing-entities
13852   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13853   // declcontext can either capture the variable or have already captured
13854   // the variable.
13855   CaptureType = Var->getType();
13856   DeclRefType = CaptureType.getNonReferenceType();
13857   bool Nested = false;
13858   bool Explicit = (Kind != TryCapture_Implicit);
13859   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13860   do {
13861     // Only block literals, captured statements, and lambda expressions can
13862     // capture; other scopes don't work.
13863     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13864                                                               ExprLoc,
13865                                                               BuildAndDiagnose,
13866                                                               *this);
13867     // We need to check for the parent *first* because, if we *have*
13868     // private-captured a global variable, we need to recursively capture it in
13869     // intermediate blocks, lambdas, etc.
13870     if (!ParentDC) {
13871       if (IsGlobal) {
13872         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13873         break;
13874       }
13875       return true;
13876     }
13877 
13878     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13879     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13880 
13881 
13882     // Check whether we've already captured it.
13883     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13884                                              DeclRefType))
13885       break;
13886     // If we are instantiating a generic lambda call operator body,
13887     // we do not want to capture new variables.  What was captured
13888     // during either a lambdas transformation or initial parsing
13889     // should be used.
13890     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13891       if (BuildAndDiagnose) {
13892         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13893         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13894           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13895           Diag(Var->getLocation(), diag::note_previous_decl)
13896              << Var->getDeclName();
13897           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13898         } else
13899           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13900       }
13901       return true;
13902     }
13903     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13904     // certain types of variables (unnamed, variably modified types etc.)
13905     // so check for eligibility.
13906     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13907        return true;
13908 
13909     // Try to capture variable-length arrays types.
13910     if (Var->getType()->isVariablyModifiedType()) {
13911       // We're going to walk down into the type and look for VLA
13912       // expressions.
13913       QualType QTy = Var->getType();
13914       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13915         QTy = PVD->getOriginalType();
13916       captureVariablyModifiedType(Context, QTy, CSI);
13917     }
13918 
13919     if (getLangOpts().OpenMP) {
13920       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13921         // OpenMP private variables should not be captured in outer scope, so
13922         // just break here. Similarly, global variables that are captured in a
13923         // target region should not be captured outside the scope of the region.
13924         if (RSI->CapRegionKind == CR_OpenMP) {
13925           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13926           // When we detect target captures we are looking from inside the
13927           // target region, therefore we need to propagate the capture from the
13928           // enclosing region. Therefore, the capture is not initially nested.
13929           if (IsTargetCap)
13930             FunctionScopesIndex--;
13931 
13932           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13933             Nested = !IsTargetCap;
13934             DeclRefType = DeclRefType.getUnqualifiedType();
13935             CaptureType = Context.getLValueReferenceType(DeclRefType);
13936             break;
13937           }
13938         }
13939       }
13940     }
13941     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13942       // No capture-default, and this is not an explicit capture
13943       // so cannot capture this variable.
13944       if (BuildAndDiagnose) {
13945         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13946         Diag(Var->getLocation(), diag::note_previous_decl)
13947           << Var->getDeclName();
13948         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13949           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13950                diag::note_lambda_decl);
13951         // FIXME: If we error out because an outer lambda can not implicitly
13952         // capture a variable that an inner lambda explicitly captures, we
13953         // should have the inner lambda do the explicit capture - because
13954         // it makes for cleaner diagnostics later.  This would purely be done
13955         // so that the diagnostic does not misleadingly claim that a variable
13956         // can not be captured by a lambda implicitly even though it is captured
13957         // explicitly.  Suggestion:
13958         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13959         //    at the function head
13960         //  - cache the StartingDeclContext - this must be a lambda
13961         //  - captureInLambda in the innermost lambda the variable.
13962       }
13963       return true;
13964     }
13965 
13966     FunctionScopesIndex--;
13967     DC = ParentDC;
13968     Explicit = false;
13969   } while (!VarDC->Equals(DC));
13970 
13971   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13972   // computing the type of the capture at each step, checking type-specific
13973   // requirements, and adding captures if requested.
13974   // If the variable had already been captured previously, we start capturing
13975   // at the lambda nested within that one.
13976   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13977        ++I) {
13978     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13979 
13980     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13981       if (!captureInBlock(BSI, Var, ExprLoc,
13982                           BuildAndDiagnose, CaptureType,
13983                           DeclRefType, Nested, *this))
13984         return true;
13985       Nested = true;
13986     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13987       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13988                                    BuildAndDiagnose, CaptureType,
13989                                    DeclRefType, Nested, *this))
13990         return true;
13991       Nested = true;
13992     } else {
13993       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13994       if (!captureInLambda(LSI, Var, ExprLoc,
13995                            BuildAndDiagnose, CaptureType,
13996                            DeclRefType, Nested, Kind, EllipsisLoc,
13997                             /*IsTopScope*/I == N - 1, *this))
13998         return true;
13999       Nested = true;
14000     }
14001   }
14002   return false;
14003 }
14004 
14005 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14006                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14007   QualType CaptureType;
14008   QualType DeclRefType;
14009   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14010                             /*BuildAndDiagnose=*/true, CaptureType,
14011                             DeclRefType, nullptr);
14012 }
14013 
14014 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14015   QualType CaptureType;
14016   QualType DeclRefType;
14017   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14018                              /*BuildAndDiagnose=*/false, CaptureType,
14019                              DeclRefType, nullptr);
14020 }
14021 
14022 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14023   QualType CaptureType;
14024   QualType DeclRefType;
14025 
14026   // Determine whether we can capture this variable.
14027   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14028                          /*BuildAndDiagnose=*/false, CaptureType,
14029                          DeclRefType, nullptr))
14030     return QualType();
14031 
14032   return DeclRefType;
14033 }
14034 
14035 
14036 
14037 // If either the type of the variable or the initializer is dependent,
14038 // return false. Otherwise, determine whether the variable is a constant
14039 // expression. Use this if you need to know if a variable that might or
14040 // might not be dependent is truly a constant expression.
14041 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14042     ASTContext &Context) {
14043 
14044   if (Var->getType()->isDependentType())
14045     return false;
14046   const VarDecl *DefVD = nullptr;
14047   Var->getAnyInitializer(DefVD);
14048   if (!DefVD)
14049     return false;
14050   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14051   Expr *Init = cast<Expr>(Eval->Value);
14052   if (Init->isValueDependent())
14053     return false;
14054   return IsVariableAConstantExpression(Var, Context);
14055 }
14056 
14057 
14058 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14059   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14060   // an object that satisfies the requirements for appearing in a
14061   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14062   // is immediately applied."  This function handles the lvalue-to-rvalue
14063   // conversion part.
14064   MaybeODRUseExprs.erase(E->IgnoreParens());
14065 
14066   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14067   // to a variable that is a constant expression, and if so, identify it as
14068   // a reference to a variable that does not involve an odr-use of that
14069   // variable.
14070   if (LambdaScopeInfo *LSI = getCurLambda()) {
14071     Expr *SansParensExpr = E->IgnoreParens();
14072     VarDecl *Var = nullptr;
14073     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14074       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14075     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14076       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14077 
14078     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14079       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14080   }
14081 }
14082 
14083 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14084   Res = CorrectDelayedTyposInExpr(Res);
14085 
14086   if (!Res.isUsable())
14087     return Res;
14088 
14089   // If a constant-expression is a reference to a variable where we delay
14090   // deciding whether it is an odr-use, just assume we will apply the
14091   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14092   // (a non-type template argument), we have special handling anyway.
14093   UpdateMarkingForLValueToRValue(Res.get());
14094   return Res;
14095 }
14096 
14097 void Sema::CleanupVarDeclMarking() {
14098   for (Expr *E : MaybeODRUseExprs) {
14099     VarDecl *Var;
14100     SourceLocation Loc;
14101     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14102       Var = cast<VarDecl>(DRE->getDecl());
14103       Loc = DRE->getLocation();
14104     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14105       Var = cast<VarDecl>(ME->getMemberDecl());
14106       Loc = ME->getMemberLoc();
14107     } else {
14108       llvm_unreachable("Unexpected expression");
14109     }
14110 
14111     MarkVarDeclODRUsed(Var, Loc, *this,
14112                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14113   }
14114 
14115   MaybeODRUseExprs.clear();
14116 }
14117 
14118 
14119 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14120                                     VarDecl *Var, Expr *E) {
14121   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14122          "Invalid Expr argument to DoMarkVarDeclReferenced");
14123   Var->setReferenced();
14124 
14125   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14126   bool MarkODRUsed = true;
14127 
14128   // If the context is not potentially evaluated, this is not an odr-use and
14129   // does not trigger instantiation.
14130   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
14131     if (SemaRef.isUnevaluatedContext())
14132       return;
14133 
14134     // If we don't yet know whether this context is going to end up being an
14135     // evaluated context, and we're referencing a variable from an enclosing
14136     // scope, add a potential capture.
14137     //
14138     // FIXME: Is this necessary? These contexts are only used for default
14139     // arguments, where local variables can't be used.
14140     const bool RefersToEnclosingScope =
14141         (SemaRef.CurContext != Var->getDeclContext() &&
14142          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14143     if (RefersToEnclosingScope) {
14144       if (LambdaScopeInfo *const LSI =
14145               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14146         // If a variable could potentially be odr-used, defer marking it so
14147         // until we finish analyzing the full expression for any
14148         // lvalue-to-rvalue
14149         // or discarded value conversions that would obviate odr-use.
14150         // Add it to the list of potential captures that will be analyzed
14151         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14152         // unless the variable is a reference that was initialized by a constant
14153         // expression (this will never need to be captured or odr-used).
14154         assert(E && "Capture variable should be used in an expression.");
14155         if (!Var->getType()->isReferenceType() ||
14156             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14157           LSI->addPotentialCapture(E->IgnoreParens());
14158       }
14159     }
14160 
14161     if (!isTemplateInstantiation(TSK))
14162       return;
14163 
14164     // Instantiate, but do not mark as odr-used, variable templates.
14165     MarkODRUsed = false;
14166   }
14167 
14168   VarTemplateSpecializationDecl *VarSpec =
14169       dyn_cast<VarTemplateSpecializationDecl>(Var);
14170   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14171          "Can't instantiate a partial template specialization.");
14172 
14173   // If this might be a member specialization of a static data member, check
14174   // the specialization is visible. We already did the checks for variable
14175   // template specializations when we created them.
14176   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14177     SemaRef.checkSpecializationVisibility(Loc, Var);
14178 
14179   // Perform implicit instantiation of static data members, static data member
14180   // templates of class templates, and variable template specializations. Delay
14181   // instantiations of variable templates, except for those that could be used
14182   // in a constant expression.
14183   if (isTemplateInstantiation(TSK)) {
14184     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14185 
14186     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14187       if (Var->getPointOfInstantiation().isInvalid()) {
14188         // This is a modification of an existing AST node. Notify listeners.
14189         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14190           L->StaticDataMemberInstantiated(Var);
14191       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14192         // Don't bother trying to instantiate it again, unless we might need
14193         // its initializer before we get to the end of the TU.
14194         TryInstantiating = false;
14195     }
14196 
14197     if (Var->getPointOfInstantiation().isInvalid())
14198       Var->setTemplateSpecializationKind(TSK, Loc);
14199 
14200     if (TryInstantiating) {
14201       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14202       bool InstantiationDependent = false;
14203       bool IsNonDependent =
14204           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14205                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14206                   : true;
14207 
14208       // Do not instantiate specializations that are still type-dependent.
14209       if (IsNonDependent) {
14210         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14211           // Do not defer instantiations of variables which could be used in a
14212           // constant expression.
14213           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14214         } else {
14215           SemaRef.PendingInstantiations
14216               .push_back(std::make_pair(Var, PointOfInstantiation));
14217         }
14218       }
14219     }
14220   }
14221 
14222   if (!MarkODRUsed)
14223     return;
14224 
14225   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14226   // the requirements for appearing in a constant expression (5.19) and, if
14227   // it is an object, the lvalue-to-rvalue conversion (4.1)
14228   // is immediately applied."  We check the first part here, and
14229   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14230   // Note that we use the C++11 definition everywhere because nothing in
14231   // C++03 depends on whether we get the C++03 version correct. The second
14232   // part does not apply to references, since they are not objects.
14233   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14234     // A reference initialized by a constant expression can never be
14235     // odr-used, so simply ignore it.
14236     if (!Var->getType()->isReferenceType())
14237       SemaRef.MaybeODRUseExprs.insert(E);
14238   } else
14239     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14240                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14241 }
14242 
14243 /// \brief Mark a variable referenced, and check whether it is odr-used
14244 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14245 /// used directly for normal expressions referring to VarDecl.
14246 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14247   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14248 }
14249 
14250 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14251                                Decl *D, Expr *E, bool MightBeOdrUse) {
14252   if (SemaRef.isInOpenMPDeclareTargetContext())
14253     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14254 
14255   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14256     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14257     return;
14258   }
14259 
14260   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14261 
14262   // If this is a call to a method via a cast, also mark the method in the
14263   // derived class used in case codegen can devirtualize the call.
14264   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14265   if (!ME)
14266     return;
14267   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14268   if (!MD)
14269     return;
14270   // Only attempt to devirtualize if this is truly a virtual call.
14271   bool IsVirtualCall = MD->isVirtual() &&
14272                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14273   if (!IsVirtualCall)
14274     return;
14275   const Expr *Base = ME->getBase();
14276   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14277   if (!MostDerivedClassDecl)
14278     return;
14279   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14280   if (!DM || DM->isPure())
14281     return;
14282   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14283 }
14284 
14285 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14286 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14287   // TODO: update this with DR# once a defect report is filed.
14288   // C++11 defect. The address of a pure member should not be an ODR use, even
14289   // if it's a qualified reference.
14290   bool OdrUse = true;
14291   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14292     if (Method->isVirtual())
14293       OdrUse = false;
14294   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14295 }
14296 
14297 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14298 void Sema::MarkMemberReferenced(MemberExpr *E) {
14299   // C++11 [basic.def.odr]p2:
14300   //   A non-overloaded function whose name appears as a potentially-evaluated
14301   //   expression or a member of a set of candidate functions, if selected by
14302   //   overload resolution when referred to from a potentially-evaluated
14303   //   expression, is odr-used, unless it is a pure virtual function and its
14304   //   name is not explicitly qualified.
14305   bool MightBeOdrUse = true;
14306   if (E->performsVirtualDispatch(getLangOpts())) {
14307     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14308       if (Method->isPure())
14309         MightBeOdrUse = false;
14310   }
14311   SourceLocation Loc = E->getMemberLoc().isValid() ?
14312                             E->getMemberLoc() : E->getLocStart();
14313   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14314 }
14315 
14316 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14317 /// marks the declaration referenced, and performs odr-use checking for
14318 /// functions and variables. This method should not be used when building a
14319 /// normal expression which refers to a variable.
14320 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14321                                  bool MightBeOdrUse) {
14322   if (MightBeOdrUse) {
14323     if (auto *VD = dyn_cast<VarDecl>(D)) {
14324       MarkVariableReferenced(Loc, VD);
14325       return;
14326     }
14327   }
14328   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14329     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14330     return;
14331   }
14332   D->setReferenced();
14333 }
14334 
14335 namespace {
14336   // Mark all of the declarations referenced
14337   // FIXME: Not fully implemented yet! We need to have a better understanding
14338   // of when we're entering
14339   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14340     Sema &S;
14341     SourceLocation Loc;
14342 
14343   public:
14344     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14345 
14346     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14347 
14348     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14349     bool TraverseRecordType(RecordType *T);
14350   };
14351 }
14352 
14353 bool MarkReferencedDecls::TraverseTemplateArgument(
14354     const TemplateArgument &Arg) {
14355   if (Arg.getKind() == TemplateArgument::Declaration) {
14356     if (Decl *D = Arg.getAsDecl())
14357       S.MarkAnyDeclReferenced(Loc, D, true);
14358   }
14359 
14360   return Inherited::TraverseTemplateArgument(Arg);
14361 }
14362 
14363 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14364   if (ClassTemplateSpecializationDecl *Spec
14365                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14366     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14367     return TraverseTemplateArguments(Args.data(), Args.size());
14368   }
14369 
14370   return true;
14371 }
14372 
14373 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14374   MarkReferencedDecls Marker(*this, Loc);
14375   Marker.TraverseType(Context.getCanonicalType(T));
14376 }
14377 
14378 namespace {
14379   /// \brief Helper class that marks all of the declarations referenced by
14380   /// potentially-evaluated subexpressions as "referenced".
14381   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14382     Sema &S;
14383     bool SkipLocalVariables;
14384 
14385   public:
14386     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14387 
14388     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14389       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14390 
14391     void VisitDeclRefExpr(DeclRefExpr *E) {
14392       // If we were asked not to visit local variables, don't.
14393       if (SkipLocalVariables) {
14394         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14395           if (VD->hasLocalStorage())
14396             return;
14397       }
14398 
14399       S.MarkDeclRefReferenced(E);
14400     }
14401 
14402     void VisitMemberExpr(MemberExpr *E) {
14403       S.MarkMemberReferenced(E);
14404       Inherited::VisitMemberExpr(E);
14405     }
14406 
14407     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14408       S.MarkFunctionReferenced(E->getLocStart(),
14409             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14410       Visit(E->getSubExpr());
14411     }
14412 
14413     void VisitCXXNewExpr(CXXNewExpr *E) {
14414       if (E->getOperatorNew())
14415         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14416       if (E->getOperatorDelete())
14417         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14418       Inherited::VisitCXXNewExpr(E);
14419     }
14420 
14421     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14422       if (E->getOperatorDelete())
14423         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14424       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14425       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14426         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14427         S.MarkFunctionReferenced(E->getLocStart(),
14428                                     S.LookupDestructor(Record));
14429       }
14430 
14431       Inherited::VisitCXXDeleteExpr(E);
14432     }
14433 
14434     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14435       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14436       Inherited::VisitCXXConstructExpr(E);
14437     }
14438 
14439     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14440       Visit(E->getExpr());
14441     }
14442 
14443     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14444       Inherited::VisitImplicitCastExpr(E);
14445 
14446       if (E->getCastKind() == CK_LValueToRValue)
14447         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14448     }
14449   };
14450 }
14451 
14452 /// \brief Mark any declarations that appear within this expression or any
14453 /// potentially-evaluated subexpressions as "referenced".
14454 ///
14455 /// \param SkipLocalVariables If true, don't mark local variables as
14456 /// 'referenced'.
14457 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14458                                             bool SkipLocalVariables) {
14459   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14460 }
14461 
14462 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14463 /// of the program being compiled.
14464 ///
14465 /// This routine emits the given diagnostic when the code currently being
14466 /// type-checked is "potentially evaluated", meaning that there is a
14467 /// possibility that the code will actually be executable. Code in sizeof()
14468 /// expressions, code used only during overload resolution, etc., are not
14469 /// potentially evaluated. This routine will suppress such diagnostics or,
14470 /// in the absolutely nutty case of potentially potentially evaluated
14471 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14472 /// later.
14473 ///
14474 /// This routine should be used for all diagnostics that describe the run-time
14475 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14476 /// Failure to do so will likely result in spurious diagnostics or failures
14477 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14478 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14479                                const PartialDiagnostic &PD) {
14480   switch (ExprEvalContexts.back().Context) {
14481   case Unevaluated:
14482   case UnevaluatedAbstract:
14483   case DiscardedStatement:
14484     // The argument will never be evaluated, so don't complain.
14485     break;
14486 
14487   case ConstantEvaluated:
14488     // Relevant diagnostics should be produced by constant evaluation.
14489     break;
14490 
14491   case PotentiallyEvaluated:
14492   case PotentiallyEvaluatedIfUsed:
14493     if (Statement && getCurFunctionOrMethodDecl()) {
14494       FunctionScopes.back()->PossiblyUnreachableDiags.
14495         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14496     }
14497     else
14498       Diag(Loc, PD);
14499 
14500     return true;
14501   }
14502 
14503   return false;
14504 }
14505 
14506 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14507                                CallExpr *CE, FunctionDecl *FD) {
14508   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14509     return false;
14510 
14511   // If we're inside a decltype's expression, don't check for a valid return
14512   // type or construct temporaries until we know whether this is the last call.
14513   if (ExprEvalContexts.back().IsDecltype) {
14514     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14515     return false;
14516   }
14517 
14518   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14519     FunctionDecl *FD;
14520     CallExpr *CE;
14521 
14522   public:
14523     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14524       : FD(FD), CE(CE) { }
14525 
14526     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14527       if (!FD) {
14528         S.Diag(Loc, diag::err_call_incomplete_return)
14529           << T << CE->getSourceRange();
14530         return;
14531       }
14532 
14533       S.Diag(Loc, diag::err_call_function_incomplete_return)
14534         << CE->getSourceRange() << FD->getDeclName() << T;
14535       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14536           << FD->getDeclName();
14537     }
14538   } Diagnoser(FD, CE);
14539 
14540   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14541     return true;
14542 
14543   return false;
14544 }
14545 
14546 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14547 // will prevent this condition from triggering, which is what we want.
14548 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14549   SourceLocation Loc;
14550 
14551   unsigned diagnostic = diag::warn_condition_is_assignment;
14552   bool IsOrAssign = false;
14553 
14554   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14555     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14556       return;
14557 
14558     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14559 
14560     // Greylist some idioms by putting them into a warning subcategory.
14561     if (ObjCMessageExpr *ME
14562           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14563       Selector Sel = ME->getSelector();
14564 
14565       // self = [<foo> init...]
14566       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14567         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14568 
14569       // <foo> = [<bar> nextObject]
14570       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14571         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14572     }
14573 
14574     Loc = Op->getOperatorLoc();
14575   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14576     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14577       return;
14578 
14579     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14580     Loc = Op->getOperatorLoc();
14581   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14582     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14583   else {
14584     // Not an assignment.
14585     return;
14586   }
14587 
14588   Diag(Loc, diagnostic) << E->getSourceRange();
14589 
14590   SourceLocation Open = E->getLocStart();
14591   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14592   Diag(Loc, diag::note_condition_assign_silence)
14593         << FixItHint::CreateInsertion(Open, "(")
14594         << FixItHint::CreateInsertion(Close, ")");
14595 
14596   if (IsOrAssign)
14597     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14598       << FixItHint::CreateReplacement(Loc, "!=");
14599   else
14600     Diag(Loc, diag::note_condition_assign_to_comparison)
14601       << FixItHint::CreateReplacement(Loc, "==");
14602 }
14603 
14604 /// \brief Redundant parentheses over an equality comparison can indicate
14605 /// that the user intended an assignment used as condition.
14606 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14607   // Don't warn if the parens came from a macro.
14608   SourceLocation parenLoc = ParenE->getLocStart();
14609   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14610     return;
14611   // Don't warn for dependent expressions.
14612   if (ParenE->isTypeDependent())
14613     return;
14614 
14615   Expr *E = ParenE->IgnoreParens();
14616 
14617   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14618     if (opE->getOpcode() == BO_EQ &&
14619         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14620                                                            == Expr::MLV_Valid) {
14621       SourceLocation Loc = opE->getOperatorLoc();
14622 
14623       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14624       SourceRange ParenERange = ParenE->getSourceRange();
14625       Diag(Loc, diag::note_equality_comparison_silence)
14626         << FixItHint::CreateRemoval(ParenERange.getBegin())
14627         << FixItHint::CreateRemoval(ParenERange.getEnd());
14628       Diag(Loc, diag::note_equality_comparison_to_assign)
14629         << FixItHint::CreateReplacement(Loc, "=");
14630     }
14631 }
14632 
14633 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14634                                        bool IsConstexpr) {
14635   DiagnoseAssignmentAsCondition(E);
14636   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14637     DiagnoseEqualityWithExtraParens(parenE);
14638 
14639   ExprResult result = CheckPlaceholderExpr(E);
14640   if (result.isInvalid()) return ExprError();
14641   E = result.get();
14642 
14643   if (!E->isTypeDependent()) {
14644     if (getLangOpts().CPlusPlus)
14645       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14646 
14647     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14648     if (ERes.isInvalid())
14649       return ExprError();
14650     E = ERes.get();
14651 
14652     QualType T = E->getType();
14653     if (!T->isScalarType()) { // C99 6.8.4.1p1
14654       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14655         << T << E->getSourceRange();
14656       return ExprError();
14657     }
14658     CheckBoolLikeConversion(E, Loc);
14659   }
14660 
14661   return E;
14662 }
14663 
14664 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14665                                            Expr *SubExpr, ConditionKind CK) {
14666   // Empty conditions are valid in for-statements.
14667   if (!SubExpr)
14668     return ConditionResult();
14669 
14670   ExprResult Cond;
14671   switch (CK) {
14672   case ConditionKind::Boolean:
14673     Cond = CheckBooleanCondition(Loc, SubExpr);
14674     break;
14675 
14676   case ConditionKind::ConstexprIf:
14677     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14678     break;
14679 
14680   case ConditionKind::Switch:
14681     Cond = CheckSwitchCondition(Loc, SubExpr);
14682     break;
14683   }
14684   if (Cond.isInvalid())
14685     return ConditionError();
14686 
14687   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14688   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14689   if (!FullExpr.get())
14690     return ConditionError();
14691 
14692   return ConditionResult(*this, nullptr, FullExpr,
14693                          CK == ConditionKind::ConstexprIf);
14694 }
14695 
14696 namespace {
14697   /// A visitor for rebuilding a call to an __unknown_any expression
14698   /// to have an appropriate type.
14699   struct RebuildUnknownAnyFunction
14700     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14701 
14702     Sema &S;
14703 
14704     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14705 
14706     ExprResult VisitStmt(Stmt *S) {
14707       llvm_unreachable("unexpected statement!");
14708     }
14709 
14710     ExprResult VisitExpr(Expr *E) {
14711       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14712         << E->getSourceRange();
14713       return ExprError();
14714     }
14715 
14716     /// Rebuild an expression which simply semantically wraps another
14717     /// expression which it shares the type and value kind of.
14718     template <class T> ExprResult rebuildSugarExpr(T *E) {
14719       ExprResult SubResult = Visit(E->getSubExpr());
14720       if (SubResult.isInvalid()) return ExprError();
14721 
14722       Expr *SubExpr = SubResult.get();
14723       E->setSubExpr(SubExpr);
14724       E->setType(SubExpr->getType());
14725       E->setValueKind(SubExpr->getValueKind());
14726       assert(E->getObjectKind() == OK_Ordinary);
14727       return E;
14728     }
14729 
14730     ExprResult VisitParenExpr(ParenExpr *E) {
14731       return rebuildSugarExpr(E);
14732     }
14733 
14734     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14735       return rebuildSugarExpr(E);
14736     }
14737 
14738     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14739       ExprResult SubResult = Visit(E->getSubExpr());
14740       if (SubResult.isInvalid()) return ExprError();
14741 
14742       Expr *SubExpr = SubResult.get();
14743       E->setSubExpr(SubExpr);
14744       E->setType(S.Context.getPointerType(SubExpr->getType()));
14745       assert(E->getValueKind() == VK_RValue);
14746       assert(E->getObjectKind() == OK_Ordinary);
14747       return E;
14748     }
14749 
14750     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14751       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14752 
14753       E->setType(VD->getType());
14754 
14755       assert(E->getValueKind() == VK_RValue);
14756       if (S.getLangOpts().CPlusPlus &&
14757           !(isa<CXXMethodDecl>(VD) &&
14758             cast<CXXMethodDecl>(VD)->isInstance()))
14759         E->setValueKind(VK_LValue);
14760 
14761       return E;
14762     }
14763 
14764     ExprResult VisitMemberExpr(MemberExpr *E) {
14765       return resolveDecl(E, E->getMemberDecl());
14766     }
14767 
14768     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14769       return resolveDecl(E, E->getDecl());
14770     }
14771   };
14772 }
14773 
14774 /// Given a function expression of unknown-any type, try to rebuild it
14775 /// to have a function type.
14776 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14777   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14778   if (Result.isInvalid()) return ExprError();
14779   return S.DefaultFunctionArrayConversion(Result.get());
14780 }
14781 
14782 namespace {
14783   /// A visitor for rebuilding an expression of type __unknown_anytype
14784   /// into one which resolves the type directly on the referring
14785   /// expression.  Strict preservation of the original source
14786   /// structure is not a goal.
14787   struct RebuildUnknownAnyExpr
14788     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14789 
14790     Sema &S;
14791 
14792     /// The current destination type.
14793     QualType DestType;
14794 
14795     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14796       : S(S), DestType(CastType) {}
14797 
14798     ExprResult VisitStmt(Stmt *S) {
14799       llvm_unreachable("unexpected statement!");
14800     }
14801 
14802     ExprResult VisitExpr(Expr *E) {
14803       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14804         << E->getSourceRange();
14805       return ExprError();
14806     }
14807 
14808     ExprResult VisitCallExpr(CallExpr *E);
14809     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14810 
14811     /// Rebuild an expression which simply semantically wraps another
14812     /// expression which it shares the type and value kind of.
14813     template <class T> ExprResult rebuildSugarExpr(T *E) {
14814       ExprResult SubResult = Visit(E->getSubExpr());
14815       if (SubResult.isInvalid()) return ExprError();
14816       Expr *SubExpr = SubResult.get();
14817       E->setSubExpr(SubExpr);
14818       E->setType(SubExpr->getType());
14819       E->setValueKind(SubExpr->getValueKind());
14820       assert(E->getObjectKind() == OK_Ordinary);
14821       return E;
14822     }
14823 
14824     ExprResult VisitParenExpr(ParenExpr *E) {
14825       return rebuildSugarExpr(E);
14826     }
14827 
14828     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14829       return rebuildSugarExpr(E);
14830     }
14831 
14832     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14833       const PointerType *Ptr = DestType->getAs<PointerType>();
14834       if (!Ptr) {
14835         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14836           << E->getSourceRange();
14837         return ExprError();
14838       }
14839 
14840       if (isa<CallExpr>(E->getSubExpr())) {
14841         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14842           << E->getSourceRange();
14843         return ExprError();
14844       }
14845 
14846       assert(E->getValueKind() == VK_RValue);
14847       assert(E->getObjectKind() == OK_Ordinary);
14848       E->setType(DestType);
14849 
14850       // Build the sub-expression as if it were an object of the pointee type.
14851       DestType = Ptr->getPointeeType();
14852       ExprResult SubResult = Visit(E->getSubExpr());
14853       if (SubResult.isInvalid()) return ExprError();
14854       E->setSubExpr(SubResult.get());
14855       return E;
14856     }
14857 
14858     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14859 
14860     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14861 
14862     ExprResult VisitMemberExpr(MemberExpr *E) {
14863       return resolveDecl(E, E->getMemberDecl());
14864     }
14865 
14866     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14867       return resolveDecl(E, E->getDecl());
14868     }
14869   };
14870 }
14871 
14872 /// Rebuilds a call expression which yielded __unknown_anytype.
14873 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14874   Expr *CalleeExpr = E->getCallee();
14875 
14876   enum FnKind {
14877     FK_MemberFunction,
14878     FK_FunctionPointer,
14879     FK_BlockPointer
14880   };
14881 
14882   FnKind Kind;
14883   QualType CalleeType = CalleeExpr->getType();
14884   if (CalleeType == S.Context.BoundMemberTy) {
14885     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14886     Kind = FK_MemberFunction;
14887     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14888   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14889     CalleeType = Ptr->getPointeeType();
14890     Kind = FK_FunctionPointer;
14891   } else {
14892     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14893     Kind = FK_BlockPointer;
14894   }
14895   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14896 
14897   // Verify that this is a legal result type of a function.
14898   if (DestType->isArrayType() || DestType->isFunctionType()) {
14899     unsigned diagID = diag::err_func_returning_array_function;
14900     if (Kind == FK_BlockPointer)
14901       diagID = diag::err_block_returning_array_function;
14902 
14903     S.Diag(E->getExprLoc(), diagID)
14904       << DestType->isFunctionType() << DestType;
14905     return ExprError();
14906   }
14907 
14908   // Otherwise, go ahead and set DestType as the call's result.
14909   E->setType(DestType.getNonLValueExprType(S.Context));
14910   E->setValueKind(Expr::getValueKindForType(DestType));
14911   assert(E->getObjectKind() == OK_Ordinary);
14912 
14913   // Rebuild the function type, replacing the result type with DestType.
14914   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14915   if (Proto) {
14916     // __unknown_anytype(...) is a special case used by the debugger when
14917     // it has no idea what a function's signature is.
14918     //
14919     // We want to build this call essentially under the K&R
14920     // unprototyped rules, but making a FunctionNoProtoType in C++
14921     // would foul up all sorts of assumptions.  However, we cannot
14922     // simply pass all arguments as variadic arguments, nor can we
14923     // portably just call the function under a non-variadic type; see
14924     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14925     // However, it turns out that in practice it is generally safe to
14926     // call a function declared as "A foo(B,C,D);" under the prototype
14927     // "A foo(B,C,D,...);".  The only known exception is with the
14928     // Windows ABI, where any variadic function is implicitly cdecl
14929     // regardless of its normal CC.  Therefore we change the parameter
14930     // types to match the types of the arguments.
14931     //
14932     // This is a hack, but it is far superior to moving the
14933     // corresponding target-specific code from IR-gen to Sema/AST.
14934 
14935     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14936     SmallVector<QualType, 8> ArgTypes;
14937     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14938       ArgTypes.reserve(E->getNumArgs());
14939       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14940         Expr *Arg = E->getArg(i);
14941         QualType ArgType = Arg->getType();
14942         if (E->isLValue()) {
14943           ArgType = S.Context.getLValueReferenceType(ArgType);
14944         } else if (E->isXValue()) {
14945           ArgType = S.Context.getRValueReferenceType(ArgType);
14946         }
14947         ArgTypes.push_back(ArgType);
14948       }
14949       ParamTypes = ArgTypes;
14950     }
14951     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14952                                          Proto->getExtProtoInfo());
14953   } else {
14954     DestType = S.Context.getFunctionNoProtoType(DestType,
14955                                                 FnType->getExtInfo());
14956   }
14957 
14958   // Rebuild the appropriate pointer-to-function type.
14959   switch (Kind) {
14960   case FK_MemberFunction:
14961     // Nothing to do.
14962     break;
14963 
14964   case FK_FunctionPointer:
14965     DestType = S.Context.getPointerType(DestType);
14966     break;
14967 
14968   case FK_BlockPointer:
14969     DestType = S.Context.getBlockPointerType(DestType);
14970     break;
14971   }
14972 
14973   // Finally, we can recurse.
14974   ExprResult CalleeResult = Visit(CalleeExpr);
14975   if (!CalleeResult.isUsable()) return ExprError();
14976   E->setCallee(CalleeResult.get());
14977 
14978   // Bind a temporary if necessary.
14979   return S.MaybeBindToTemporary(E);
14980 }
14981 
14982 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14983   // Verify that this is a legal result type of a call.
14984   if (DestType->isArrayType() || DestType->isFunctionType()) {
14985     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14986       << DestType->isFunctionType() << DestType;
14987     return ExprError();
14988   }
14989 
14990   // Rewrite the method result type if available.
14991   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14992     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14993     Method->setReturnType(DestType);
14994   }
14995 
14996   // Change the type of the message.
14997   E->setType(DestType.getNonReferenceType());
14998   E->setValueKind(Expr::getValueKindForType(DestType));
14999 
15000   return S.MaybeBindToTemporary(E);
15001 }
15002 
15003 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15004   // The only case we should ever see here is a function-to-pointer decay.
15005   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15006     assert(E->getValueKind() == VK_RValue);
15007     assert(E->getObjectKind() == OK_Ordinary);
15008 
15009     E->setType(DestType);
15010 
15011     // Rebuild the sub-expression as the pointee (function) type.
15012     DestType = DestType->castAs<PointerType>()->getPointeeType();
15013 
15014     ExprResult Result = Visit(E->getSubExpr());
15015     if (!Result.isUsable()) return ExprError();
15016 
15017     E->setSubExpr(Result.get());
15018     return E;
15019   } else if (E->getCastKind() == CK_LValueToRValue) {
15020     assert(E->getValueKind() == VK_RValue);
15021     assert(E->getObjectKind() == OK_Ordinary);
15022 
15023     assert(isa<BlockPointerType>(E->getType()));
15024 
15025     E->setType(DestType);
15026 
15027     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15028     DestType = S.Context.getLValueReferenceType(DestType);
15029 
15030     ExprResult Result = Visit(E->getSubExpr());
15031     if (!Result.isUsable()) return ExprError();
15032 
15033     E->setSubExpr(Result.get());
15034     return E;
15035   } else {
15036     llvm_unreachable("Unhandled cast type!");
15037   }
15038 }
15039 
15040 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15041   ExprValueKind ValueKind = VK_LValue;
15042   QualType Type = DestType;
15043 
15044   // We know how to make this work for certain kinds of decls:
15045 
15046   //  - functions
15047   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15048     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15049       DestType = Ptr->getPointeeType();
15050       ExprResult Result = resolveDecl(E, VD);
15051       if (Result.isInvalid()) return ExprError();
15052       return S.ImpCastExprToType(Result.get(), Type,
15053                                  CK_FunctionToPointerDecay, VK_RValue);
15054     }
15055 
15056     if (!Type->isFunctionType()) {
15057       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15058         << VD << E->getSourceRange();
15059       return ExprError();
15060     }
15061     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15062       // We must match the FunctionDecl's type to the hack introduced in
15063       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15064       // type. See the lengthy commentary in that routine.
15065       QualType FDT = FD->getType();
15066       const FunctionType *FnType = FDT->castAs<FunctionType>();
15067       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15068       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15069       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15070         SourceLocation Loc = FD->getLocation();
15071         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15072                                       FD->getDeclContext(),
15073                                       Loc, Loc, FD->getNameInfo().getName(),
15074                                       DestType, FD->getTypeSourceInfo(),
15075                                       SC_None, false/*isInlineSpecified*/,
15076                                       FD->hasPrototype(),
15077                                       false/*isConstexprSpecified*/);
15078 
15079         if (FD->getQualifier())
15080           NewFD->setQualifierInfo(FD->getQualifierLoc());
15081 
15082         SmallVector<ParmVarDecl*, 16> Params;
15083         for (const auto &AI : FT->param_types()) {
15084           ParmVarDecl *Param =
15085             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15086           Param->setScopeInfo(0, Params.size());
15087           Params.push_back(Param);
15088         }
15089         NewFD->setParams(Params);
15090         DRE->setDecl(NewFD);
15091         VD = DRE->getDecl();
15092       }
15093     }
15094 
15095     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15096       if (MD->isInstance()) {
15097         ValueKind = VK_RValue;
15098         Type = S.Context.BoundMemberTy;
15099       }
15100 
15101     // Function references aren't l-values in C.
15102     if (!S.getLangOpts().CPlusPlus)
15103       ValueKind = VK_RValue;
15104 
15105   //  - variables
15106   } else if (isa<VarDecl>(VD)) {
15107     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15108       Type = RefTy->getPointeeType();
15109     } else if (Type->isFunctionType()) {
15110       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15111         << VD << E->getSourceRange();
15112       return ExprError();
15113     }
15114 
15115   //  - nothing else
15116   } else {
15117     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15118       << VD << E->getSourceRange();
15119     return ExprError();
15120   }
15121 
15122   // Modifying the declaration like this is friendly to IR-gen but
15123   // also really dangerous.
15124   VD->setType(DestType);
15125   E->setType(Type);
15126   E->setValueKind(ValueKind);
15127   return E;
15128 }
15129 
15130 /// Check a cast of an unknown-any type.  We intentionally only
15131 /// trigger this for C-style casts.
15132 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15133                                      Expr *CastExpr, CastKind &CastKind,
15134                                      ExprValueKind &VK, CXXCastPath &Path) {
15135   // The type we're casting to must be either void or complete.
15136   if (!CastType->isVoidType() &&
15137       RequireCompleteType(TypeRange.getBegin(), CastType,
15138                           diag::err_typecheck_cast_to_incomplete))
15139     return ExprError();
15140 
15141   // Rewrite the casted expression from scratch.
15142   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15143   if (!result.isUsable()) return ExprError();
15144 
15145   CastExpr = result.get();
15146   VK = CastExpr->getValueKind();
15147   CastKind = CK_NoOp;
15148 
15149   return CastExpr;
15150 }
15151 
15152 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15153   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15154 }
15155 
15156 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15157                                     Expr *arg, QualType &paramType) {
15158   // If the syntactic form of the argument is not an explicit cast of
15159   // any sort, just do default argument promotion.
15160   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15161   if (!castArg) {
15162     ExprResult result = DefaultArgumentPromotion(arg);
15163     if (result.isInvalid()) return ExprError();
15164     paramType = result.get()->getType();
15165     return result;
15166   }
15167 
15168   // Otherwise, use the type that was written in the explicit cast.
15169   assert(!arg->hasPlaceholderType());
15170   paramType = castArg->getTypeAsWritten();
15171 
15172   // Copy-initialize a parameter of that type.
15173   InitializedEntity entity =
15174     InitializedEntity::InitializeParameter(Context, paramType,
15175                                            /*consumed*/ false);
15176   return PerformCopyInitialization(entity, callLoc, arg);
15177 }
15178 
15179 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15180   Expr *orig = E;
15181   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15182   while (true) {
15183     E = E->IgnoreParenImpCasts();
15184     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15185       E = call->getCallee();
15186       diagID = diag::err_uncasted_call_of_unknown_any;
15187     } else {
15188       break;
15189     }
15190   }
15191 
15192   SourceLocation loc;
15193   NamedDecl *d;
15194   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15195     loc = ref->getLocation();
15196     d = ref->getDecl();
15197   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15198     loc = mem->getMemberLoc();
15199     d = mem->getMemberDecl();
15200   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15201     diagID = diag::err_uncasted_call_of_unknown_any;
15202     loc = msg->getSelectorStartLoc();
15203     d = msg->getMethodDecl();
15204     if (!d) {
15205       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15206         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15207         << orig->getSourceRange();
15208       return ExprError();
15209     }
15210   } else {
15211     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15212       << E->getSourceRange();
15213     return ExprError();
15214   }
15215 
15216   S.Diag(loc, diagID) << d << orig->getSourceRange();
15217 
15218   // Never recoverable.
15219   return ExprError();
15220 }
15221 
15222 /// Check for operands with placeholder types and complain if found.
15223 /// Returns true if there was an error and no recovery was possible.
15224 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15225   if (!getLangOpts().CPlusPlus) {
15226     // C cannot handle TypoExpr nodes on either side of a binop because it
15227     // doesn't handle dependent types properly, so make sure any TypoExprs have
15228     // been dealt with before checking the operands.
15229     ExprResult Result = CorrectDelayedTyposInExpr(E);
15230     if (!Result.isUsable()) return ExprError();
15231     E = Result.get();
15232   }
15233 
15234   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15235   if (!placeholderType) return E;
15236 
15237   switch (placeholderType->getKind()) {
15238 
15239   // Overloaded expressions.
15240   case BuiltinType::Overload: {
15241     // Try to resolve a single function template specialization.
15242     // This is obligatory.
15243     ExprResult Result = E;
15244     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15245       return Result;
15246 
15247     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15248     // leaves Result unchanged on failure.
15249     Result = E;
15250     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15251       return Result;
15252 
15253     // If that failed, try to recover with a call.
15254     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15255                          /*complain*/ true);
15256     return Result;
15257   }
15258 
15259   // Bound member functions.
15260   case BuiltinType::BoundMember: {
15261     ExprResult result = E;
15262     const Expr *BME = E->IgnoreParens();
15263     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15264     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15265     if (isa<CXXPseudoDestructorExpr>(BME)) {
15266       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15267     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15268       if (ME->getMemberNameInfo().getName().getNameKind() ==
15269           DeclarationName::CXXDestructorName)
15270         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15271     }
15272     tryToRecoverWithCall(result, PD,
15273                          /*complain*/ true);
15274     return result;
15275   }
15276 
15277   // ARC unbridged casts.
15278   case BuiltinType::ARCUnbridgedCast: {
15279     Expr *realCast = stripARCUnbridgedCast(E);
15280     diagnoseARCUnbridgedCast(realCast);
15281     return realCast;
15282   }
15283 
15284   // Expressions of unknown type.
15285   case BuiltinType::UnknownAny:
15286     return diagnoseUnknownAnyExpr(*this, E);
15287 
15288   // Pseudo-objects.
15289   case BuiltinType::PseudoObject:
15290     return checkPseudoObjectRValue(E);
15291 
15292   case BuiltinType::BuiltinFn: {
15293     // Accept __noop without parens by implicitly converting it to a call expr.
15294     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15295     if (DRE) {
15296       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15297       if (FD->getBuiltinID() == Builtin::BI__noop) {
15298         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15299                               CK_BuiltinFnToFnPtr).get();
15300         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15301                                       VK_RValue, SourceLocation());
15302       }
15303     }
15304 
15305     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15306     return ExprError();
15307   }
15308 
15309   // Expressions of unknown type.
15310   case BuiltinType::OMPArraySection:
15311     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15312     return ExprError();
15313 
15314   // Everything else should be impossible.
15315 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15316   case BuiltinType::Id:
15317 #include "clang/Basic/OpenCLImageTypes.def"
15318 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15319 #define PLACEHOLDER_TYPE(Id, SingletonId)
15320 #include "clang/AST/BuiltinTypes.def"
15321     break;
15322   }
15323 
15324   llvm_unreachable("invalid placeholder type!");
15325 }
15326 
15327 bool Sema::CheckCaseExpression(Expr *E) {
15328   if (E->isTypeDependent())
15329     return true;
15330   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15331     return E->getType()->isIntegralOrEnumerationType();
15332   return false;
15333 }
15334 
15335 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15336 ExprResult
15337 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15338   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15339          "Unknown Objective-C Boolean value!");
15340   QualType BoolT = Context.ObjCBuiltinBoolTy;
15341   if (!Context.getBOOLDecl()) {
15342     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15343                         Sema::LookupOrdinaryName);
15344     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15345       NamedDecl *ND = Result.getFoundDecl();
15346       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15347         Context.setBOOLDecl(TD);
15348     }
15349   }
15350   if (Context.getBOOLDecl())
15351     BoolT = Context.getBOOLType();
15352   return new (Context)
15353       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15354 }
15355 
15356 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15357     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15358     SourceLocation RParen) {
15359 
15360   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15361 
15362   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15363                            [&](const AvailabilitySpec &Spec) {
15364                              return Spec.getPlatform() == Platform;
15365                            });
15366 
15367   VersionTuple Version;
15368   if (Spec != AvailSpecs.end())
15369     Version = Spec->getVersion();
15370 
15371   return new (Context)
15372       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15373 }
15374