1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.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/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/DiagnosticSema.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/LiteralSupport.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/AnalysisBasedWarnings.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Designator.h"
42 #include "clang/Sema/Initialization.h"
43 #include "clang/Sema/Lookup.h"
44 #include "clang/Sema/Overload.h"
45 #include "clang/Sema/ParsedTemplate.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaFixItUtils.h"
49 #include "clang/Sema/SemaInternal.h"
50 #include "clang/Sema/Template.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/Support/ConvertUTF.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 
56 using namespace clang;
57 using namespace sema;
58 
59 /// Determine whether the use of this declaration is valid, without
60 /// emitting diagnostics.
61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
62   // See if this is an auto-typed variable whose initializer we are parsing.
63   if (ParsingInitForAutoVars.count(D))
64     return false;
65 
66   // See if this is a deleted function.
67   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
68     if (FD->isDeleted())
69       return false;
70 
71     // If the function has a deduced return type, and we can't deduce it,
72     // then we can't use it either.
73     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
74         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
75       return false;
76 
77     // See if this is an aligned allocation/deallocation function that is
78     // unavailable.
79     if (TreatUnavailableAsInvalid &&
80         isUnavailableAlignedAllocationFunction(*FD))
81       return false;
82   }
83 
84   // See if this function is unavailable.
85   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
86       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
87     return false;
88 
89   if (isa<UnresolvedUsingIfExistsDecl>(D))
90     return false;
91 
92   return true;
93 }
94 
95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
96   // Warn if this is used but marked unused.
97   if (const auto *A = D->getAttr<UnusedAttr>()) {
98     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
99     // should diagnose them.
100     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
101         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
102       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
103       if (DC && !DC->hasAttr<UnusedAttr>())
104         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
105     }
106   }
107 }
108 
109 /// Emit a note explaining that this function is deleted.
110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
111   assert(Decl && Decl->isDeleted());
112 
113   if (Decl->isDefaulted()) {
114     // If the method was explicitly defaulted, point at that declaration.
115     if (!Decl->isImplicit())
116       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
117 
118     // Try to diagnose why this special member function was implicitly
119     // deleted. This might fail, if that reason no longer applies.
120     DiagnoseDeletedDefaultedFunction(Decl);
121     return;
122   }
123 
124   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
125   if (Ctor && Ctor->isInheritingConstructor())
126     return NoteDeletedInheritingConstructor(Ctor);
127 
128   Diag(Decl->getLocation(), diag::note_availability_specified_here)
129     << Decl << 1;
130 }
131 
132 /// Determine whether a FunctionDecl was ever declared with an
133 /// explicit storage class.
134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
135   for (auto I : D->redecls()) {
136     if (I->getStorageClass() != SC_None)
137       return true;
138   }
139   return false;
140 }
141 
142 /// Check whether we're in an extern inline function and referring to a
143 /// variable or function with internal linkage (C11 6.7.4p3).
144 ///
145 /// This is only a warning because we used to silently accept this code, but
146 /// in many cases it will not behave correctly. This is not enabled in C++ mode
147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
148 /// and so while there may still be user mistakes, most of the time we can't
149 /// prove that there are errors.
150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
151                                                       const NamedDecl *D,
152                                                       SourceLocation Loc) {
153   // This is disabled under C++; there are too many ways for this to fire in
154   // contexts where the warning is a false positive, or where it is technically
155   // correct but benign.
156   if (S.getLangOpts().CPlusPlus)
157     return;
158 
159   // Check if this is an inlined function or method.
160   FunctionDecl *Current = S.getCurFunctionDecl();
161   if (!Current)
162     return;
163   if (!Current->isInlined())
164     return;
165   if (!Current->isExternallyVisible())
166     return;
167 
168   // Check if the decl has internal linkage.
169   if (D->getFormalLinkage() != InternalLinkage)
170     return;
171 
172   // Downgrade from ExtWarn to Extension if
173   //  (1) the supposedly external inline function is in the main file,
174   //      and probably won't be included anywhere else.
175   //  (2) the thing we're referencing is a pure function.
176   //  (3) the thing we're referencing is another inline function.
177   // This last can give us false negatives, but it's better than warning on
178   // wrappers for simple C library functions.
179   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
180   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
181   if (!DowngradeWarning && UsedFn)
182     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
183 
184   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
185                                : diag::ext_internal_in_extern_inline)
186     << /*IsVar=*/!UsedFn << D;
187 
188   S.MaybeSuggestAddingStaticToDecl(Current);
189 
190   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
191       << D;
192 }
193 
194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
195   const FunctionDecl *First = Cur->getFirstDecl();
196 
197   // Suggest "static" on the function, if possible.
198   if (!hasAnyExplicitStorageClass(First)) {
199     SourceLocation DeclBegin = First->getSourceRange().getBegin();
200     Diag(DeclBegin, diag::note_convert_inline_to_static)
201       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
202   }
203 }
204 
205 /// Determine whether the use of this declaration is valid, and
206 /// emit any corresponding diagnostics.
207 ///
208 /// This routine diagnoses various problems with referencing
209 /// declarations that can occur when using a declaration. For example,
210 /// it might warn if a deprecated or unavailable declaration is being
211 /// used, or produce an error (and return true) if a C++0x deleted
212 /// function is being used.
213 ///
214 /// \returns true if there was an error (this declaration cannot be
215 /// referenced), false otherwise.
216 ///
217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
218                              const ObjCInterfaceDecl *UnknownObjCClass,
219                              bool ObjCPropertyAccess,
220                              bool AvoidPartialAvailabilityChecks,
221                              ObjCInterfaceDecl *ClassReceiver) {
222   SourceLocation Loc = Locs.front();
223   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224     // If there were any diagnostics suppressed by template argument deduction,
225     // emit them now.
226     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227     if (Pos != SuppressedDiagnostics.end()) {
228       for (const PartialDiagnosticAt &Suppressed : Pos->second)
229         Diag(Suppressed.first, Suppressed.second);
230 
231       // Clear out the list of suppressed diagnostics, so that we don't emit
232       // them again for this specialization. However, we don't obsolete this
233       // entry from the table, because we want to avoid ever emitting these
234       // diagnostics again.
235       Pos->second.clear();
236     }
237 
238     // C++ [basic.start.main]p3:
239     //   The function 'main' shall not be used within a program.
240     if (cast<FunctionDecl>(D)->isMain())
241       Diag(Loc, diag::ext_main_used);
242 
243     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244   }
245 
246   // See if this is an auto-typed variable whose initializer we are parsing.
247   if (ParsingInitForAutoVars.count(D)) {
248     if (isa<BindingDecl>(D)) {
249       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250         << D->getDeclName();
251     } else {
252       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253         << D->getDeclName() << cast<VarDecl>(D)->getType();
254     }
255     return true;
256   }
257 
258   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259     // See if this is a deleted function.
260     if (FD->isDeleted()) {
261       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262       if (Ctor && Ctor->isInheritingConstructor())
263         Diag(Loc, diag::err_deleted_inherited_ctor_use)
264             << Ctor->getParent()
265             << Ctor->getInheritedConstructor().getConstructor()->getParent();
266       else
267         Diag(Loc, diag::err_deleted_function_use);
268       NoteDeletedFunction(FD);
269       return true;
270     }
271 
272     // [expr.prim.id]p4
273     //   A program that refers explicitly or implicitly to a function with a
274     //   trailing requires-clause whose constraint-expression is not satisfied,
275     //   other than to declare it, is ill-formed. [...]
276     //
277     // See if this is a function with constraints that need to be satisfied.
278     // Check this before deducing the return type, as it might instantiate the
279     // definition.
280     if (FD->getTrailingRequiresClause()) {
281       ConstraintSatisfaction Satisfaction;
282       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
283         // A diagnostic will have already been generated (non-constant
284         // constraint expression, for example)
285         return true;
286       if (!Satisfaction.IsSatisfied) {
287         Diag(Loc,
288              diag::err_reference_to_function_with_unsatisfied_constraints)
289             << D;
290         DiagnoseUnsatisfiedConstraint(Satisfaction);
291         return true;
292       }
293     }
294 
295     // If the function has a deduced return type, and we can't deduce it,
296     // then we can't use it either.
297     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
298         DeduceReturnType(FD, Loc))
299       return true;
300 
301     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
302       return true;
303 
304     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
305       return true;
306   }
307 
308   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
309     // Lambdas are only default-constructible or assignable in C++2a onwards.
310     if (MD->getParent()->isLambda() &&
311         ((isa<CXXConstructorDecl>(MD) &&
312           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
313          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
314       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
315         << !isa<CXXConstructorDecl>(MD);
316     }
317   }
318 
319   auto getReferencedObjCProp = [](const NamedDecl *D) ->
320                                       const ObjCPropertyDecl * {
321     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
322       return MD->findPropertyDecl();
323     return nullptr;
324   };
325   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
326     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
327       return true;
328   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
329       return true;
330   }
331 
332   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
333   // Only the variables omp_in and omp_out are allowed in the combiner.
334   // Only the variables omp_priv and omp_orig are allowed in the
335   // initializer-clause.
336   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
337   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
338       isa<VarDecl>(D)) {
339     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
340         << getCurFunction()->HasOMPDeclareReductionCombiner;
341     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
342     return true;
343   }
344 
345   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
346   //  List-items in map clauses on this construct may only refer to the declared
347   //  variable var and entities that could be referenced by a procedure defined
348   //  at the same location
349   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
350       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
351     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
352         << getOpenMPDeclareMapperVarName();
353     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
354     return true;
355   }
356 
357   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
358     Diag(Loc, diag::err_use_of_empty_using_if_exists);
359     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
360     return true;
361   }
362 
363   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
364                              AvoidPartialAvailabilityChecks, ClassReceiver);
365 
366   DiagnoseUnusedOfDecl(*this, D, Loc);
367 
368   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
369 
370   if (auto *VD = dyn_cast<ValueDecl>(D))
371     checkTypeSupport(VD->getType(), Loc, VD);
372 
373   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
374     if (!Context.getTargetInfo().isTLSSupported())
375       if (const auto *VD = dyn_cast<VarDecl>(D))
376         if (VD->getTLSKind() != VarDecl::TLS_None)
377           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
378   }
379 
380   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
381       !isUnevaluatedContext()) {
382     // C++ [expr.prim.req.nested] p3
383     //   A local parameter shall only appear as an unevaluated operand
384     //   (Clause 8) within the constraint-expression.
385     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
386         << D;
387     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
388     return true;
389   }
390 
391   return false;
392 }
393 
394 /// DiagnoseSentinelCalls - This routine checks whether a call or
395 /// message-send is to a declaration with the sentinel attribute, and
396 /// if so, it checks that the requirements of the sentinel are
397 /// satisfied.
398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
399                                  ArrayRef<Expr *> Args) {
400   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
401   if (!attr)
402     return;
403 
404   // The number of formal parameters of the declaration.
405   unsigned numFormalParams;
406 
407   // The kind of declaration.  This is also an index into a %select in
408   // the diagnostic.
409   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
410 
411   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
412     numFormalParams = MD->param_size();
413     calleeType = CT_Method;
414   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415     numFormalParams = FD->param_size();
416     calleeType = CT_Function;
417   } else if (isa<VarDecl>(D)) {
418     QualType type = cast<ValueDecl>(D)->getType();
419     const FunctionType *fn = nullptr;
420     if (const PointerType *ptr = type->getAs<PointerType>()) {
421       fn = ptr->getPointeeType()->getAs<FunctionType>();
422       if (!fn) return;
423       calleeType = CT_Function;
424     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
425       fn = ptr->getPointeeType()->castAs<FunctionType>();
426       calleeType = CT_Block;
427     } else {
428       return;
429     }
430 
431     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
432       numFormalParams = proto->getNumParams();
433     } else {
434       numFormalParams = 0;
435     }
436   } else {
437     return;
438   }
439 
440   // "nullPos" is the number of formal parameters at the end which
441   // effectively count as part of the variadic arguments.  This is
442   // useful if you would prefer to not have *any* formal parameters,
443   // but the language forces you to have at least one.
444   unsigned nullPos = attr->getNullPos();
445   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
446   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
447 
448   // The number of arguments which should follow the sentinel.
449   unsigned numArgsAfterSentinel = attr->getSentinel();
450 
451   // If there aren't enough arguments for all the formal parameters,
452   // the sentinel, and the args after the sentinel, complain.
453   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
454     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
455     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
456     return;
457   }
458 
459   // Otherwise, find the sentinel expression.
460   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
461   if (!sentinelExpr) return;
462   if (sentinelExpr->isValueDependent()) return;
463   if (Context.isSentinelNullExpr(sentinelExpr)) return;
464 
465   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
466   // or 'NULL' if those are actually defined in the context.  Only use
467   // 'nil' for ObjC methods, where it's much more likely that the
468   // variadic arguments form a list of object pointers.
469   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
470   std::string NullValue;
471   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
472     NullValue = "nil";
473   else if (getLangOpts().CPlusPlus11)
474     NullValue = "nullptr";
475   else if (PP.isMacroDefined("NULL"))
476     NullValue = "NULL";
477   else
478     NullValue = "(void*) 0";
479 
480   if (MissingNilLoc.isInvalid())
481     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
482   else
483     Diag(MissingNilLoc, diag::warn_missing_sentinel)
484       << int(calleeType)
485       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
486   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
487 }
488 
489 SourceRange Sema::getExprRange(Expr *E) const {
490   return E ? E->getSourceRange() : SourceRange();
491 }
492 
493 //===----------------------------------------------------------------------===//
494 //  Standard Promotions and Conversions
495 //===----------------------------------------------------------------------===//
496 
497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
499   // Handle any placeholder expressions which made it here.
500   if (E->hasPlaceholderType()) {
501     ExprResult result = CheckPlaceholderExpr(E);
502     if (result.isInvalid()) return ExprError();
503     E = result.get();
504   }
505 
506   QualType Ty = E->getType();
507   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
508 
509   if (Ty->isFunctionType()) {
510     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
511       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
512         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
513           return ExprError();
514 
515     E = ImpCastExprToType(E, Context.getPointerType(Ty),
516                           CK_FunctionToPointerDecay).get();
517   } else if (Ty->isArrayType()) {
518     // In C90 mode, arrays only promote to pointers if the array expression is
519     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
520     // type 'array of type' is converted to an expression that has type 'pointer
521     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
522     // that has type 'array of type' ...".  The relevant change is "an lvalue"
523     // (C90) to "an expression" (C99).
524     //
525     // C++ 4.2p1:
526     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
527     // T" can be converted to an rvalue of type "pointer to T".
528     //
529     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
530       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
531                                          CK_ArrayToPointerDecay);
532       if (Res.isInvalid())
533         return ExprError();
534       E = Res.get();
535     }
536   }
537   return E;
538 }
539 
540 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
541   // Check to see if we are dereferencing a null pointer.  If so,
542   // and if not volatile-qualified, this is undefined behavior that the
543   // optimizer will delete, so warn about it.  People sometimes try to use this
544   // to get a deterministic trap and are surprised by clang's behavior.  This
545   // only handles the pattern "*null", which is a very syntactic check.
546   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
547   if (UO && UO->getOpcode() == UO_Deref &&
548       UO->getSubExpr()->getType()->isPointerType()) {
549     const LangAS AS =
550         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
551     if ((!isTargetAddressSpace(AS) ||
552          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
553         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
554             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
555         !UO->getType().isVolatileQualified()) {
556       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
557                             S.PDiag(diag::warn_indirection_through_null)
558                                 << UO->getSubExpr()->getSourceRange());
559       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
560                             S.PDiag(diag::note_indirection_through_null));
561     }
562   }
563 }
564 
565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
566                                     SourceLocation AssignLoc,
567                                     const Expr* RHS) {
568   const ObjCIvarDecl *IV = OIRE->getDecl();
569   if (!IV)
570     return;
571 
572   DeclarationName MemberName = IV->getDeclName();
573   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
574   if (!Member || !Member->isStr("isa"))
575     return;
576 
577   const Expr *Base = OIRE->getBase();
578   QualType BaseType = Base->getType();
579   if (OIRE->isArrow())
580     BaseType = BaseType->getPointeeType();
581   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
582     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
583       ObjCInterfaceDecl *ClassDeclared = nullptr;
584       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
585       if (!ClassDeclared->getSuperClass()
586           && (*ClassDeclared->ivar_begin()) == IV) {
587         if (RHS) {
588           NamedDecl *ObjectSetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_setClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectSetClass) {
593             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
594             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
595                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
596                                               "object_setClass(")
597                 << FixItHint::CreateReplacement(
598                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
599                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
600           }
601           else
602             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
603         } else {
604           NamedDecl *ObjectGetClass =
605             S.LookupSingleName(S.TUScope,
606                                &S.Context.Idents.get("object_getClass"),
607                                SourceLocation(), S.LookupOrdinaryName);
608           if (ObjectGetClass)
609             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
610                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
611                                               "object_getClass(")
612                 << FixItHint::CreateReplacement(
613                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
614           else
615             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
616         }
617         S.Diag(IV->getLocation(), diag::note_ivar_decl);
618       }
619     }
620 }
621 
622 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
623   // Handle any placeholder expressions which made it here.
624   if (E->hasPlaceholderType()) {
625     ExprResult result = CheckPlaceholderExpr(E);
626     if (result.isInvalid()) return ExprError();
627     E = result.get();
628   }
629 
630   // C++ [conv.lval]p1:
631   //   A glvalue of a non-function, non-array type T can be
632   //   converted to a prvalue.
633   if (!E->isGLValue()) return E;
634 
635   QualType T = E->getType();
636   assert(!T.isNull() && "r-value conversion on typeless expression?");
637 
638   // lvalue-to-rvalue conversion cannot be applied to function or array types.
639   if (T->isFunctionType() || T->isArrayType())
640     return E;
641 
642   // We don't want to throw lvalue-to-rvalue casts on top of
643   // expressions of certain types in C++.
644   if (getLangOpts().CPlusPlus &&
645       (E->getType() == Context.OverloadTy ||
646        T->isDependentType() ||
647        T->isRecordType()))
648     return E;
649 
650   // The C standard is actually really unclear on this point, and
651   // DR106 tells us what the result should be but not why.  It's
652   // generally best to say that void types just doesn't undergo
653   // lvalue-to-rvalue at all.  Note that expressions of unqualified
654   // 'void' type are never l-values, but qualified void can be.
655   if (T->isVoidType())
656     return E;
657 
658   // OpenCL usually rejects direct accesses to values of 'half' type.
659   if (getLangOpts().OpenCL &&
660       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
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->getBeginLoc(), "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   ExprResult Res = CheckLValueToRValueConversionOperand(E);
702   if (Res.isInvalid())
703     return Res;
704   E = Res.get();
705 
706   // Loading a __weak object implicitly retains the value, so we need a cleanup to
707   // balance that.
708   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709     Cleanup.setExprNeedsCleanups(true);
710 
711   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712     Cleanup.setExprNeedsCleanups(true);
713 
714   // C++ [conv.lval]p3:
715   //   If T is cv std::nullptr_t, the result is a null pointer constant.
716   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
717   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
718                                  CurFPFeatureOverrides());
719 
720   // C11 6.3.2.1p2:
721   //   ... if the lvalue has atomic type, the value has the non-atomic version
722   //   of the type of the lvalue ...
723   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724     T = Atomic->getValueType().getUnqualifiedType();
725     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726                                    nullptr, VK_PRValue, FPOptionsOverride());
727   }
728 
729   return Res;
730 }
731 
732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734   if (Res.isInvalid())
735     return ExprError();
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res;
740 }
741 
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745   QualType Ty = E->getType();
746   ExprResult Res = E;
747   // Only do implicit cast for a function type, but not for a pointer
748   // to function type.
749   if (Ty->isFunctionType()) {
750     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751                             CK_FunctionToPointerDecay);
752     if (Res.isInvalid())
753       return ExprError();
754   }
755   Res = DefaultLvalueConversion(Res.get());
756   if (Res.isInvalid())
757     return ExprError();
758   return Res.get();
759 }
760 
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767   // First, convert to an r-value.
768   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769   if (Res.isInvalid())
770     return ExprError();
771   E = Res.get();
772 
773   QualType Ty = E->getType();
774   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775 
776   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
777   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
778       (getLangOpts().getFPEvalMethod() !=
779            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
780        PP.getLastFPEvalPragmaLocation().isValid())) {
781     switch (EvalMethod) {
782     default:
783       llvm_unreachable("Unrecognized float evaluation method");
784       break;
785     case LangOptions::FEM_UnsetOnCommandLine:
786       llvm_unreachable("Float evaluation method should be set by now");
787       break;
788     case LangOptions::FEM_Double:
789       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
790         // Widen the expression to double.
791         return Ty->isComplexType()
792                    ? ImpCastExprToType(E,
793                                        Context.getComplexType(Context.DoubleTy),
794                                        CK_FloatingComplexCast)
795                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
796       break;
797     case LangOptions::FEM_Extended:
798       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
799         // Widen the expression to long double.
800         return Ty->isComplexType()
801                    ? ImpCastExprToType(
802                          E, Context.getComplexType(Context.LongDoubleTy),
803                          CK_FloatingComplexCast)
804                    : ImpCastExprToType(E, Context.LongDoubleTy,
805                                        CK_FloatingCast);
806       break;
807     }
808   }
809 
810   // Half FP have to be promoted to float unless it is natively supported
811   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
812     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
813 
814   // Try to perform integral promotions if the object has a theoretically
815   // promotable type.
816   if (Ty->isIntegralOrUnscopedEnumerationType()) {
817     // C99 6.3.1.1p2:
818     //
819     //   The following may be used in an expression wherever an int or
820     //   unsigned int may be used:
821     //     - an object or expression with an integer type whose integer
822     //       conversion rank is less than or equal to the rank of int
823     //       and unsigned int.
824     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
825     //
826     //   If an int can represent all values of the original type, the
827     //   value is converted to an int; otherwise, it is converted to an
828     //   unsigned int. These are called the integer promotions. All
829     //   other types are unchanged by the integer promotions.
830 
831     QualType PTy = Context.isPromotableBitField(E);
832     if (!PTy.isNull()) {
833       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
834       return E;
835     }
836     if (Ty->isPromotableIntegerType()) {
837       QualType PT = Context.getPromotedIntegerType(Ty);
838       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
839       return E;
840     }
841   }
842   return E;
843 }
844 
845 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
846 /// do not have a prototype. Arguments that have type float or __fp16
847 /// are promoted to double. All other argument types are converted by
848 /// UsualUnaryConversions().
849 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
850   QualType Ty = E->getType();
851   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
852 
853   ExprResult Res = UsualUnaryConversions(E);
854   if (Res.isInvalid())
855     return ExprError();
856   E = Res.get();
857 
858   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
859   // promote to double.
860   // Note that default argument promotion applies only to float (and
861   // half/fp16); it does not apply to _Float16.
862   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
863   if (BTy && (BTy->getKind() == BuiltinType::Half ||
864               BTy->getKind() == BuiltinType::Float)) {
865     if (getLangOpts().OpenCL &&
866         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
867       if (BTy->getKind() == BuiltinType::Half) {
868         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
869       }
870     } else {
871       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
872     }
873   }
874   if (BTy &&
875       getLangOpts().getExtendIntArgs() ==
876           LangOptions::ExtendArgsKind::ExtendTo64 &&
877       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
878       Context.getTypeSizeInChars(BTy) <
879           Context.getTypeSizeInChars(Context.LongLongTy)) {
880     E = (Ty->isUnsignedIntegerType())
881             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
882                   .get()
883             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
884     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
885            "Unexpected typesize for LongLongTy");
886   }
887 
888   // C++ performs lvalue-to-rvalue conversion as a default argument
889   // promotion, even on class types, but note:
890   //   C++11 [conv.lval]p2:
891   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
892   //     operand or a subexpression thereof the value contained in the
893   //     referenced object is not accessed. Otherwise, if the glvalue
894   //     has a class type, the conversion copy-initializes a temporary
895   //     of type T from the glvalue and the result of the conversion
896   //     is a prvalue for the temporary.
897   // FIXME: add some way to gate this entire thing for correctness in
898   // potentially potentially evaluated contexts.
899   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
900     ExprResult Temp = PerformCopyInitialization(
901                        InitializedEntity::InitializeTemporary(E->getType()),
902                                                 E->getExprLoc(), E);
903     if (Temp.isInvalid())
904       return ExprError();
905     E = Temp.get();
906   }
907 
908   return E;
909 }
910 
911 /// Determine the degree of POD-ness for an expression.
912 /// Incomplete types are considered POD, since this check can be performed
913 /// when we're in an unevaluated context.
914 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
915   if (Ty->isIncompleteType()) {
916     // C++11 [expr.call]p7:
917     //   After these conversions, if the argument does not have arithmetic,
918     //   enumeration, pointer, pointer to member, or class type, the program
919     //   is ill-formed.
920     //
921     // Since we've already performed array-to-pointer and function-to-pointer
922     // decay, the only such type in C++ is cv void. This also handles
923     // initializer lists as variadic arguments.
924     if (Ty->isVoidType())
925       return VAK_Invalid;
926 
927     if (Ty->isObjCObjectType())
928       return VAK_Invalid;
929     return VAK_Valid;
930   }
931 
932   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
933     return VAK_Invalid;
934 
935   if (Ty.isCXX98PODType(Context))
936     return VAK_Valid;
937 
938   // C++11 [expr.call]p7:
939   //   Passing a potentially-evaluated argument of class type (Clause 9)
940   //   having a non-trivial copy constructor, a non-trivial move constructor,
941   //   or a non-trivial destructor, with no corresponding parameter,
942   //   is conditionally-supported with implementation-defined semantics.
943   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
944     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
945       if (!Record->hasNonTrivialCopyConstructor() &&
946           !Record->hasNonTrivialMoveConstructor() &&
947           !Record->hasNonTrivialDestructor())
948         return VAK_ValidInCXX11;
949 
950   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
951     return VAK_Valid;
952 
953   if (Ty->isObjCObjectType())
954     return VAK_Invalid;
955 
956   if (getLangOpts().MSVCCompat)
957     return VAK_MSVCUndefined;
958 
959   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
960   // permitted to reject them. We should consider doing so.
961   return VAK_Undefined;
962 }
963 
964 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
965   // Don't allow one to pass an Objective-C interface to a vararg.
966   const QualType &Ty = E->getType();
967   VarArgKind VAK = isValidVarArgType(Ty);
968 
969   // Complain about passing non-POD types through varargs.
970   switch (VAK) {
971   case VAK_ValidInCXX11:
972     DiagRuntimeBehavior(
973         E->getBeginLoc(), nullptr,
974         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
975     LLVM_FALLTHROUGH;
976   case VAK_Valid:
977     if (Ty->isRecordType()) {
978       // This is unlikely to be what the user intended. If the class has a
979       // 'c_str' member function, the user probably meant to call that.
980       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
981                           PDiag(diag::warn_pass_class_arg_to_vararg)
982                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
983     }
984     break;
985 
986   case VAK_Undefined:
987   case VAK_MSVCUndefined:
988     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
989                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
990                             << getLangOpts().CPlusPlus11 << Ty << CT);
991     break;
992 
993   case VAK_Invalid:
994     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
995       Diag(E->getBeginLoc(),
996            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
997           << Ty << CT;
998     else if (Ty->isObjCObjectType())
999       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1000                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1001                               << Ty << CT);
1002     else
1003       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1004           << isa<InitListExpr>(E) << Ty << CT;
1005     break;
1006   }
1007 }
1008 
1009 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1010 /// will create a trap if the resulting type is not a POD type.
1011 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1012                                                   FunctionDecl *FDecl) {
1013   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1014     // Strip the unbridged-cast placeholder expression off, if applicable.
1015     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1016         (CT == VariadicMethod ||
1017          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1018       E = stripARCUnbridgedCast(E);
1019 
1020     // Otherwise, do normal placeholder checking.
1021     } else {
1022       ExprResult ExprRes = CheckPlaceholderExpr(E);
1023       if (ExprRes.isInvalid())
1024         return ExprError();
1025       E = ExprRes.get();
1026     }
1027   }
1028 
1029   ExprResult ExprRes = DefaultArgumentPromotion(E);
1030   if (ExprRes.isInvalid())
1031     return ExprError();
1032 
1033   // Copy blocks to the heap.
1034   if (ExprRes.get()->getType()->isBlockPointerType())
1035     maybeExtendBlockObject(ExprRes);
1036 
1037   E = ExprRes.get();
1038 
1039   // Diagnostics regarding non-POD argument types are
1040   // emitted along with format string checking in Sema::CheckFunctionCall().
1041   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1042     // Turn this into a trap.
1043     CXXScopeSpec SS;
1044     SourceLocation TemplateKWLoc;
1045     UnqualifiedId Name;
1046     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1047                        E->getBeginLoc());
1048     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1049                                           /*HasTrailingLParen=*/true,
1050                                           /*IsAddressOfOperand=*/false);
1051     if (TrapFn.isInvalid())
1052       return ExprError();
1053 
1054     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1055                                     None, E->getEndLoc());
1056     if (Call.isInvalid())
1057       return ExprError();
1058 
1059     ExprResult Comma =
1060         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1061     if (Comma.isInvalid())
1062       return ExprError();
1063     return Comma.get();
1064   }
1065 
1066   if (!getLangOpts().CPlusPlus &&
1067       RequireCompleteType(E->getExprLoc(), E->getType(),
1068                           diag::err_call_incomplete_argument))
1069     return ExprError();
1070 
1071   return E;
1072 }
1073 
1074 /// Converts an integer to complex float type.  Helper function of
1075 /// UsualArithmeticConversions()
1076 ///
1077 /// \return false if the integer expression is an integer type and is
1078 /// successfully converted to the complex type.
1079 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1080                                                   ExprResult &ComplexExpr,
1081                                                   QualType IntTy,
1082                                                   QualType ComplexTy,
1083                                                   bool SkipCast) {
1084   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1085   if (SkipCast) return false;
1086   if (IntTy->isIntegerType()) {
1087     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1088     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1089     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1090                                   CK_FloatingRealToComplex);
1091   } else {
1092     assert(IntTy->isComplexIntegerType());
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094                                   CK_IntegralComplexToFloatingComplex);
1095   }
1096   return false;
1097 }
1098 
1099 /// Handle arithmetic conversion with complex types.  Helper function of
1100 /// UsualArithmeticConversions()
1101 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1102                                              ExprResult &RHS, QualType LHSType,
1103                                              QualType RHSType,
1104                                              bool IsCompAssign) {
1105   // if we have an integer operand, the result is the complex type.
1106   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1107                                              /*skipCast*/false))
1108     return LHSType;
1109   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1110                                              /*skipCast*/IsCompAssign))
1111     return RHSType;
1112 
1113   // This handles complex/complex, complex/float, or float/complex.
1114   // When both operands are complex, the shorter operand is converted to the
1115   // type of the longer, and that is the type of the result. This corresponds
1116   // to what is done when combining two real floating-point operands.
1117   // The fun begins when size promotion occur across type domains.
1118   // From H&S 6.3.4: When one operand is complex and the other is a real
1119   // floating-point type, the less precise type is converted, within it's
1120   // real or complex domain, to the precision of the other type. For example,
1121   // when combining a "long double" with a "double _Complex", the
1122   // "double _Complex" is promoted to "long double _Complex".
1123 
1124   // Compute the rank of the two types, regardless of whether they are complex.
1125   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1126 
1127   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1128   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1129   QualType LHSElementType =
1130       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1131   QualType RHSElementType =
1132       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1133 
1134   QualType ResultType = S.Context.getComplexType(LHSElementType);
1135   if (Order < 0) {
1136     // Promote the precision of the LHS if not an assignment.
1137     ResultType = S.Context.getComplexType(RHSElementType);
1138     if (!IsCompAssign) {
1139       if (LHSComplexType)
1140         LHS =
1141             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1142       else
1143         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1144     }
1145   } else if (Order > 0) {
1146     // Promote the precision of the RHS.
1147     if (RHSComplexType)
1148       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1149     else
1150       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1151   }
1152   return ResultType;
1153 }
1154 
1155 /// Handle arithmetic conversion from integer to float.  Helper function
1156 /// of UsualArithmeticConversions()
1157 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1158                                            ExprResult &IntExpr,
1159                                            QualType FloatTy, QualType IntTy,
1160                                            bool ConvertFloat, bool ConvertInt) {
1161   if (IntTy->isIntegerType()) {
1162     if (ConvertInt)
1163       // Convert intExpr to the lhs floating point type.
1164       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1165                                     CK_IntegralToFloating);
1166     return FloatTy;
1167   }
1168 
1169   // Convert both sides to the appropriate complex float.
1170   assert(IntTy->isComplexIntegerType());
1171   QualType result = S.Context.getComplexType(FloatTy);
1172 
1173   // _Complex int -> _Complex float
1174   if (ConvertInt)
1175     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1176                                   CK_IntegralComplexToFloatingComplex);
1177 
1178   // float -> _Complex float
1179   if (ConvertFloat)
1180     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1181                                     CK_FloatingRealToComplex);
1182 
1183   return result;
1184 }
1185 
1186 /// Handle arithmethic conversion with floating point types.  Helper
1187 /// function of UsualArithmeticConversions()
1188 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1189                                       ExprResult &RHS, QualType LHSType,
1190                                       QualType RHSType, bool IsCompAssign) {
1191   bool LHSFloat = LHSType->isRealFloatingType();
1192   bool RHSFloat = RHSType->isRealFloatingType();
1193 
1194   // N1169 4.1.4: If one of the operands has a floating type and the other
1195   //              operand has a fixed-point type, the fixed-point operand
1196   //              is converted to the floating type [...]
1197   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1198     if (LHSFloat)
1199       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1200     else if (!IsCompAssign)
1201       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1202     return LHSFloat ? LHSType : RHSType;
1203   }
1204 
1205   // If we have two real floating types, convert the smaller operand
1206   // to the bigger result.
1207   if (LHSFloat && RHSFloat) {
1208     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1209     if (order > 0) {
1210       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1211       return LHSType;
1212     }
1213 
1214     assert(order < 0 && "illegal float comparison");
1215     if (!IsCompAssign)
1216       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1217     return RHSType;
1218   }
1219 
1220   if (LHSFloat) {
1221     // Half FP has to be promoted to float unless it is natively supported
1222     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1223       LHSType = S.Context.FloatTy;
1224 
1225     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1226                                       /*ConvertFloat=*/!IsCompAssign,
1227                                       /*ConvertInt=*/ true);
1228   }
1229   assert(RHSFloat);
1230   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1231                                     /*ConvertFloat=*/ true,
1232                                     /*ConvertInt=*/!IsCompAssign);
1233 }
1234 
1235 /// Diagnose attempts to convert between __float128, __ibm128 and
1236 /// long double if there is no support for such conversion.
1237 /// Helper function of UsualArithmeticConversions().
1238 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1239                                       QualType RHSType) {
1240   // No issue if either is not a floating point type.
1241   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1242     return false;
1243 
1244   // No issue if both have the same 128-bit float semantics.
1245   auto *LHSComplex = LHSType->getAs<ComplexType>();
1246   auto *RHSComplex = RHSType->getAs<ComplexType>();
1247 
1248   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1249   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1250 
1251   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1252   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1253 
1254   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1255        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1256       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1257        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1258     return false;
1259 
1260   return true;
1261 }
1262 
1263 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1264 
1265 namespace {
1266 /// These helper callbacks are placed in an anonymous namespace to
1267 /// permit their use as function template parameters.
1268 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1269   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1270 }
1271 
1272 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1273   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1274                              CK_IntegralComplexCast);
1275 }
1276 }
1277 
1278 /// Handle integer arithmetic conversions.  Helper function of
1279 /// UsualArithmeticConversions()
1280 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1281 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1282                                         ExprResult &RHS, QualType LHSType,
1283                                         QualType RHSType, bool IsCompAssign) {
1284   // The rules for this case are in C99 6.3.1.8
1285   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1286   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1287   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1288   if (LHSSigned == RHSSigned) {
1289     // Same signedness; use the higher-ranked type
1290     if (order >= 0) {
1291       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1292       return LHSType;
1293     } else if (!IsCompAssign)
1294       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1295     return RHSType;
1296   } else if (order != (LHSSigned ? 1 : -1)) {
1297     // The unsigned type has greater than or equal rank to the
1298     // signed type, so use the unsigned type
1299     if (RHSSigned) {
1300       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1301       return LHSType;
1302     } else if (!IsCompAssign)
1303       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1304     return RHSType;
1305   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1306     // The two types are different widths; if we are here, that
1307     // means the signed type is larger than the unsigned type, so
1308     // use the signed type.
1309     if (LHSSigned) {
1310       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1311       return LHSType;
1312     } else if (!IsCompAssign)
1313       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1314     return RHSType;
1315   } else {
1316     // The signed type is higher-ranked than the unsigned type,
1317     // but isn't actually any bigger (like unsigned int and long
1318     // on most 32-bit systems).  Use the unsigned type corresponding
1319     // to the signed type.
1320     QualType result =
1321       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1322     RHS = (*doRHSCast)(S, RHS.get(), result);
1323     if (!IsCompAssign)
1324       LHS = (*doLHSCast)(S, LHS.get(), result);
1325     return result;
1326   }
1327 }
1328 
1329 /// Handle conversions with GCC complex int extension.  Helper function
1330 /// of UsualArithmeticConversions()
1331 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1332                                            ExprResult &RHS, QualType LHSType,
1333                                            QualType RHSType,
1334                                            bool IsCompAssign) {
1335   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1336   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1337 
1338   if (LHSComplexInt && RHSComplexInt) {
1339     QualType LHSEltType = LHSComplexInt->getElementType();
1340     QualType RHSEltType = RHSComplexInt->getElementType();
1341     QualType ScalarType =
1342       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1343         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1344 
1345     return S.Context.getComplexType(ScalarType);
1346   }
1347 
1348   if (LHSComplexInt) {
1349     QualType LHSEltType = LHSComplexInt->getElementType();
1350     QualType ScalarType =
1351       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1352         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1353     QualType ComplexType = S.Context.getComplexType(ScalarType);
1354     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1355                               CK_IntegralRealToComplex);
1356 
1357     return ComplexType;
1358   }
1359 
1360   assert(RHSComplexInt);
1361 
1362   QualType RHSEltType = RHSComplexInt->getElementType();
1363   QualType ScalarType =
1364     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1365       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1366   QualType ComplexType = S.Context.getComplexType(ScalarType);
1367 
1368   if (!IsCompAssign)
1369     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1370                               CK_IntegralRealToComplex);
1371   return ComplexType;
1372 }
1373 
1374 /// Return the rank of a given fixed point or integer type. The value itself
1375 /// doesn't matter, but the values must be increasing with proper increasing
1376 /// rank as described in N1169 4.1.1.
1377 static unsigned GetFixedPointRank(QualType Ty) {
1378   const auto *BTy = Ty->getAs<BuiltinType>();
1379   assert(BTy && "Expected a builtin type.");
1380 
1381   switch (BTy->getKind()) {
1382   case BuiltinType::ShortFract:
1383   case BuiltinType::UShortFract:
1384   case BuiltinType::SatShortFract:
1385   case BuiltinType::SatUShortFract:
1386     return 1;
1387   case BuiltinType::Fract:
1388   case BuiltinType::UFract:
1389   case BuiltinType::SatFract:
1390   case BuiltinType::SatUFract:
1391     return 2;
1392   case BuiltinType::LongFract:
1393   case BuiltinType::ULongFract:
1394   case BuiltinType::SatLongFract:
1395   case BuiltinType::SatULongFract:
1396     return 3;
1397   case BuiltinType::ShortAccum:
1398   case BuiltinType::UShortAccum:
1399   case BuiltinType::SatShortAccum:
1400   case BuiltinType::SatUShortAccum:
1401     return 4;
1402   case BuiltinType::Accum:
1403   case BuiltinType::UAccum:
1404   case BuiltinType::SatAccum:
1405   case BuiltinType::SatUAccum:
1406     return 5;
1407   case BuiltinType::LongAccum:
1408   case BuiltinType::ULongAccum:
1409   case BuiltinType::SatLongAccum:
1410   case BuiltinType::SatULongAccum:
1411     return 6;
1412   default:
1413     if (BTy->isInteger())
1414       return 0;
1415     llvm_unreachable("Unexpected fixed point or integer type");
1416   }
1417 }
1418 
1419 /// handleFixedPointConversion - Fixed point operations between fixed
1420 /// point types and integers or other fixed point types do not fall under
1421 /// usual arithmetic conversion since these conversions could result in loss
1422 /// of precsision (N1169 4.1.4). These operations should be calculated with
1423 /// the full precision of their result type (N1169 4.1.6.2.1).
1424 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1425                                            QualType RHSTy) {
1426   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1427          "Expected at least one of the operands to be a fixed point type");
1428   assert((LHSTy->isFixedPointOrIntegerType() ||
1429           RHSTy->isFixedPointOrIntegerType()) &&
1430          "Special fixed point arithmetic operation conversions are only "
1431          "applied to ints or other fixed point types");
1432 
1433   // If one operand has signed fixed-point type and the other operand has
1434   // unsigned fixed-point type, then the unsigned fixed-point operand is
1435   // converted to its corresponding signed fixed-point type and the resulting
1436   // type is the type of the converted operand.
1437   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1438     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1439   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1440     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1441 
1442   // The result type is the type with the highest rank, whereby a fixed-point
1443   // conversion rank is always greater than an integer conversion rank; if the
1444   // type of either of the operands is a saturating fixedpoint type, the result
1445   // type shall be the saturating fixed-point type corresponding to the type
1446   // with the highest rank; the resulting value is converted (taking into
1447   // account rounding and overflow) to the precision of the resulting type.
1448   // Same ranks between signed and unsigned types are resolved earlier, so both
1449   // types are either signed or both unsigned at this point.
1450   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1451   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1452 
1453   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1454 
1455   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1456     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1457 
1458   return ResultTy;
1459 }
1460 
1461 /// Check that the usual arithmetic conversions can be performed on this pair of
1462 /// expressions that might be of enumeration type.
1463 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1464                                            SourceLocation Loc,
1465                                            Sema::ArithConvKind ACK) {
1466   // C++2a [expr.arith.conv]p1:
1467   //   If one operand is of enumeration type and the other operand is of a
1468   //   different enumeration type or a floating-point type, this behavior is
1469   //   deprecated ([depr.arith.conv.enum]).
1470   //
1471   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1472   // Eventually we will presumably reject these cases (in C++23 onwards?).
1473   QualType L = LHS->getType(), R = RHS->getType();
1474   bool LEnum = L->isUnscopedEnumerationType(),
1475        REnum = R->isUnscopedEnumerationType();
1476   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1477   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1478       (REnum && L->isFloatingType())) {
1479     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1480                     ? diag::warn_arith_conv_enum_float_cxx20
1481                     : diag::warn_arith_conv_enum_float)
1482         << LHS->getSourceRange() << RHS->getSourceRange()
1483         << (int)ACK << LEnum << L << R;
1484   } else if (!IsCompAssign && LEnum && REnum &&
1485              !S.Context.hasSameUnqualifiedType(L, R)) {
1486     unsigned DiagID;
1487     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1488         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1489       // If either enumeration type is unnamed, it's less likely that the
1490       // user cares about this, but this situation is still deprecated in
1491       // C++2a. Use a different warning group.
1492       DiagID = S.getLangOpts().CPlusPlus20
1493                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1494                     : diag::warn_arith_conv_mixed_anon_enum_types;
1495     } else if (ACK == Sema::ACK_Conditional) {
1496       // Conditional expressions are separated out because they have
1497       // historically had a different warning flag.
1498       DiagID = S.getLangOpts().CPlusPlus20
1499                    ? diag::warn_conditional_mixed_enum_types_cxx20
1500                    : diag::warn_conditional_mixed_enum_types;
1501     } else if (ACK == Sema::ACK_Comparison) {
1502       // Comparison expressions are separated out because they have
1503       // historically had a different warning flag.
1504       DiagID = S.getLangOpts().CPlusPlus20
1505                    ? diag::warn_comparison_mixed_enum_types_cxx20
1506                    : diag::warn_comparison_mixed_enum_types;
1507     } else {
1508       DiagID = S.getLangOpts().CPlusPlus20
1509                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1510                    : diag::warn_arith_conv_mixed_enum_types;
1511     }
1512     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1513                         << (int)ACK << L << R;
1514   }
1515 }
1516 
1517 /// UsualArithmeticConversions - Performs various conversions that are common to
1518 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1519 /// routine returns the first non-arithmetic type found. The client is
1520 /// responsible for emitting appropriate error diagnostics.
1521 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1522                                           SourceLocation Loc,
1523                                           ArithConvKind ACK) {
1524   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1525 
1526   if (ACK != ACK_CompAssign) {
1527     LHS = UsualUnaryConversions(LHS.get());
1528     if (LHS.isInvalid())
1529       return QualType();
1530   }
1531 
1532   RHS = UsualUnaryConversions(RHS.get());
1533   if (RHS.isInvalid())
1534     return QualType();
1535 
1536   // For conversion purposes, we ignore any qualifiers.
1537   // For example, "const float" and "float" are equivalent.
1538   QualType LHSType =
1539     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1540   QualType RHSType =
1541     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1542 
1543   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1544   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1545     LHSType = AtomicLHS->getValueType();
1546 
1547   // If both types are identical, no conversion is needed.
1548   if (LHSType == RHSType)
1549     return LHSType;
1550 
1551   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1552   // The caller can deal with this (e.g. pointer + int).
1553   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1554     return QualType();
1555 
1556   // Apply unary and bitfield promotions to the LHS's type.
1557   QualType LHSUnpromotedType = LHSType;
1558   if (LHSType->isPromotableIntegerType())
1559     LHSType = Context.getPromotedIntegerType(LHSType);
1560   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1561   if (!LHSBitfieldPromoteTy.isNull())
1562     LHSType = LHSBitfieldPromoteTy;
1563   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1564     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1565 
1566   // If both types are identical, no conversion is needed.
1567   if (LHSType == RHSType)
1568     return LHSType;
1569 
1570   // At this point, we have two different arithmetic types.
1571 
1572   // Diagnose attempts to convert between __ibm128, __float128 and long double
1573   // where such conversions currently can't be handled.
1574   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1575     return QualType();
1576 
1577   // Handle complex types first (C99 6.3.1.8p1).
1578   if (LHSType->isComplexType() || RHSType->isComplexType())
1579     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1580                                         ACK == ACK_CompAssign);
1581 
1582   // Now handle "real" floating types (i.e. float, double, long double).
1583   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1584     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1585                                  ACK == ACK_CompAssign);
1586 
1587   // Handle GCC complex int extension.
1588   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1589     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1590                                       ACK == ACK_CompAssign);
1591 
1592   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1593     return handleFixedPointConversion(*this, LHSType, RHSType);
1594 
1595   // Finally, we have two differing integer types.
1596   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1597            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1598 }
1599 
1600 //===----------------------------------------------------------------------===//
1601 //  Semantic Analysis for various Expression Types
1602 //===----------------------------------------------------------------------===//
1603 
1604 
1605 ExprResult
1606 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1607                                 SourceLocation DefaultLoc,
1608                                 SourceLocation RParenLoc,
1609                                 Expr *ControllingExpr,
1610                                 ArrayRef<ParsedType> ArgTypes,
1611                                 ArrayRef<Expr *> ArgExprs) {
1612   unsigned NumAssocs = ArgTypes.size();
1613   assert(NumAssocs == ArgExprs.size());
1614 
1615   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1616   for (unsigned i = 0; i < NumAssocs; ++i) {
1617     if (ArgTypes[i])
1618       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1619     else
1620       Types[i] = nullptr;
1621   }
1622 
1623   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1624                                              ControllingExpr,
1625                                              llvm::makeArrayRef(Types, NumAssocs),
1626                                              ArgExprs);
1627   delete [] Types;
1628   return ER;
1629 }
1630 
1631 ExprResult
1632 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1633                                  SourceLocation DefaultLoc,
1634                                  SourceLocation RParenLoc,
1635                                  Expr *ControllingExpr,
1636                                  ArrayRef<TypeSourceInfo *> Types,
1637                                  ArrayRef<Expr *> Exprs) {
1638   unsigned NumAssocs = Types.size();
1639   assert(NumAssocs == Exprs.size());
1640 
1641   // Decay and strip qualifiers for the controlling expression type, and handle
1642   // placeholder type replacement. See committee discussion from WG14 DR423.
1643   {
1644     EnterExpressionEvaluationContext Unevaluated(
1645         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1646     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1647     if (R.isInvalid())
1648       return ExprError();
1649     ControllingExpr = R.get();
1650   }
1651 
1652   // The controlling expression is an unevaluated operand, so side effects are
1653   // likely unintended.
1654   if (!inTemplateInstantiation() &&
1655       ControllingExpr->HasSideEffects(Context, false))
1656     Diag(ControllingExpr->getExprLoc(),
1657          diag::warn_side_effects_unevaluated_context);
1658 
1659   bool TypeErrorFound = false,
1660        IsResultDependent = ControllingExpr->isTypeDependent(),
1661        ContainsUnexpandedParameterPack
1662          = ControllingExpr->containsUnexpandedParameterPack();
1663 
1664   for (unsigned i = 0; i < NumAssocs; ++i) {
1665     if (Exprs[i]->containsUnexpandedParameterPack())
1666       ContainsUnexpandedParameterPack = true;
1667 
1668     if (Types[i]) {
1669       if (Types[i]->getType()->containsUnexpandedParameterPack())
1670         ContainsUnexpandedParameterPack = true;
1671 
1672       if (Types[i]->getType()->isDependentType()) {
1673         IsResultDependent = true;
1674       } else {
1675         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1676         // complete object type other than a variably modified type."
1677         unsigned D = 0;
1678         if (Types[i]->getType()->isIncompleteType())
1679           D = diag::err_assoc_type_incomplete;
1680         else if (!Types[i]->getType()->isObjectType())
1681           D = diag::err_assoc_type_nonobject;
1682         else if (Types[i]->getType()->isVariablyModifiedType())
1683           D = diag::err_assoc_type_variably_modified;
1684 
1685         if (D != 0) {
1686           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1687             << Types[i]->getTypeLoc().getSourceRange()
1688             << Types[i]->getType();
1689           TypeErrorFound = true;
1690         }
1691 
1692         // C11 6.5.1.1p2 "No two generic associations in the same generic
1693         // selection shall specify compatible types."
1694         for (unsigned j = i+1; j < NumAssocs; ++j)
1695           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1696               Context.typesAreCompatible(Types[i]->getType(),
1697                                          Types[j]->getType())) {
1698             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1699                  diag::err_assoc_compatible_types)
1700               << Types[j]->getTypeLoc().getSourceRange()
1701               << Types[j]->getType()
1702               << Types[i]->getType();
1703             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1704                  diag::note_compat_assoc)
1705               << Types[i]->getTypeLoc().getSourceRange()
1706               << Types[i]->getType();
1707             TypeErrorFound = true;
1708           }
1709       }
1710     }
1711   }
1712   if (TypeErrorFound)
1713     return ExprError();
1714 
1715   // If we determined that the generic selection is result-dependent, don't
1716   // try to compute the result expression.
1717   if (IsResultDependent)
1718     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1719                                         Exprs, DefaultLoc, RParenLoc,
1720                                         ContainsUnexpandedParameterPack);
1721 
1722   SmallVector<unsigned, 1> CompatIndices;
1723   unsigned DefaultIndex = -1U;
1724   for (unsigned i = 0; i < NumAssocs; ++i) {
1725     if (!Types[i])
1726       DefaultIndex = i;
1727     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1728                                         Types[i]->getType()))
1729       CompatIndices.push_back(i);
1730   }
1731 
1732   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1733   // type compatible with at most one of the types named in its generic
1734   // association list."
1735   if (CompatIndices.size() > 1) {
1736     // We strip parens here because the controlling expression is typically
1737     // parenthesized in macro definitions.
1738     ControllingExpr = ControllingExpr->IgnoreParens();
1739     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1740         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1741         << (unsigned)CompatIndices.size();
1742     for (unsigned I : CompatIndices) {
1743       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1744            diag::note_compat_assoc)
1745         << Types[I]->getTypeLoc().getSourceRange()
1746         << Types[I]->getType();
1747     }
1748     return ExprError();
1749   }
1750 
1751   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1752   // its controlling expression shall have type compatible with exactly one of
1753   // the types named in its generic association list."
1754   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1755     // We strip parens here because the controlling expression is typically
1756     // parenthesized in macro definitions.
1757     ControllingExpr = ControllingExpr->IgnoreParens();
1758     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1759         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1760     return ExprError();
1761   }
1762 
1763   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1764   // type name that is compatible with the type of the controlling expression,
1765   // then the result expression of the generic selection is the expression
1766   // in that generic association. Otherwise, the result expression of the
1767   // generic selection is the expression in the default generic association."
1768   unsigned ResultIndex =
1769     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1770 
1771   return GenericSelectionExpr::Create(
1772       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1773       ContainsUnexpandedParameterPack, ResultIndex);
1774 }
1775 
1776 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1777 /// location of the token and the offset of the ud-suffix within it.
1778 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1779                                      unsigned Offset) {
1780   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1781                                         S.getLangOpts());
1782 }
1783 
1784 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1785 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1786 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1787                                                  IdentifierInfo *UDSuffix,
1788                                                  SourceLocation UDSuffixLoc,
1789                                                  ArrayRef<Expr*> Args,
1790                                                  SourceLocation LitEndLoc) {
1791   assert(Args.size() <= 2 && "too many arguments for literal operator");
1792 
1793   QualType ArgTy[2];
1794   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1795     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1796     if (ArgTy[ArgIdx]->isArrayType())
1797       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1798   }
1799 
1800   DeclarationName OpName =
1801     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1802   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1803   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1804 
1805   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1806   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1807                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1808                               /*AllowStringTemplatePack*/ false,
1809                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1810     return ExprError();
1811 
1812   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1813 }
1814 
1815 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1816 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1817 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1818 /// multiple tokens.  However, the common case is that StringToks points to one
1819 /// string.
1820 ///
1821 ExprResult
1822 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1823   assert(!StringToks.empty() && "Must have at least one string!");
1824 
1825   StringLiteralParser Literal(StringToks, PP);
1826   if (Literal.hadError)
1827     return ExprError();
1828 
1829   SmallVector<SourceLocation, 4> StringTokLocs;
1830   for (const Token &Tok : StringToks)
1831     StringTokLocs.push_back(Tok.getLocation());
1832 
1833   QualType CharTy = Context.CharTy;
1834   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1835   if (Literal.isWide()) {
1836     CharTy = Context.getWideCharType();
1837     Kind = StringLiteral::Wide;
1838   } else if (Literal.isUTF8()) {
1839     if (getLangOpts().Char8)
1840       CharTy = Context.Char8Ty;
1841     Kind = StringLiteral::UTF8;
1842   } else if (Literal.isUTF16()) {
1843     CharTy = Context.Char16Ty;
1844     Kind = StringLiteral::UTF16;
1845   } else if (Literal.isUTF32()) {
1846     CharTy = Context.Char32Ty;
1847     Kind = StringLiteral::UTF32;
1848   } else if (Literal.isPascal()) {
1849     CharTy = Context.UnsignedCharTy;
1850   }
1851 
1852   // Warn on initializing an array of char from a u8 string literal; this
1853   // becomes ill-formed in C++2a.
1854   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1855       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1856     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1857 
1858     // Create removals for all 'u8' prefixes in the string literal(s). This
1859     // ensures C++2a compatibility (but may change the program behavior when
1860     // built by non-Clang compilers for which the execution character set is
1861     // not always UTF-8).
1862     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1863     SourceLocation RemovalDiagLoc;
1864     for (const Token &Tok : StringToks) {
1865       if (Tok.getKind() == tok::utf8_string_literal) {
1866         if (RemovalDiagLoc.isInvalid())
1867           RemovalDiagLoc = Tok.getLocation();
1868         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1869             Tok.getLocation(),
1870             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1871                                            getSourceManager(), getLangOpts())));
1872       }
1873     }
1874     Diag(RemovalDiagLoc, RemovalDiag);
1875   }
1876 
1877   QualType StrTy =
1878       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1879 
1880   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1881   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1882                                              Kind, Literal.Pascal, StrTy,
1883                                              &StringTokLocs[0],
1884                                              StringTokLocs.size());
1885   if (Literal.getUDSuffix().empty())
1886     return Lit;
1887 
1888   // We're building a user-defined literal.
1889   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1890   SourceLocation UDSuffixLoc =
1891     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1892                    Literal.getUDSuffixOffset());
1893 
1894   // Make sure we're allowed user-defined literals here.
1895   if (!UDLScope)
1896     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1897 
1898   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1899   //   operator "" X (str, len)
1900   QualType SizeType = Context.getSizeType();
1901 
1902   DeclarationName OpName =
1903     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1904   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1905   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1906 
1907   QualType ArgTy[] = {
1908     Context.getArrayDecayedType(StrTy), SizeType
1909   };
1910 
1911   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1912   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1913                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1914                                 /*AllowStringTemplatePack*/ true,
1915                                 /*DiagnoseMissing*/ true, Lit)) {
1916 
1917   case LOLR_Cooked: {
1918     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1919     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1920                                                     StringTokLocs[0]);
1921     Expr *Args[] = { Lit, LenArg };
1922 
1923     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1924   }
1925 
1926   case LOLR_Template: {
1927     TemplateArgumentListInfo ExplicitArgs;
1928     TemplateArgument Arg(Lit);
1929     TemplateArgumentLocInfo ArgInfo(Lit);
1930     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1931     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1932                                     &ExplicitArgs);
1933   }
1934 
1935   case LOLR_StringTemplatePack: {
1936     TemplateArgumentListInfo ExplicitArgs;
1937 
1938     unsigned CharBits = Context.getIntWidth(CharTy);
1939     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1940     llvm::APSInt Value(CharBits, CharIsUnsigned);
1941 
1942     TemplateArgument TypeArg(CharTy);
1943     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1944     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1945 
1946     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1947       Value = Lit->getCodeUnit(I);
1948       TemplateArgument Arg(Context, Value, CharTy);
1949       TemplateArgumentLocInfo ArgInfo;
1950       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1951     }
1952     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1953                                     &ExplicitArgs);
1954   }
1955   case LOLR_Raw:
1956   case LOLR_ErrorNoDiagnostic:
1957     llvm_unreachable("unexpected literal operator lookup result");
1958   case LOLR_Error:
1959     return ExprError();
1960   }
1961   llvm_unreachable("unexpected literal operator lookup result");
1962 }
1963 
1964 DeclRefExpr *
1965 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1966                        SourceLocation Loc,
1967                        const CXXScopeSpec *SS) {
1968   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1969   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1970 }
1971 
1972 DeclRefExpr *
1973 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1974                        const DeclarationNameInfo &NameInfo,
1975                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1976                        SourceLocation TemplateKWLoc,
1977                        const TemplateArgumentListInfo *TemplateArgs) {
1978   NestedNameSpecifierLoc NNS =
1979       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1980   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1981                           TemplateArgs);
1982 }
1983 
1984 // CUDA/HIP: Check whether a captured reference variable is referencing a
1985 // host variable in a device or host device lambda.
1986 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1987                                                             VarDecl *VD) {
1988   if (!S.getLangOpts().CUDA || !VD->hasInit())
1989     return false;
1990   assert(VD->getType()->isReferenceType());
1991 
1992   // Check whether the reference variable is referencing a host variable.
1993   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1994   if (!DRE)
1995     return false;
1996   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1997   if (!Referee || !Referee->hasGlobalStorage() ||
1998       Referee->hasAttr<CUDADeviceAttr>())
1999     return false;
2000 
2001   // Check whether the current function is a device or host device lambda.
2002   // Check whether the reference variable is a capture by getDeclContext()
2003   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2004   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2005   if (MD && MD->getParent()->isLambda() &&
2006       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2007       VD->getDeclContext() != MD)
2008     return true;
2009 
2010   return false;
2011 }
2012 
2013 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2014   // A declaration named in an unevaluated operand never constitutes an odr-use.
2015   if (isUnevaluatedContext())
2016     return NOUR_Unevaluated;
2017 
2018   // C++2a [basic.def.odr]p4:
2019   //   A variable x whose name appears as a potentially-evaluated expression e
2020   //   is odr-used by e unless [...] x is a reference that is usable in
2021   //   constant expressions.
2022   // CUDA/HIP:
2023   //   If a reference variable referencing a host variable is captured in a
2024   //   device or host device lambda, the value of the referee must be copied
2025   //   to the capture and the reference variable must be treated as odr-use
2026   //   since the value of the referee is not known at compile time and must
2027   //   be loaded from the captured.
2028   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2029     if (VD->getType()->isReferenceType() &&
2030         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2031         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2032         VD->isUsableInConstantExpressions(Context))
2033       return NOUR_Constant;
2034   }
2035 
2036   // All remaining non-variable cases constitute an odr-use. For variables, we
2037   // need to wait and see how the expression is used.
2038   return NOUR_None;
2039 }
2040 
2041 /// BuildDeclRefExpr - Build an expression that references a
2042 /// declaration that does not require a closure capture.
2043 DeclRefExpr *
2044 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2045                        const DeclarationNameInfo &NameInfo,
2046                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2047                        SourceLocation TemplateKWLoc,
2048                        const TemplateArgumentListInfo *TemplateArgs) {
2049   bool RefersToCapturedVariable =
2050       isa<VarDecl>(D) &&
2051       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2052 
2053   DeclRefExpr *E = DeclRefExpr::Create(
2054       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2055       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2056   MarkDeclRefReferenced(E);
2057 
2058   // C++ [except.spec]p17:
2059   //   An exception-specification is considered to be needed when:
2060   //   - in an expression, the function is the unique lookup result or
2061   //     the selected member of a set of overloaded functions.
2062   //
2063   // We delay doing this until after we've built the function reference and
2064   // marked it as used so that:
2065   //  a) if the function is defaulted, we get errors from defining it before /
2066   //     instead of errors from computing its exception specification, and
2067   //  b) if the function is a defaulted comparison, we can use the body we
2068   //     build when defining it as input to the exception specification
2069   //     computation rather than computing a new body.
2070   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2071     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2072       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2073         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2074     }
2075   }
2076 
2077   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2078       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2079       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2080     getCurFunction()->recordUseOfWeak(E);
2081 
2082   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2083   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2084     FD = IFD->getAnonField();
2085   if (FD) {
2086     UnusedPrivateFields.remove(FD);
2087     // Just in case we're building an illegal pointer-to-member.
2088     if (FD->isBitField())
2089       E->setObjectKind(OK_BitField);
2090   }
2091 
2092   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2093   // designates a bit-field.
2094   if (auto *BD = dyn_cast<BindingDecl>(D))
2095     if (auto *BE = BD->getBinding())
2096       E->setObjectKind(BE->getObjectKind());
2097 
2098   return E;
2099 }
2100 
2101 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2102 /// possibly a list of template arguments.
2103 ///
2104 /// If this produces template arguments, it is permitted to call
2105 /// DecomposeTemplateName.
2106 ///
2107 /// This actually loses a lot of source location information for
2108 /// non-standard name kinds; we should consider preserving that in
2109 /// some way.
2110 void
2111 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2112                              TemplateArgumentListInfo &Buffer,
2113                              DeclarationNameInfo &NameInfo,
2114                              const TemplateArgumentListInfo *&TemplateArgs) {
2115   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2116     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2117     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2118 
2119     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2120                                        Id.TemplateId->NumArgs);
2121     translateTemplateArguments(TemplateArgsPtr, Buffer);
2122 
2123     TemplateName TName = Id.TemplateId->Template.get();
2124     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2125     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2126     TemplateArgs = &Buffer;
2127   } else {
2128     NameInfo = GetNameFromUnqualifiedId(Id);
2129     TemplateArgs = nullptr;
2130   }
2131 }
2132 
2133 static void emitEmptyLookupTypoDiagnostic(
2134     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2135     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2136     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2137   DeclContext *Ctx =
2138       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2139   if (!TC) {
2140     // Emit a special diagnostic for failed member lookups.
2141     // FIXME: computing the declaration context might fail here (?)
2142     if (Ctx)
2143       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2144                                                  << SS.getRange();
2145     else
2146       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2147     return;
2148   }
2149 
2150   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2151   bool DroppedSpecifier =
2152       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2153   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2154                         ? diag::note_implicit_param_decl
2155                         : diag::note_previous_decl;
2156   if (!Ctx)
2157     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2158                          SemaRef.PDiag(NoteID));
2159   else
2160     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2161                                  << Typo << Ctx << DroppedSpecifier
2162                                  << SS.getRange(),
2163                          SemaRef.PDiag(NoteID));
2164 }
2165 
2166 /// Diagnose a lookup that found results in an enclosing class during error
2167 /// recovery. This usually indicates that the results were found in a dependent
2168 /// base class that could not be searched as part of a template definition.
2169 /// Always issues a diagnostic (though this may be only a warning in MS
2170 /// compatibility mode).
2171 ///
2172 /// Return \c true if the error is unrecoverable, or \c false if the caller
2173 /// should attempt to recover using these lookup results.
2174 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2175   // During a default argument instantiation the CurContext points
2176   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2177   // function parameter list, hence add an explicit check.
2178   bool isDefaultArgument =
2179       !CodeSynthesisContexts.empty() &&
2180       CodeSynthesisContexts.back().Kind ==
2181           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2182   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2183   bool isInstance = CurMethod && CurMethod->isInstance() &&
2184                     R.getNamingClass() == CurMethod->getParent() &&
2185                     !isDefaultArgument;
2186 
2187   // There are two ways we can find a class-scope declaration during template
2188   // instantiation that we did not find in the template definition: if it is a
2189   // member of a dependent base class, or if it is declared after the point of
2190   // use in the same class. Distinguish these by comparing the class in which
2191   // the member was found to the naming class of the lookup.
2192   unsigned DiagID = diag::err_found_in_dependent_base;
2193   unsigned NoteID = diag::note_member_declared_at;
2194   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2195     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2196                                       : diag::err_found_later_in_class;
2197   } else if (getLangOpts().MSVCCompat) {
2198     DiagID = diag::ext_found_in_dependent_base;
2199     NoteID = diag::note_dependent_member_use;
2200   }
2201 
2202   if (isInstance) {
2203     // Give a code modification hint to insert 'this->'.
2204     Diag(R.getNameLoc(), DiagID)
2205         << R.getLookupName()
2206         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2207     CheckCXXThisCapture(R.getNameLoc());
2208   } else {
2209     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2210     // they're not shadowed).
2211     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2212   }
2213 
2214   for (NamedDecl *D : R)
2215     Diag(D->getLocation(), NoteID);
2216 
2217   // Return true if we are inside a default argument instantiation
2218   // and the found name refers to an instance member function, otherwise
2219   // the caller will try to create an implicit member call and this is wrong
2220   // for default arguments.
2221   //
2222   // FIXME: Is this special case necessary? We could allow the caller to
2223   // diagnose this.
2224   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2225     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2226     return true;
2227   }
2228 
2229   // Tell the callee to try to recover.
2230   return false;
2231 }
2232 
2233 /// Diagnose an empty lookup.
2234 ///
2235 /// \return false if new lookup candidates were found
2236 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2237                                CorrectionCandidateCallback &CCC,
2238                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2239                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2240   DeclarationName Name = R.getLookupName();
2241 
2242   unsigned diagnostic = diag::err_undeclared_var_use;
2243   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2244   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2245       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2246       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2247     diagnostic = diag::err_undeclared_use;
2248     diagnostic_suggest = diag::err_undeclared_use_suggest;
2249   }
2250 
2251   // If the original lookup was an unqualified lookup, fake an
2252   // unqualified lookup.  This is useful when (for example) the
2253   // original lookup would not have found something because it was a
2254   // dependent name.
2255   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2256   while (DC) {
2257     if (isa<CXXRecordDecl>(DC)) {
2258       LookupQualifiedName(R, DC);
2259 
2260       if (!R.empty()) {
2261         // Don't give errors about ambiguities in this lookup.
2262         R.suppressDiagnostics();
2263 
2264         // If there's a best viable function among the results, only mention
2265         // that one in the notes.
2266         OverloadCandidateSet Candidates(R.getNameLoc(),
2267                                         OverloadCandidateSet::CSK_Normal);
2268         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2269         OverloadCandidateSet::iterator Best;
2270         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2271             OR_Success) {
2272           R.clear();
2273           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2274           R.resolveKind();
2275         }
2276 
2277         return DiagnoseDependentMemberLookup(R);
2278       }
2279 
2280       R.clear();
2281     }
2282 
2283     DC = DC->getLookupParent();
2284   }
2285 
2286   // We didn't find anything, so try to correct for a typo.
2287   TypoCorrection Corrected;
2288   if (S && Out) {
2289     SourceLocation TypoLoc = R.getNameLoc();
2290     assert(!ExplicitTemplateArgs &&
2291            "Diagnosing an empty lookup with explicit template args!");
2292     *Out = CorrectTypoDelayed(
2293         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2294         [=](const TypoCorrection &TC) {
2295           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2296                                         diagnostic, diagnostic_suggest);
2297         },
2298         nullptr, CTK_ErrorRecovery);
2299     if (*Out)
2300       return true;
2301   } else if (S &&
2302              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2303                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2304     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2305     bool DroppedSpecifier =
2306         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2307     R.setLookupName(Corrected.getCorrection());
2308 
2309     bool AcceptableWithRecovery = false;
2310     bool AcceptableWithoutRecovery = false;
2311     NamedDecl *ND = Corrected.getFoundDecl();
2312     if (ND) {
2313       if (Corrected.isOverloaded()) {
2314         OverloadCandidateSet OCS(R.getNameLoc(),
2315                                  OverloadCandidateSet::CSK_Normal);
2316         OverloadCandidateSet::iterator Best;
2317         for (NamedDecl *CD : Corrected) {
2318           if (FunctionTemplateDecl *FTD =
2319                    dyn_cast<FunctionTemplateDecl>(CD))
2320             AddTemplateOverloadCandidate(
2321                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2322                 Args, OCS);
2323           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2324             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2325               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2326                                    Args, OCS);
2327         }
2328         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2329         case OR_Success:
2330           ND = Best->FoundDecl;
2331           Corrected.setCorrectionDecl(ND);
2332           break;
2333         default:
2334           // FIXME: Arbitrarily pick the first declaration for the note.
2335           Corrected.setCorrectionDecl(ND);
2336           break;
2337         }
2338       }
2339       R.addDecl(ND);
2340       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2341         CXXRecordDecl *Record = nullptr;
2342         if (Corrected.getCorrectionSpecifier()) {
2343           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2344           Record = Ty->getAsCXXRecordDecl();
2345         }
2346         if (!Record)
2347           Record = cast<CXXRecordDecl>(
2348               ND->getDeclContext()->getRedeclContext());
2349         R.setNamingClass(Record);
2350       }
2351 
2352       auto *UnderlyingND = ND->getUnderlyingDecl();
2353       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2354                                isa<FunctionTemplateDecl>(UnderlyingND);
2355       // FIXME: If we ended up with a typo for a type name or
2356       // Objective-C class name, we're in trouble because the parser
2357       // is in the wrong place to recover. Suggest the typo
2358       // correction, but don't make it a fix-it since we're not going
2359       // to recover well anyway.
2360       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2361                                   getAsTypeTemplateDecl(UnderlyingND) ||
2362                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2363     } else {
2364       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2365       // because we aren't able to recover.
2366       AcceptableWithoutRecovery = true;
2367     }
2368 
2369     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2370       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2371                             ? diag::note_implicit_param_decl
2372                             : diag::note_previous_decl;
2373       if (SS.isEmpty())
2374         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2375                      PDiag(NoteID), AcceptableWithRecovery);
2376       else
2377         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2378                                   << Name << computeDeclContext(SS, false)
2379                                   << DroppedSpecifier << SS.getRange(),
2380                      PDiag(NoteID), AcceptableWithRecovery);
2381 
2382       // Tell the callee whether to try to recover.
2383       return !AcceptableWithRecovery;
2384     }
2385   }
2386   R.clear();
2387 
2388   // Emit a special diagnostic for failed member lookups.
2389   // FIXME: computing the declaration context might fail here (?)
2390   if (!SS.isEmpty()) {
2391     Diag(R.getNameLoc(), diag::err_no_member)
2392       << Name << computeDeclContext(SS, false)
2393       << SS.getRange();
2394     return true;
2395   }
2396 
2397   // Give up, we can't recover.
2398   Diag(R.getNameLoc(), diagnostic) << Name;
2399   return true;
2400 }
2401 
2402 /// In Microsoft mode, if we are inside a template class whose parent class has
2403 /// dependent base classes, and we can't resolve an unqualified identifier, then
2404 /// assume the identifier is a member of a dependent base class.  We can only
2405 /// recover successfully in static methods, instance methods, and other contexts
2406 /// where 'this' is available.  This doesn't precisely match MSVC's
2407 /// instantiation model, but it's close enough.
2408 static Expr *
2409 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2410                                DeclarationNameInfo &NameInfo,
2411                                SourceLocation TemplateKWLoc,
2412                                const TemplateArgumentListInfo *TemplateArgs) {
2413   // Only try to recover from lookup into dependent bases in static methods or
2414   // contexts where 'this' is available.
2415   QualType ThisType = S.getCurrentThisType();
2416   const CXXRecordDecl *RD = nullptr;
2417   if (!ThisType.isNull())
2418     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2419   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2420     RD = MD->getParent();
2421   if (!RD || !RD->hasAnyDependentBases())
2422     return nullptr;
2423 
2424   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2425   // is available, suggest inserting 'this->' as a fixit.
2426   SourceLocation Loc = NameInfo.getLoc();
2427   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2428   DB << NameInfo.getName() << RD;
2429 
2430   if (!ThisType.isNull()) {
2431     DB << FixItHint::CreateInsertion(Loc, "this->");
2432     return CXXDependentScopeMemberExpr::Create(
2433         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2434         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2435         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2436   }
2437 
2438   // Synthesize a fake NNS that points to the derived class.  This will
2439   // perform name lookup during template instantiation.
2440   CXXScopeSpec SS;
2441   auto *NNS =
2442       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2443   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2444   return DependentScopeDeclRefExpr::Create(
2445       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2446       TemplateArgs);
2447 }
2448 
2449 ExprResult
2450 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2451                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2452                         bool HasTrailingLParen, bool IsAddressOfOperand,
2453                         CorrectionCandidateCallback *CCC,
2454                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2455   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2456          "cannot be direct & operand and have a trailing lparen");
2457   if (SS.isInvalid())
2458     return ExprError();
2459 
2460   TemplateArgumentListInfo TemplateArgsBuffer;
2461 
2462   // Decompose the UnqualifiedId into the following data.
2463   DeclarationNameInfo NameInfo;
2464   const TemplateArgumentListInfo *TemplateArgs;
2465   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2466 
2467   DeclarationName Name = NameInfo.getName();
2468   IdentifierInfo *II = Name.getAsIdentifierInfo();
2469   SourceLocation NameLoc = NameInfo.getLoc();
2470 
2471   if (II && II->isEditorPlaceholder()) {
2472     // FIXME: When typed placeholders are supported we can create a typed
2473     // placeholder expression node.
2474     return ExprError();
2475   }
2476 
2477   // C++ [temp.dep.expr]p3:
2478   //   An id-expression is type-dependent if it contains:
2479   //     -- an identifier that was declared with a dependent type,
2480   //        (note: handled after lookup)
2481   //     -- a template-id that is dependent,
2482   //        (note: handled in BuildTemplateIdExpr)
2483   //     -- a conversion-function-id that specifies a dependent type,
2484   //     -- a nested-name-specifier that contains a class-name that
2485   //        names a dependent type.
2486   // Determine whether this is a member of an unknown specialization;
2487   // we need to handle these differently.
2488   bool DependentID = false;
2489   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2490       Name.getCXXNameType()->isDependentType()) {
2491     DependentID = true;
2492   } else if (SS.isSet()) {
2493     if (DeclContext *DC = computeDeclContext(SS, false)) {
2494       if (RequireCompleteDeclContext(SS, DC))
2495         return ExprError();
2496     } else {
2497       DependentID = true;
2498     }
2499   }
2500 
2501   if (DependentID)
2502     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2503                                       IsAddressOfOperand, TemplateArgs);
2504 
2505   // Perform the required lookup.
2506   LookupResult R(*this, NameInfo,
2507                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2508                      ? LookupObjCImplicitSelfParam
2509                      : LookupOrdinaryName);
2510   if (TemplateKWLoc.isValid() || TemplateArgs) {
2511     // Lookup the template name again to correctly establish the context in
2512     // which it was found. This is really unfortunate as we already did the
2513     // lookup to determine that it was a template name in the first place. If
2514     // this becomes a performance hit, we can work harder to preserve those
2515     // results until we get here but it's likely not worth it.
2516     bool MemberOfUnknownSpecialization;
2517     AssumedTemplateKind AssumedTemplate;
2518     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2519                            MemberOfUnknownSpecialization, TemplateKWLoc,
2520                            &AssumedTemplate))
2521       return ExprError();
2522 
2523     if (MemberOfUnknownSpecialization ||
2524         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2525       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2526                                         IsAddressOfOperand, TemplateArgs);
2527   } else {
2528     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2529     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2530 
2531     // If the result might be in a dependent base class, this is a dependent
2532     // id-expression.
2533     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2534       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2535                                         IsAddressOfOperand, TemplateArgs);
2536 
2537     // If this reference is in an Objective-C method, then we need to do
2538     // some special Objective-C lookup, too.
2539     if (IvarLookupFollowUp) {
2540       ExprResult E(LookupInObjCMethod(R, S, II, true));
2541       if (E.isInvalid())
2542         return ExprError();
2543 
2544       if (Expr *Ex = E.getAs<Expr>())
2545         return Ex;
2546     }
2547   }
2548 
2549   if (R.isAmbiguous())
2550     return ExprError();
2551 
2552   // This could be an implicitly declared function reference (legal in C90,
2553   // extension in C99, forbidden in C++).
2554   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2555     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2556     if (D) R.addDecl(D);
2557   }
2558 
2559   // Determine whether this name might be a candidate for
2560   // argument-dependent lookup.
2561   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2562 
2563   if (R.empty() && !ADL) {
2564     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2565       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2566                                                    TemplateKWLoc, TemplateArgs))
2567         return E;
2568     }
2569 
2570     // Don't diagnose an empty lookup for inline assembly.
2571     if (IsInlineAsmIdentifier)
2572       return ExprError();
2573 
2574     // If this name wasn't predeclared and if this is not a function
2575     // call, diagnose the problem.
2576     TypoExpr *TE = nullptr;
2577     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2578                                                        : nullptr);
2579     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2580     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2581            "Typo correction callback misconfigured");
2582     if (CCC) {
2583       // Make sure the callback knows what the typo being diagnosed is.
2584       CCC->setTypoName(II);
2585       if (SS.isValid())
2586         CCC->setTypoNNS(SS.getScopeRep());
2587     }
2588     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2589     // a template name, but we happen to have always already looked up the name
2590     // before we get here if it must be a template name.
2591     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2592                             None, &TE)) {
2593       if (TE && KeywordReplacement) {
2594         auto &State = getTypoExprState(TE);
2595         auto BestTC = State.Consumer->getNextCorrection();
2596         if (BestTC.isKeyword()) {
2597           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2598           if (State.DiagHandler)
2599             State.DiagHandler(BestTC);
2600           KeywordReplacement->startToken();
2601           KeywordReplacement->setKind(II->getTokenID());
2602           KeywordReplacement->setIdentifierInfo(II);
2603           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2604           // Clean up the state associated with the TypoExpr, since it has
2605           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2606           clearDelayedTypo(TE);
2607           // Signal that a correction to a keyword was performed by returning a
2608           // valid-but-null ExprResult.
2609           return (Expr*)nullptr;
2610         }
2611         State.Consumer->resetCorrectionStream();
2612       }
2613       return TE ? TE : ExprError();
2614     }
2615 
2616     assert(!R.empty() &&
2617            "DiagnoseEmptyLookup returned false but added no results");
2618 
2619     // If we found an Objective-C instance variable, let
2620     // LookupInObjCMethod build the appropriate expression to
2621     // reference the ivar.
2622     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2623       R.clear();
2624       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2625       // In a hopelessly buggy code, Objective-C instance variable
2626       // lookup fails and no expression will be built to reference it.
2627       if (!E.isInvalid() && !E.get())
2628         return ExprError();
2629       return E;
2630     }
2631   }
2632 
2633   // This is guaranteed from this point on.
2634   assert(!R.empty() || ADL);
2635 
2636   // Check whether this might be a C++ implicit instance member access.
2637   // C++ [class.mfct.non-static]p3:
2638   //   When an id-expression that is not part of a class member access
2639   //   syntax and not used to form a pointer to member is used in the
2640   //   body of a non-static member function of class X, if name lookup
2641   //   resolves the name in the id-expression to a non-static non-type
2642   //   member of some class C, the id-expression is transformed into a
2643   //   class member access expression using (*this) as the
2644   //   postfix-expression to the left of the . operator.
2645   //
2646   // But we don't actually need to do this for '&' operands if R
2647   // resolved to a function or overloaded function set, because the
2648   // expression is ill-formed if it actually works out to be a
2649   // non-static member function:
2650   //
2651   // C++ [expr.ref]p4:
2652   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2653   //   [t]he expression can be used only as the left-hand operand of a
2654   //   member function call.
2655   //
2656   // There are other safeguards against such uses, but it's important
2657   // to get this right here so that we don't end up making a
2658   // spuriously dependent expression if we're inside a dependent
2659   // instance method.
2660   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2661     bool MightBeImplicitMember;
2662     if (!IsAddressOfOperand)
2663       MightBeImplicitMember = true;
2664     else if (!SS.isEmpty())
2665       MightBeImplicitMember = false;
2666     else if (R.isOverloadedResult())
2667       MightBeImplicitMember = false;
2668     else if (R.isUnresolvableResult())
2669       MightBeImplicitMember = true;
2670     else
2671       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2672                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2673                               isa<MSPropertyDecl>(R.getFoundDecl());
2674 
2675     if (MightBeImplicitMember)
2676       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2677                                              R, TemplateArgs, S);
2678   }
2679 
2680   if (TemplateArgs || TemplateKWLoc.isValid()) {
2681 
2682     // In C++1y, if this is a variable template id, then check it
2683     // in BuildTemplateIdExpr().
2684     // The single lookup result must be a variable template declaration.
2685     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2686         Id.TemplateId->Kind == TNK_Var_template) {
2687       assert(R.getAsSingle<VarTemplateDecl>() &&
2688              "There should only be one declaration found.");
2689     }
2690 
2691     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2692   }
2693 
2694   return BuildDeclarationNameExpr(SS, R, ADL);
2695 }
2696 
2697 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2698 /// declaration name, generally during template instantiation.
2699 /// There's a large number of things which don't need to be done along
2700 /// this path.
2701 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2702     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2703     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2704   DeclContext *DC = computeDeclContext(SS, false);
2705   if (!DC)
2706     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2707                                      NameInfo, /*TemplateArgs=*/nullptr);
2708 
2709   if (RequireCompleteDeclContext(SS, DC))
2710     return ExprError();
2711 
2712   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2713   LookupQualifiedName(R, DC);
2714 
2715   if (R.isAmbiguous())
2716     return ExprError();
2717 
2718   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2719     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2720                                      NameInfo, /*TemplateArgs=*/nullptr);
2721 
2722   if (R.empty()) {
2723     // Don't diagnose problems with invalid record decl, the secondary no_member
2724     // diagnostic during template instantiation is likely bogus, e.g. if a class
2725     // is invalid because it's derived from an invalid base class, then missing
2726     // members were likely supposed to be inherited.
2727     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2728       if (CD->isInvalidDecl())
2729         return ExprError();
2730     Diag(NameInfo.getLoc(), diag::err_no_member)
2731       << NameInfo.getName() << DC << SS.getRange();
2732     return ExprError();
2733   }
2734 
2735   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2736     // Diagnose a missing typename if this resolved unambiguously to a type in
2737     // a dependent context.  If we can recover with a type, downgrade this to
2738     // a warning in Microsoft compatibility mode.
2739     unsigned DiagID = diag::err_typename_missing;
2740     if (RecoveryTSI && getLangOpts().MSVCCompat)
2741       DiagID = diag::ext_typename_missing;
2742     SourceLocation Loc = SS.getBeginLoc();
2743     auto D = Diag(Loc, DiagID);
2744     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2745       << SourceRange(Loc, NameInfo.getEndLoc());
2746 
2747     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2748     // context.
2749     if (!RecoveryTSI)
2750       return ExprError();
2751 
2752     // Only issue the fixit if we're prepared to recover.
2753     D << FixItHint::CreateInsertion(Loc, "typename ");
2754 
2755     // Recover by pretending this was an elaborated type.
2756     QualType Ty = Context.getTypeDeclType(TD);
2757     TypeLocBuilder TLB;
2758     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2759 
2760     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2761     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2762     QTL.setElaboratedKeywordLoc(SourceLocation());
2763     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2764 
2765     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2766 
2767     return ExprEmpty();
2768   }
2769 
2770   // Defend against this resolving to an implicit member access. We usually
2771   // won't get here if this might be a legitimate a class member (we end up in
2772   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2773   // a pointer-to-member or in an unevaluated context in C++11.
2774   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2775     return BuildPossibleImplicitMemberExpr(SS,
2776                                            /*TemplateKWLoc=*/SourceLocation(),
2777                                            R, /*TemplateArgs=*/nullptr, S);
2778 
2779   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2780 }
2781 
2782 /// The parser has read a name in, and Sema has detected that we're currently
2783 /// inside an ObjC method. Perform some additional checks and determine if we
2784 /// should form a reference to an ivar.
2785 ///
2786 /// Ideally, most of this would be done by lookup, but there's
2787 /// actually quite a lot of extra work involved.
2788 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2789                                         IdentifierInfo *II) {
2790   SourceLocation Loc = Lookup.getNameLoc();
2791   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2792 
2793   // Check for error condition which is already reported.
2794   if (!CurMethod)
2795     return DeclResult(true);
2796 
2797   // There are two cases to handle here.  1) scoped lookup could have failed,
2798   // in which case we should look for an ivar.  2) scoped lookup could have
2799   // found a decl, but that decl is outside the current instance method (i.e.
2800   // a global variable).  In these two cases, we do a lookup for an ivar with
2801   // this name, if the lookup sucedes, we replace it our current decl.
2802 
2803   // If we're in a class method, we don't normally want to look for
2804   // ivars.  But if we don't find anything else, and there's an
2805   // ivar, that's an error.
2806   bool IsClassMethod = CurMethod->isClassMethod();
2807 
2808   bool LookForIvars;
2809   if (Lookup.empty())
2810     LookForIvars = true;
2811   else if (IsClassMethod)
2812     LookForIvars = false;
2813   else
2814     LookForIvars = (Lookup.isSingleResult() &&
2815                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2816   ObjCInterfaceDecl *IFace = nullptr;
2817   if (LookForIvars) {
2818     IFace = CurMethod->getClassInterface();
2819     ObjCInterfaceDecl *ClassDeclared;
2820     ObjCIvarDecl *IV = nullptr;
2821     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2822       // Diagnose using an ivar in a class method.
2823       if (IsClassMethod) {
2824         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2825         return DeclResult(true);
2826       }
2827 
2828       // Diagnose the use of an ivar outside of the declaring class.
2829       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2830           !declaresSameEntity(ClassDeclared, IFace) &&
2831           !getLangOpts().DebuggerSupport)
2832         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2833 
2834       // Success.
2835       return IV;
2836     }
2837   } else if (CurMethod->isInstanceMethod()) {
2838     // We should warn if a local variable hides an ivar.
2839     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2840       ObjCInterfaceDecl *ClassDeclared;
2841       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2842         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2843             declaresSameEntity(IFace, ClassDeclared))
2844           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2845       }
2846     }
2847   } else if (Lookup.isSingleResult() &&
2848              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2849     // If accessing a stand-alone ivar in a class method, this is an error.
2850     if (const ObjCIvarDecl *IV =
2851             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2852       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2853       return DeclResult(true);
2854     }
2855   }
2856 
2857   // Didn't encounter an error, didn't find an ivar.
2858   return DeclResult(false);
2859 }
2860 
2861 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2862                                   ObjCIvarDecl *IV) {
2863   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2864   assert(CurMethod && CurMethod->isInstanceMethod() &&
2865          "should not reference ivar from this context");
2866 
2867   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2868   assert(IFace && "should not reference ivar from this context");
2869 
2870   // If we're referencing an invalid decl, just return this as a silent
2871   // error node.  The error diagnostic was already emitted on the decl.
2872   if (IV->isInvalidDecl())
2873     return ExprError();
2874 
2875   // Check if referencing a field with __attribute__((deprecated)).
2876   if (DiagnoseUseOfDecl(IV, Loc))
2877     return ExprError();
2878 
2879   // FIXME: This should use a new expr for a direct reference, don't
2880   // turn this into Self->ivar, just return a BareIVarExpr or something.
2881   IdentifierInfo &II = Context.Idents.get("self");
2882   UnqualifiedId SelfName;
2883   SelfName.setImplicitSelfParam(&II);
2884   CXXScopeSpec SelfScopeSpec;
2885   SourceLocation TemplateKWLoc;
2886   ExprResult SelfExpr =
2887       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2888                         /*HasTrailingLParen=*/false,
2889                         /*IsAddressOfOperand=*/false);
2890   if (SelfExpr.isInvalid())
2891     return ExprError();
2892 
2893   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2894   if (SelfExpr.isInvalid())
2895     return ExprError();
2896 
2897   MarkAnyDeclReferenced(Loc, IV, true);
2898 
2899   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2900   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2901       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2902     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2903 
2904   ObjCIvarRefExpr *Result = new (Context)
2905       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2906                       IV->getLocation(), SelfExpr.get(), true, true);
2907 
2908   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2909     if (!isUnevaluatedContext() &&
2910         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2911       getCurFunction()->recordUseOfWeak(Result);
2912   }
2913   if (getLangOpts().ObjCAutoRefCount)
2914     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2915       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2916 
2917   return Result;
2918 }
2919 
2920 /// The parser has read a name in, and Sema has detected that we're currently
2921 /// inside an ObjC method. Perform some additional checks and determine if we
2922 /// should form a reference to an ivar. If so, build an expression referencing
2923 /// that ivar.
2924 ExprResult
2925 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2926                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2927   // FIXME: Integrate this lookup step into LookupParsedName.
2928   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2929   if (Ivar.isInvalid())
2930     return ExprError();
2931   if (Ivar.isUsable())
2932     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2933                             cast<ObjCIvarDecl>(Ivar.get()));
2934 
2935   if (Lookup.empty() && II && AllowBuiltinCreation)
2936     LookupBuiltin(Lookup);
2937 
2938   // Sentinel value saying that we didn't do anything special.
2939   return ExprResult(false);
2940 }
2941 
2942 /// Cast a base object to a member's actual type.
2943 ///
2944 /// There are two relevant checks:
2945 ///
2946 /// C++ [class.access.base]p7:
2947 ///
2948 ///   If a class member access operator [...] is used to access a non-static
2949 ///   data member or non-static member function, the reference is ill-formed if
2950 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2951 ///   naming class of the right operand.
2952 ///
2953 /// C++ [expr.ref]p7:
2954 ///
2955 ///   If E2 is a non-static data member or a non-static member function, the
2956 ///   program is ill-formed if the class of which E2 is directly a member is an
2957 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2958 ///
2959 /// Note that the latter check does not consider access; the access of the
2960 /// "real" base class is checked as appropriate when checking the access of the
2961 /// member name.
2962 ExprResult
2963 Sema::PerformObjectMemberConversion(Expr *From,
2964                                     NestedNameSpecifier *Qualifier,
2965                                     NamedDecl *FoundDecl,
2966                                     NamedDecl *Member) {
2967   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2968   if (!RD)
2969     return From;
2970 
2971   QualType DestRecordType;
2972   QualType DestType;
2973   QualType FromRecordType;
2974   QualType FromType = From->getType();
2975   bool PointerConversions = false;
2976   if (isa<FieldDecl>(Member)) {
2977     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2978     auto FromPtrType = FromType->getAs<PointerType>();
2979     DestRecordType = Context.getAddrSpaceQualType(
2980         DestRecordType, FromPtrType
2981                             ? FromType->getPointeeType().getAddressSpace()
2982                             : FromType.getAddressSpace());
2983 
2984     if (FromPtrType) {
2985       DestType = Context.getPointerType(DestRecordType);
2986       FromRecordType = FromPtrType->getPointeeType();
2987       PointerConversions = true;
2988     } else {
2989       DestType = DestRecordType;
2990       FromRecordType = FromType;
2991     }
2992   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2993     if (Method->isStatic())
2994       return From;
2995 
2996     DestType = Method->getThisType();
2997     DestRecordType = DestType->getPointeeType();
2998 
2999     if (FromType->getAs<PointerType>()) {
3000       FromRecordType = FromType->getPointeeType();
3001       PointerConversions = true;
3002     } else {
3003       FromRecordType = FromType;
3004       DestType = DestRecordType;
3005     }
3006 
3007     LangAS FromAS = FromRecordType.getAddressSpace();
3008     LangAS DestAS = DestRecordType.getAddressSpace();
3009     if (FromAS != DestAS) {
3010       QualType FromRecordTypeWithoutAS =
3011           Context.removeAddrSpaceQualType(FromRecordType);
3012       QualType FromTypeWithDestAS =
3013           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3014       if (PointerConversions)
3015         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3016       From = ImpCastExprToType(From, FromTypeWithDestAS,
3017                                CK_AddressSpaceConversion, From->getValueKind())
3018                  .get();
3019     }
3020   } else {
3021     // No conversion necessary.
3022     return From;
3023   }
3024 
3025   if (DestType->isDependentType() || FromType->isDependentType())
3026     return From;
3027 
3028   // If the unqualified types are the same, no conversion is necessary.
3029   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3030     return From;
3031 
3032   SourceRange FromRange = From->getSourceRange();
3033   SourceLocation FromLoc = FromRange.getBegin();
3034 
3035   ExprValueKind VK = From->getValueKind();
3036 
3037   // C++ [class.member.lookup]p8:
3038   //   [...] Ambiguities can often be resolved by qualifying a name with its
3039   //   class name.
3040   //
3041   // If the member was a qualified name and the qualified referred to a
3042   // specific base subobject type, we'll cast to that intermediate type
3043   // first and then to the object in which the member is declared. That allows
3044   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3045   //
3046   //   class Base { public: int x; };
3047   //   class Derived1 : public Base { };
3048   //   class Derived2 : public Base { };
3049   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3050   //
3051   //   void VeryDerived::f() {
3052   //     x = 17; // error: ambiguous base subobjects
3053   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3054   //   }
3055   if (Qualifier && Qualifier->getAsType()) {
3056     QualType QType = QualType(Qualifier->getAsType(), 0);
3057     assert(QType->isRecordType() && "lookup done with non-record type");
3058 
3059     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3060 
3061     // In C++98, the qualifier type doesn't actually have to be a base
3062     // type of the object type, in which case we just ignore it.
3063     // Otherwise build the appropriate casts.
3064     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3065       CXXCastPath BasePath;
3066       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3067                                        FromLoc, FromRange, &BasePath))
3068         return ExprError();
3069 
3070       if (PointerConversions)
3071         QType = Context.getPointerType(QType);
3072       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3073                                VK, &BasePath).get();
3074 
3075       FromType = QType;
3076       FromRecordType = QRecordType;
3077 
3078       // If the qualifier type was the same as the destination type,
3079       // we're done.
3080       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3081         return From;
3082     }
3083   }
3084 
3085   CXXCastPath BasePath;
3086   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3087                                    FromLoc, FromRange, &BasePath,
3088                                    /*IgnoreAccess=*/true))
3089     return ExprError();
3090 
3091   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3092                            VK, &BasePath);
3093 }
3094 
3095 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3096                                       const LookupResult &R,
3097                                       bool HasTrailingLParen) {
3098   // Only when used directly as the postfix-expression of a call.
3099   if (!HasTrailingLParen)
3100     return false;
3101 
3102   // Never if a scope specifier was provided.
3103   if (SS.isSet())
3104     return false;
3105 
3106   // Only in C++ or ObjC++.
3107   if (!getLangOpts().CPlusPlus)
3108     return false;
3109 
3110   // Turn off ADL when we find certain kinds of declarations during
3111   // normal lookup:
3112   for (NamedDecl *D : R) {
3113     // C++0x [basic.lookup.argdep]p3:
3114     //     -- a declaration of a class member
3115     // Since using decls preserve this property, we check this on the
3116     // original decl.
3117     if (D->isCXXClassMember())
3118       return false;
3119 
3120     // C++0x [basic.lookup.argdep]p3:
3121     //     -- a block-scope function declaration that is not a
3122     //        using-declaration
3123     // NOTE: we also trigger this for function templates (in fact, we
3124     // don't check the decl type at all, since all other decl types
3125     // turn off ADL anyway).
3126     if (isa<UsingShadowDecl>(D))
3127       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3128     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3129       return false;
3130 
3131     // C++0x [basic.lookup.argdep]p3:
3132     //     -- a declaration that is neither a function or a function
3133     //        template
3134     // And also for builtin functions.
3135     if (isa<FunctionDecl>(D)) {
3136       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3137 
3138       // But also builtin functions.
3139       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3140         return false;
3141     } else if (!isa<FunctionTemplateDecl>(D))
3142       return false;
3143   }
3144 
3145   return true;
3146 }
3147 
3148 
3149 /// Diagnoses obvious problems with the use of the given declaration
3150 /// as an expression.  This is only actually called for lookups that
3151 /// were not overloaded, and it doesn't promise that the declaration
3152 /// will in fact be used.
3153 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3154   if (D->isInvalidDecl())
3155     return true;
3156 
3157   if (isa<TypedefNameDecl>(D)) {
3158     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3159     return true;
3160   }
3161 
3162   if (isa<ObjCInterfaceDecl>(D)) {
3163     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3164     return true;
3165   }
3166 
3167   if (isa<NamespaceDecl>(D)) {
3168     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3169     return true;
3170   }
3171 
3172   return false;
3173 }
3174 
3175 // Certain multiversion types should be treated as overloaded even when there is
3176 // only one result.
3177 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3178   assert(R.isSingleResult() && "Expected only a single result");
3179   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3180   return FD &&
3181          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3182 }
3183 
3184 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3185                                           LookupResult &R, bool NeedsADL,
3186                                           bool AcceptInvalidDecl) {
3187   // If this is a single, fully-resolved result and we don't need ADL,
3188   // just build an ordinary singleton decl ref.
3189   if (!NeedsADL && R.isSingleResult() &&
3190       !R.getAsSingle<FunctionTemplateDecl>() &&
3191       !ShouldLookupResultBeMultiVersionOverload(R))
3192     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3193                                     R.getRepresentativeDecl(), nullptr,
3194                                     AcceptInvalidDecl);
3195 
3196   // We only need to check the declaration if there's exactly one
3197   // result, because in the overloaded case the results can only be
3198   // functions and function templates.
3199   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3200       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3201     return ExprError();
3202 
3203   // Otherwise, just build an unresolved lookup expression.  Suppress
3204   // any lookup-related diagnostics; we'll hash these out later, when
3205   // we've picked a target.
3206   R.suppressDiagnostics();
3207 
3208   UnresolvedLookupExpr *ULE
3209     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3210                                    SS.getWithLocInContext(Context),
3211                                    R.getLookupNameInfo(),
3212                                    NeedsADL, R.isOverloadedResult(),
3213                                    R.begin(), R.end());
3214 
3215   return ULE;
3216 }
3217 
3218 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3219                                                ValueDecl *var);
3220 
3221 /// Complete semantic analysis for a reference to the given declaration.
3222 ExprResult Sema::BuildDeclarationNameExpr(
3223     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3224     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3225     bool AcceptInvalidDecl) {
3226   assert(D && "Cannot refer to a NULL declaration");
3227   assert(!isa<FunctionTemplateDecl>(D) &&
3228          "Cannot refer unambiguously to a function template");
3229 
3230   SourceLocation Loc = NameInfo.getLoc();
3231   if (CheckDeclInExpr(*this, Loc, D)) {
3232     // Recovery from invalid cases (e.g. D is an invalid Decl).
3233     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3234     // diagnostics, as invalid decls use int as a fallback type.
3235     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3236   }
3237 
3238   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3239     // Specifically diagnose references to class templates that are missing
3240     // a template argument list.
3241     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3242     return ExprError();
3243   }
3244 
3245   // Make sure that we're referring to a value.
3246   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3247     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3248     Diag(D->getLocation(), diag::note_declared_at);
3249     return ExprError();
3250   }
3251 
3252   // Check whether this declaration can be used. Note that we suppress
3253   // this check when we're going to perform argument-dependent lookup
3254   // on this function name, because this might not be the function
3255   // that overload resolution actually selects.
3256   if (DiagnoseUseOfDecl(D, Loc))
3257     return ExprError();
3258 
3259   auto *VD = cast<ValueDecl>(D);
3260 
3261   // Only create DeclRefExpr's for valid Decl's.
3262   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3263     return ExprError();
3264 
3265   // Handle members of anonymous structs and unions.  If we got here,
3266   // and the reference is to a class member indirect field, then this
3267   // must be the subject of a pointer-to-member expression.
3268   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3269     if (!indirectField->isCXXClassMember())
3270       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3271                                                       indirectField);
3272 
3273   QualType type = VD->getType();
3274   if (type.isNull())
3275     return ExprError();
3276   ExprValueKind valueKind = VK_PRValue;
3277 
3278   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3279   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3280   // is expanded by some outer '...' in the context of the use.
3281   type = type.getNonPackExpansionType();
3282 
3283   switch (D->getKind()) {
3284     // Ignore all the non-ValueDecl kinds.
3285 #define ABSTRACT_DECL(kind)
3286 #define VALUE(type, base)
3287 #define DECL(type, base) case Decl::type:
3288 #include "clang/AST/DeclNodes.inc"
3289     llvm_unreachable("invalid value decl kind");
3290 
3291   // These shouldn't make it here.
3292   case Decl::ObjCAtDefsField:
3293     llvm_unreachable("forming non-member reference to ivar?");
3294 
3295   // Enum constants are always r-values and never references.
3296   // Unresolved using declarations are dependent.
3297   case Decl::EnumConstant:
3298   case Decl::UnresolvedUsingValue:
3299   case Decl::OMPDeclareReduction:
3300   case Decl::OMPDeclareMapper:
3301     valueKind = VK_PRValue;
3302     break;
3303 
3304   // Fields and indirect fields that got here must be for
3305   // pointer-to-member expressions; we just call them l-values for
3306   // internal consistency, because this subexpression doesn't really
3307   // exist in the high-level semantics.
3308   case Decl::Field:
3309   case Decl::IndirectField:
3310   case Decl::ObjCIvar:
3311     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3312 
3313     // These can't have reference type in well-formed programs, but
3314     // for internal consistency we do this anyway.
3315     type = type.getNonReferenceType();
3316     valueKind = VK_LValue;
3317     break;
3318 
3319   // Non-type template parameters are either l-values or r-values
3320   // depending on the type.
3321   case Decl::NonTypeTemplateParm: {
3322     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3323       type = reftype->getPointeeType();
3324       valueKind = VK_LValue; // even if the parameter is an r-value reference
3325       break;
3326     }
3327 
3328     // [expr.prim.id.unqual]p2:
3329     //   If the entity is a template parameter object for a template
3330     //   parameter of type T, the type of the expression is const T.
3331     //   [...] The expression is an lvalue if the entity is a [...] template
3332     //   parameter object.
3333     if (type->isRecordType()) {
3334       type = type.getUnqualifiedType().withConst();
3335       valueKind = VK_LValue;
3336       break;
3337     }
3338 
3339     // For non-references, we need to strip qualifiers just in case
3340     // the template parameter was declared as 'const int' or whatever.
3341     valueKind = VK_PRValue;
3342     type = type.getUnqualifiedType();
3343     break;
3344   }
3345 
3346   case Decl::Var:
3347   case Decl::VarTemplateSpecialization:
3348   case Decl::VarTemplatePartialSpecialization:
3349   case Decl::Decomposition:
3350   case Decl::OMPCapturedExpr:
3351     // In C, "extern void blah;" is valid and is an r-value.
3352     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3353         type->isVoidType()) {
3354       valueKind = VK_PRValue;
3355       break;
3356     }
3357     LLVM_FALLTHROUGH;
3358 
3359   case Decl::ImplicitParam:
3360   case Decl::ParmVar: {
3361     // These are always l-values.
3362     valueKind = VK_LValue;
3363     type = type.getNonReferenceType();
3364 
3365     // FIXME: Does the addition of const really only apply in
3366     // potentially-evaluated contexts? Since the variable isn't actually
3367     // captured in an unevaluated context, it seems that the answer is no.
3368     if (!isUnevaluatedContext()) {
3369       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3370       if (!CapturedType.isNull())
3371         type = CapturedType;
3372     }
3373 
3374     break;
3375   }
3376 
3377   case Decl::Binding: {
3378     // These are always lvalues.
3379     valueKind = VK_LValue;
3380     type = type.getNonReferenceType();
3381     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3382     // decides how that's supposed to work.
3383     auto *BD = cast<BindingDecl>(VD);
3384     if (BD->getDeclContext() != CurContext) {
3385       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3386       if (DD && DD->hasLocalStorage())
3387         diagnoseUncapturableValueReference(*this, Loc, BD);
3388     }
3389     break;
3390   }
3391 
3392   case Decl::Function: {
3393     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3394       if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3395         type = Context.BuiltinFnTy;
3396         valueKind = VK_PRValue;
3397         break;
3398       }
3399     }
3400 
3401     const FunctionType *fty = type->castAs<FunctionType>();
3402 
3403     // If we're referring to a function with an __unknown_anytype
3404     // result type, make the entire expression __unknown_anytype.
3405     if (fty->getReturnType() == Context.UnknownAnyTy) {
3406       type = Context.UnknownAnyTy;
3407       valueKind = VK_PRValue;
3408       break;
3409     }
3410 
3411     // Functions are l-values in C++.
3412     if (getLangOpts().CPlusPlus) {
3413       valueKind = VK_LValue;
3414       break;
3415     }
3416 
3417     // C99 DR 316 says that, if a function type comes from a
3418     // function definition (without a prototype), that type is only
3419     // used for checking compatibility. Therefore, when referencing
3420     // the function, we pretend that we don't have the full function
3421     // type.
3422     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3423       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3424                                             fty->getExtInfo());
3425 
3426     // Functions are r-values in C.
3427     valueKind = VK_PRValue;
3428     break;
3429   }
3430 
3431   case Decl::CXXDeductionGuide:
3432     llvm_unreachable("building reference to deduction guide");
3433 
3434   case Decl::MSProperty:
3435   case Decl::MSGuid:
3436   case Decl::TemplateParamObject:
3437     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3438     // capture in OpenMP, or duplicated between host and device?
3439     valueKind = VK_LValue;
3440     break;
3441 
3442   case Decl::CXXMethod:
3443     // If we're referring to a method with an __unknown_anytype
3444     // result type, make the entire expression __unknown_anytype.
3445     // This should only be possible with a type written directly.
3446     if (const FunctionProtoType *proto =
3447             dyn_cast<FunctionProtoType>(VD->getType()))
3448       if (proto->getReturnType() == Context.UnknownAnyTy) {
3449         type = Context.UnknownAnyTy;
3450         valueKind = VK_PRValue;
3451         break;
3452       }
3453 
3454     // C++ methods are l-values if static, r-values if non-static.
3455     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3456       valueKind = VK_LValue;
3457       break;
3458     }
3459     LLVM_FALLTHROUGH;
3460 
3461   case Decl::CXXConversion:
3462   case Decl::CXXDestructor:
3463   case Decl::CXXConstructor:
3464     valueKind = VK_PRValue;
3465     break;
3466   }
3467 
3468   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3469                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3470                           TemplateArgs);
3471 }
3472 
3473 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3474                                     SmallString<32> &Target) {
3475   Target.resize(CharByteWidth * (Source.size() + 1));
3476   char *ResultPtr = &Target[0];
3477   const llvm::UTF8 *ErrorPtr;
3478   bool success =
3479       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3480   (void)success;
3481   assert(success);
3482   Target.resize(ResultPtr - &Target[0]);
3483 }
3484 
3485 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3486                                      PredefinedExpr::IdentKind IK) {
3487   // Pick the current block, lambda, captured statement or function.
3488   Decl *currentDecl = nullptr;
3489   if (const BlockScopeInfo *BSI = getCurBlock())
3490     currentDecl = BSI->TheDecl;
3491   else if (const LambdaScopeInfo *LSI = getCurLambda())
3492     currentDecl = LSI->CallOperator;
3493   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3494     currentDecl = CSI->TheCapturedDecl;
3495   else
3496     currentDecl = getCurFunctionOrMethodDecl();
3497 
3498   if (!currentDecl) {
3499     Diag(Loc, diag::ext_predef_outside_function);
3500     currentDecl = Context.getTranslationUnitDecl();
3501   }
3502 
3503   QualType ResTy;
3504   StringLiteral *SL = nullptr;
3505   if (cast<DeclContext>(currentDecl)->isDependentContext())
3506     ResTy = Context.DependentTy;
3507   else {
3508     // Pre-defined identifiers are of type char[x], where x is the length of
3509     // the string.
3510     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3511     unsigned Length = Str.length();
3512 
3513     llvm::APInt LengthI(32, Length + 1);
3514     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3515       ResTy =
3516           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3517       SmallString<32> RawChars;
3518       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3519                               Str, RawChars);
3520       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3521                                            ArrayType::Normal,
3522                                            /*IndexTypeQuals*/ 0);
3523       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3524                                  /*Pascal*/ false, ResTy, Loc);
3525     } else {
3526       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3527       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3528                                            ArrayType::Normal,
3529                                            /*IndexTypeQuals*/ 0);
3530       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3531                                  /*Pascal*/ false, ResTy, Loc);
3532     }
3533   }
3534 
3535   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3536 }
3537 
3538 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3539                                                SourceLocation LParen,
3540                                                SourceLocation RParen,
3541                                                TypeSourceInfo *TSI) {
3542   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3543 }
3544 
3545 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3546                                                SourceLocation LParen,
3547                                                SourceLocation RParen,
3548                                                ParsedType ParsedTy) {
3549   TypeSourceInfo *TSI = nullptr;
3550   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3551 
3552   if (Ty.isNull())
3553     return ExprError();
3554   if (!TSI)
3555     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3556 
3557   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3558 }
3559 
3560 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3561   PredefinedExpr::IdentKind IK;
3562 
3563   switch (Kind) {
3564   default: llvm_unreachable("Unknown simple primary expr!");
3565   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3566   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3567   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3568   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3569   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3570   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3571   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3572   }
3573 
3574   return BuildPredefinedExpr(Loc, IK);
3575 }
3576 
3577 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3578   SmallString<16> CharBuffer;
3579   bool Invalid = false;
3580   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3581   if (Invalid)
3582     return ExprError();
3583 
3584   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3585                             PP, Tok.getKind());
3586   if (Literal.hadError())
3587     return ExprError();
3588 
3589   QualType Ty;
3590   if (Literal.isWide())
3591     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3592   else if (Literal.isUTF8() && getLangOpts().Char8)
3593     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3594   else if (Literal.isUTF16())
3595     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3596   else if (Literal.isUTF32())
3597     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3598   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3599     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3600   else
3601     Ty = Context.CharTy;  // 'x' -> char in C++
3602 
3603   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3604   if (Literal.isWide())
3605     Kind = CharacterLiteral::Wide;
3606   else if (Literal.isUTF16())
3607     Kind = CharacterLiteral::UTF16;
3608   else if (Literal.isUTF32())
3609     Kind = CharacterLiteral::UTF32;
3610   else if (Literal.isUTF8())
3611     Kind = CharacterLiteral::UTF8;
3612 
3613   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3614                                              Tok.getLocation());
3615 
3616   if (Literal.getUDSuffix().empty())
3617     return Lit;
3618 
3619   // We're building a user-defined literal.
3620   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3621   SourceLocation UDSuffixLoc =
3622     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3623 
3624   // Make sure we're allowed user-defined literals here.
3625   if (!UDLScope)
3626     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3627 
3628   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3629   //   operator "" X (ch)
3630   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3631                                         Lit, Tok.getLocation());
3632 }
3633 
3634 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3635   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3636   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3637                                 Context.IntTy, Loc);
3638 }
3639 
3640 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3641                                   QualType Ty, SourceLocation Loc) {
3642   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3643 
3644   using llvm::APFloat;
3645   APFloat Val(Format);
3646 
3647   APFloat::opStatus result = Literal.GetFloatValue(Val);
3648 
3649   // Overflow is always an error, but underflow is only an error if
3650   // we underflowed to zero (APFloat reports denormals as underflow).
3651   if ((result & APFloat::opOverflow) ||
3652       ((result & APFloat::opUnderflow) && Val.isZero())) {
3653     unsigned diagnostic;
3654     SmallString<20> buffer;
3655     if (result & APFloat::opOverflow) {
3656       diagnostic = diag::warn_float_overflow;
3657       APFloat::getLargest(Format).toString(buffer);
3658     } else {
3659       diagnostic = diag::warn_float_underflow;
3660       APFloat::getSmallest(Format).toString(buffer);
3661     }
3662 
3663     S.Diag(Loc, diagnostic)
3664       << Ty
3665       << StringRef(buffer.data(), buffer.size());
3666   }
3667 
3668   bool isExact = (result == APFloat::opOK);
3669   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3670 }
3671 
3672 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3673   assert(E && "Invalid expression");
3674 
3675   if (E->isValueDependent())
3676     return false;
3677 
3678   QualType QT = E->getType();
3679   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3680     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3681     return true;
3682   }
3683 
3684   llvm::APSInt ValueAPS;
3685   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3686 
3687   if (R.isInvalid())
3688     return true;
3689 
3690   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3691   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3692     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3693         << toString(ValueAPS, 10) << ValueIsPositive;
3694     return true;
3695   }
3696 
3697   return false;
3698 }
3699 
3700 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3701   // Fast path for a single digit (which is quite common).  A single digit
3702   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3703   if (Tok.getLength() == 1) {
3704     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3705     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3706   }
3707 
3708   SmallString<128> SpellingBuffer;
3709   // NumericLiteralParser wants to overread by one character.  Add padding to
3710   // the buffer in case the token is copied to the buffer.  If getSpelling()
3711   // returns a StringRef to the memory buffer, it should have a null char at
3712   // the EOF, so it is also safe.
3713   SpellingBuffer.resize(Tok.getLength() + 1);
3714 
3715   // Get the spelling of the token, which eliminates trigraphs, etc.
3716   bool Invalid = false;
3717   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3718   if (Invalid)
3719     return ExprError();
3720 
3721   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3722                                PP.getSourceManager(), PP.getLangOpts(),
3723                                PP.getTargetInfo(), PP.getDiagnostics());
3724   if (Literal.hadError)
3725     return ExprError();
3726 
3727   if (Literal.hasUDSuffix()) {
3728     // We're building a user-defined literal.
3729     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3730     SourceLocation UDSuffixLoc =
3731       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3732 
3733     // Make sure we're allowed user-defined literals here.
3734     if (!UDLScope)
3735       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3736 
3737     QualType CookedTy;
3738     if (Literal.isFloatingLiteral()) {
3739       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3740       // long double, the literal is treated as a call of the form
3741       //   operator "" X (f L)
3742       CookedTy = Context.LongDoubleTy;
3743     } else {
3744       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3745       // unsigned long long, the literal is treated as a call of the form
3746       //   operator "" X (n ULL)
3747       CookedTy = Context.UnsignedLongLongTy;
3748     }
3749 
3750     DeclarationName OpName =
3751       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3752     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3753     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3754 
3755     SourceLocation TokLoc = Tok.getLocation();
3756 
3757     // Perform literal operator lookup to determine if we're building a raw
3758     // literal or a cooked one.
3759     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3760     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3761                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3762                                   /*AllowStringTemplatePack*/ false,
3763                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3764     case LOLR_ErrorNoDiagnostic:
3765       // Lookup failure for imaginary constants isn't fatal, there's still the
3766       // GNU extension producing _Complex types.
3767       break;
3768     case LOLR_Error:
3769       return ExprError();
3770     case LOLR_Cooked: {
3771       Expr *Lit;
3772       if (Literal.isFloatingLiteral()) {
3773         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3774       } else {
3775         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3776         if (Literal.GetIntegerValue(ResultVal))
3777           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3778               << /* Unsigned */ 1;
3779         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3780                                      Tok.getLocation());
3781       }
3782       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3783     }
3784 
3785     case LOLR_Raw: {
3786       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3787       // literal is treated as a call of the form
3788       //   operator "" X ("n")
3789       unsigned Length = Literal.getUDSuffixOffset();
3790       QualType StrTy = Context.getConstantArrayType(
3791           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3792           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3793       Expr *Lit = StringLiteral::Create(
3794           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3795           /*Pascal*/false, StrTy, &TokLoc, 1);
3796       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3797     }
3798 
3799     case LOLR_Template: {
3800       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3801       // template), L is treated as a call fo the form
3802       //   operator "" X <'c1', 'c2', ... 'ck'>()
3803       // where n is the source character sequence c1 c2 ... ck.
3804       TemplateArgumentListInfo ExplicitArgs;
3805       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3806       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3807       llvm::APSInt Value(CharBits, CharIsUnsigned);
3808       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3809         Value = TokSpelling[I];
3810         TemplateArgument Arg(Context, Value, Context.CharTy);
3811         TemplateArgumentLocInfo ArgInfo;
3812         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3813       }
3814       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3815                                       &ExplicitArgs);
3816     }
3817     case LOLR_StringTemplatePack:
3818       llvm_unreachable("unexpected literal operator lookup result");
3819     }
3820   }
3821 
3822   Expr *Res;
3823 
3824   if (Literal.isFixedPointLiteral()) {
3825     QualType Ty;
3826 
3827     if (Literal.isAccum) {
3828       if (Literal.isHalf) {
3829         Ty = Context.ShortAccumTy;
3830       } else if (Literal.isLong) {
3831         Ty = Context.LongAccumTy;
3832       } else {
3833         Ty = Context.AccumTy;
3834       }
3835     } else if (Literal.isFract) {
3836       if (Literal.isHalf) {
3837         Ty = Context.ShortFractTy;
3838       } else if (Literal.isLong) {
3839         Ty = Context.LongFractTy;
3840       } else {
3841         Ty = Context.FractTy;
3842       }
3843     }
3844 
3845     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3846 
3847     bool isSigned = !Literal.isUnsigned;
3848     unsigned scale = Context.getFixedPointScale(Ty);
3849     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3850 
3851     llvm::APInt Val(bit_width, 0, isSigned);
3852     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3853     bool ValIsZero = Val.isZero() && !Overflowed;
3854 
3855     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3856     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3857       // Clause 6.4.4 - The value of a constant shall be in the range of
3858       // representable values for its type, with exception for constants of a
3859       // fract type with a value of exactly 1; such a constant shall denote
3860       // the maximal value for the type.
3861       --Val;
3862     else if (Val.ugt(MaxVal) || Overflowed)
3863       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3864 
3865     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3866                                               Tok.getLocation(), scale);
3867   } else if (Literal.isFloatingLiteral()) {
3868     QualType Ty;
3869     if (Literal.isHalf){
3870       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3871         Ty = Context.HalfTy;
3872       else {
3873         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3874         return ExprError();
3875       }
3876     } else if (Literal.isFloat)
3877       Ty = Context.FloatTy;
3878     else if (Literal.isLong)
3879       Ty = Context.LongDoubleTy;
3880     else if (Literal.isFloat16)
3881       Ty = Context.Float16Ty;
3882     else if (Literal.isFloat128)
3883       Ty = Context.Float128Ty;
3884     else
3885       Ty = Context.DoubleTy;
3886 
3887     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3888 
3889     if (Ty == Context.DoubleTy) {
3890       if (getLangOpts().SinglePrecisionConstants) {
3891         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3892           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3893         }
3894       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3895                                              "cl_khr_fp64", getLangOpts())) {
3896         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3897         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3898             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3899         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3900       }
3901     }
3902   } else if (!Literal.isIntegerLiteral()) {
3903     return ExprError();
3904   } else {
3905     QualType Ty;
3906 
3907     // 'long long' is a C99 or C++11 feature.
3908     if (!getLangOpts().C99 && Literal.isLongLong) {
3909       if (getLangOpts().CPlusPlus)
3910         Diag(Tok.getLocation(),
3911              getLangOpts().CPlusPlus11 ?
3912              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3913       else
3914         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3915     }
3916 
3917     // 'z/uz' literals are a C++2b feature.
3918     if (Literal.isSizeT)
3919       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3920                                   ? getLangOpts().CPlusPlus2b
3921                                         ? diag::warn_cxx20_compat_size_t_suffix
3922                                         : diag::ext_cxx2b_size_t_suffix
3923                                   : diag::err_cxx2b_size_t_suffix);
3924 
3925     // Get the value in the widest-possible width.
3926     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3927     llvm::APInt ResultVal(MaxWidth, 0);
3928 
3929     if (Literal.GetIntegerValue(ResultVal)) {
3930       // If this value didn't fit into uintmax_t, error and force to ull.
3931       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3932           << /* Unsigned */ 1;
3933       Ty = Context.UnsignedLongLongTy;
3934       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3935              "long long is not intmax_t?");
3936     } else {
3937       // If this value fits into a ULL, try to figure out what else it fits into
3938       // according to the rules of C99 6.4.4.1p5.
3939 
3940       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3941       // be an unsigned int.
3942       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3943 
3944       // Check from smallest to largest, picking the smallest type we can.
3945       unsigned Width = 0;
3946 
3947       // Microsoft specific integer suffixes are explicitly sized.
3948       if (Literal.MicrosoftInteger) {
3949         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3950           Width = 8;
3951           Ty = Context.CharTy;
3952         } else {
3953           Width = Literal.MicrosoftInteger;
3954           Ty = Context.getIntTypeForBitwidth(Width,
3955                                              /*Signed=*/!Literal.isUnsigned);
3956         }
3957       }
3958 
3959       // Check C++2b size_t literals.
3960       if (Literal.isSizeT) {
3961         assert(!Literal.MicrosoftInteger &&
3962                "size_t literals can't be Microsoft literals");
3963         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3964             Context.getTargetInfo().getSizeType());
3965 
3966         // Does it fit in size_t?
3967         if (ResultVal.isIntN(SizeTSize)) {
3968           // Does it fit in ssize_t?
3969           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3970             Ty = Context.getSignedSizeType();
3971           else if (AllowUnsigned)
3972             Ty = Context.getSizeType();
3973           Width = SizeTSize;
3974         }
3975       }
3976 
3977       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3978           !Literal.isSizeT) {
3979         // Are int/unsigned possibilities?
3980         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3981 
3982         // Does it fit in a unsigned int?
3983         if (ResultVal.isIntN(IntSize)) {
3984           // Does it fit in a signed int?
3985           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3986             Ty = Context.IntTy;
3987           else if (AllowUnsigned)
3988             Ty = Context.UnsignedIntTy;
3989           Width = IntSize;
3990         }
3991       }
3992 
3993       // Are long/unsigned long possibilities?
3994       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3995         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3996 
3997         // Does it fit in a unsigned long?
3998         if (ResultVal.isIntN(LongSize)) {
3999           // Does it fit in a signed long?
4000           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4001             Ty = Context.LongTy;
4002           else if (AllowUnsigned)
4003             Ty = Context.UnsignedLongTy;
4004           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4005           // is compatible.
4006           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4007             const unsigned LongLongSize =
4008                 Context.getTargetInfo().getLongLongWidth();
4009             Diag(Tok.getLocation(),
4010                  getLangOpts().CPlusPlus
4011                      ? Literal.isLong
4012                            ? diag::warn_old_implicitly_unsigned_long_cxx
4013                            : /*C++98 UB*/ diag::
4014                                  ext_old_implicitly_unsigned_long_cxx
4015                      : diag::warn_old_implicitly_unsigned_long)
4016                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4017                                             : /*will be ill-formed*/ 1);
4018             Ty = Context.UnsignedLongTy;
4019           }
4020           Width = LongSize;
4021         }
4022       }
4023 
4024       // Check long long if needed.
4025       if (Ty.isNull() && !Literal.isSizeT) {
4026         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4027 
4028         // Does it fit in a unsigned long long?
4029         if (ResultVal.isIntN(LongLongSize)) {
4030           // Does it fit in a signed long long?
4031           // To be compatible with MSVC, hex integer literals ending with the
4032           // LL or i64 suffix are always signed in Microsoft mode.
4033           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4034               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4035             Ty = Context.LongLongTy;
4036           else if (AllowUnsigned)
4037             Ty = Context.UnsignedLongLongTy;
4038           Width = LongLongSize;
4039         }
4040       }
4041 
4042       // If we still couldn't decide a type, we either have 'size_t' literal
4043       // that is out of range, or a decimal literal that does not fit in a
4044       // signed long long and has no U suffix.
4045       if (Ty.isNull()) {
4046         if (Literal.isSizeT)
4047           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4048               << Literal.isUnsigned;
4049         else
4050           Diag(Tok.getLocation(),
4051                diag::ext_integer_literal_too_large_for_signed);
4052         Ty = Context.UnsignedLongLongTy;
4053         Width = Context.getTargetInfo().getLongLongWidth();
4054       }
4055 
4056       if (ResultVal.getBitWidth() != Width)
4057         ResultVal = ResultVal.trunc(Width);
4058     }
4059     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4060   }
4061 
4062   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4063   if (Literal.isImaginary) {
4064     Res = new (Context) ImaginaryLiteral(Res,
4065                                         Context.getComplexType(Res->getType()));
4066 
4067     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4068   }
4069   return Res;
4070 }
4071 
4072 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4073   assert(E && "ActOnParenExpr() missing expr");
4074   QualType ExprTy = E->getType();
4075   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4076       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4077     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4078   return new (Context) ParenExpr(L, R, E);
4079 }
4080 
4081 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4082                                          SourceLocation Loc,
4083                                          SourceRange ArgRange) {
4084   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4085   // scalar or vector data type argument..."
4086   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4087   // type (C99 6.2.5p18) or void.
4088   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4089     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4090       << T << ArgRange;
4091     return true;
4092   }
4093 
4094   assert((T->isVoidType() || !T->isIncompleteType()) &&
4095          "Scalar types should always be complete");
4096   return false;
4097 }
4098 
4099 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4100                                            SourceLocation Loc,
4101                                            SourceRange ArgRange,
4102                                            UnaryExprOrTypeTrait TraitKind) {
4103   // Invalid types must be hard errors for SFINAE in C++.
4104   if (S.LangOpts.CPlusPlus)
4105     return true;
4106 
4107   // C99 6.5.3.4p1:
4108   if (T->isFunctionType() &&
4109       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4110        TraitKind == UETT_PreferredAlignOf)) {
4111     // sizeof(function)/alignof(function) is allowed as an extension.
4112     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4113         << getTraitSpelling(TraitKind) << ArgRange;
4114     return false;
4115   }
4116 
4117   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4118   // this is an error (OpenCL v1.1 s6.3.k)
4119   if (T->isVoidType()) {
4120     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4121                                         : diag::ext_sizeof_alignof_void_type;
4122     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4123     return false;
4124   }
4125 
4126   return true;
4127 }
4128 
4129 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4130                                              SourceLocation Loc,
4131                                              SourceRange ArgRange,
4132                                              UnaryExprOrTypeTrait TraitKind) {
4133   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4134   // runtime doesn't allow it.
4135   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4136     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4137       << T << (TraitKind == UETT_SizeOf)
4138       << ArgRange;
4139     return true;
4140   }
4141 
4142   return false;
4143 }
4144 
4145 /// Check whether E is a pointer from a decayed array type (the decayed
4146 /// pointer type is equal to T) and emit a warning if it is.
4147 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4148                                      Expr *E) {
4149   // Don't warn if the operation changed the type.
4150   if (T != E->getType())
4151     return;
4152 
4153   // Now look for array decays.
4154   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4155   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4156     return;
4157 
4158   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4159                                              << ICE->getType()
4160                                              << ICE->getSubExpr()->getType();
4161 }
4162 
4163 /// Check the constraints on expression operands to unary type expression
4164 /// and type traits.
4165 ///
4166 /// Completes any types necessary and validates the constraints on the operand
4167 /// expression. The logic mostly mirrors the type-based overload, but may modify
4168 /// the expression as it completes the type for that expression through template
4169 /// instantiation, etc.
4170 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4171                                             UnaryExprOrTypeTrait ExprKind) {
4172   QualType ExprTy = E->getType();
4173   assert(!ExprTy->isReferenceType());
4174 
4175   bool IsUnevaluatedOperand =
4176       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4177        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4178   if (IsUnevaluatedOperand) {
4179     ExprResult Result = CheckUnevaluatedOperand(E);
4180     if (Result.isInvalid())
4181       return true;
4182     E = Result.get();
4183   }
4184 
4185   // The operand for sizeof and alignof is in an unevaluated expression context,
4186   // so side effects could result in unintended consequences.
4187   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4188   // used to build SFINAE gadgets.
4189   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4190   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4191       !E->isInstantiationDependent() &&
4192       E->HasSideEffects(Context, false))
4193     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4194 
4195   if (ExprKind == UETT_VecStep)
4196     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4197                                         E->getSourceRange());
4198 
4199   // Explicitly list some types as extensions.
4200   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4201                                       E->getSourceRange(), ExprKind))
4202     return false;
4203 
4204   // 'alignof' applied to an expression only requires the base element type of
4205   // the expression to be complete. 'sizeof' requires the expression's type to
4206   // be complete (and will attempt to complete it if it's an array of unknown
4207   // bound).
4208   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4209     if (RequireCompleteSizedType(
4210             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4211             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4212             getTraitSpelling(ExprKind), E->getSourceRange()))
4213       return true;
4214   } else {
4215     if (RequireCompleteSizedExprType(
4216             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4217             getTraitSpelling(ExprKind), E->getSourceRange()))
4218       return true;
4219   }
4220 
4221   // Completing the expression's type may have changed it.
4222   ExprTy = E->getType();
4223   assert(!ExprTy->isReferenceType());
4224 
4225   if (ExprTy->isFunctionType()) {
4226     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4227         << getTraitSpelling(ExprKind) << E->getSourceRange();
4228     return true;
4229   }
4230 
4231   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4232                                        E->getSourceRange(), ExprKind))
4233     return true;
4234 
4235   if (ExprKind == UETT_SizeOf) {
4236     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4237       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4238         QualType OType = PVD->getOriginalType();
4239         QualType Type = PVD->getType();
4240         if (Type->isPointerType() && OType->isArrayType()) {
4241           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4242             << Type << OType;
4243           Diag(PVD->getLocation(), diag::note_declared_at);
4244         }
4245       }
4246     }
4247 
4248     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4249     // decays into a pointer and returns an unintended result. This is most
4250     // likely a typo for "sizeof(array) op x".
4251     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4252       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4253                                BO->getLHS());
4254       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4255                                BO->getRHS());
4256     }
4257   }
4258 
4259   return false;
4260 }
4261 
4262 /// Check the constraints on operands to unary expression and type
4263 /// traits.
4264 ///
4265 /// This will complete any types necessary, and validate the various constraints
4266 /// on those operands.
4267 ///
4268 /// The UsualUnaryConversions() function is *not* called by this routine.
4269 /// C99 6.3.2.1p[2-4] all state:
4270 ///   Except when it is the operand of the sizeof operator ...
4271 ///
4272 /// C++ [expr.sizeof]p4
4273 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4274 ///   standard conversions are not applied to the operand of sizeof.
4275 ///
4276 /// This policy is followed for all of the unary trait expressions.
4277 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4278                                             SourceLocation OpLoc,
4279                                             SourceRange ExprRange,
4280                                             UnaryExprOrTypeTrait ExprKind) {
4281   if (ExprType->isDependentType())
4282     return false;
4283 
4284   // C++ [expr.sizeof]p2:
4285   //     When applied to a reference or a reference type, the result
4286   //     is the size of the referenced type.
4287   // C++11 [expr.alignof]p3:
4288   //     When alignof is applied to a reference type, the result
4289   //     shall be the alignment of the referenced type.
4290   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4291     ExprType = Ref->getPointeeType();
4292 
4293   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4294   //   When alignof or _Alignof is applied to an array type, the result
4295   //   is the alignment of the element type.
4296   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4297       ExprKind == UETT_OpenMPRequiredSimdAlign)
4298     ExprType = Context.getBaseElementType(ExprType);
4299 
4300   if (ExprKind == UETT_VecStep)
4301     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4302 
4303   // Explicitly list some types as extensions.
4304   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4305                                       ExprKind))
4306     return false;
4307 
4308   if (RequireCompleteSizedType(
4309           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4310           getTraitSpelling(ExprKind), ExprRange))
4311     return true;
4312 
4313   if (ExprType->isFunctionType()) {
4314     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4315         << getTraitSpelling(ExprKind) << ExprRange;
4316     return true;
4317   }
4318 
4319   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4320                                        ExprKind))
4321     return true;
4322 
4323   return false;
4324 }
4325 
4326 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4327   // Cannot know anything else if the expression is dependent.
4328   if (E->isTypeDependent())
4329     return false;
4330 
4331   if (E->getObjectKind() == OK_BitField) {
4332     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4333        << 1 << E->getSourceRange();
4334     return true;
4335   }
4336 
4337   ValueDecl *D = nullptr;
4338   Expr *Inner = E->IgnoreParens();
4339   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4340     D = DRE->getDecl();
4341   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4342     D = ME->getMemberDecl();
4343   }
4344 
4345   // If it's a field, require the containing struct to have a
4346   // complete definition so that we can compute the layout.
4347   //
4348   // This can happen in C++11 onwards, either by naming the member
4349   // in a way that is not transformed into a member access expression
4350   // (in an unevaluated operand, for instance), or by naming the member
4351   // in a trailing-return-type.
4352   //
4353   // For the record, since __alignof__ on expressions is a GCC
4354   // extension, GCC seems to permit this but always gives the
4355   // nonsensical answer 0.
4356   //
4357   // We don't really need the layout here --- we could instead just
4358   // directly check for all the appropriate alignment-lowing
4359   // attributes --- but that would require duplicating a lot of
4360   // logic that just isn't worth duplicating for such a marginal
4361   // use-case.
4362   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4363     // Fast path this check, since we at least know the record has a
4364     // definition if we can find a member of it.
4365     if (!FD->getParent()->isCompleteDefinition()) {
4366       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4367         << E->getSourceRange();
4368       return true;
4369     }
4370 
4371     // Otherwise, if it's a field, and the field doesn't have
4372     // reference type, then it must have a complete type (or be a
4373     // flexible array member, which we explicitly want to
4374     // white-list anyway), which makes the following checks trivial.
4375     if (!FD->getType()->isReferenceType())
4376       return false;
4377   }
4378 
4379   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4380 }
4381 
4382 bool Sema::CheckVecStepExpr(Expr *E) {
4383   E = E->IgnoreParens();
4384 
4385   // Cannot know anything else if the expression is dependent.
4386   if (E->isTypeDependent())
4387     return false;
4388 
4389   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4390 }
4391 
4392 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4393                                         CapturingScopeInfo *CSI) {
4394   assert(T->isVariablyModifiedType());
4395   assert(CSI != nullptr);
4396 
4397   // We're going to walk down into the type and look for VLA expressions.
4398   do {
4399     const Type *Ty = T.getTypePtr();
4400     switch (Ty->getTypeClass()) {
4401 #define TYPE(Class, Base)
4402 #define ABSTRACT_TYPE(Class, Base)
4403 #define NON_CANONICAL_TYPE(Class, Base)
4404 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4405 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4406 #include "clang/AST/TypeNodes.inc"
4407       T = QualType();
4408       break;
4409     // These types are never variably-modified.
4410     case Type::Builtin:
4411     case Type::Complex:
4412     case Type::Vector:
4413     case Type::ExtVector:
4414     case Type::ConstantMatrix:
4415     case Type::Record:
4416     case Type::Enum:
4417     case Type::Elaborated:
4418     case Type::TemplateSpecialization:
4419     case Type::ObjCObject:
4420     case Type::ObjCInterface:
4421     case Type::ObjCObjectPointer:
4422     case Type::ObjCTypeParam:
4423     case Type::Pipe:
4424     case Type::BitInt:
4425       llvm_unreachable("type class is never variably-modified!");
4426     case Type::Adjusted:
4427       T = cast<AdjustedType>(Ty)->getOriginalType();
4428       break;
4429     case Type::Decayed:
4430       T = cast<DecayedType>(Ty)->getPointeeType();
4431       break;
4432     case Type::Pointer:
4433       T = cast<PointerType>(Ty)->getPointeeType();
4434       break;
4435     case Type::BlockPointer:
4436       T = cast<BlockPointerType>(Ty)->getPointeeType();
4437       break;
4438     case Type::LValueReference:
4439     case Type::RValueReference:
4440       T = cast<ReferenceType>(Ty)->getPointeeType();
4441       break;
4442     case Type::MemberPointer:
4443       T = cast<MemberPointerType>(Ty)->getPointeeType();
4444       break;
4445     case Type::ConstantArray:
4446     case Type::IncompleteArray:
4447       // Losing element qualification here is fine.
4448       T = cast<ArrayType>(Ty)->getElementType();
4449       break;
4450     case Type::VariableArray: {
4451       // Losing element qualification here is fine.
4452       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4453 
4454       // Unknown size indication requires no size computation.
4455       // Otherwise, evaluate and record it.
4456       auto Size = VAT->getSizeExpr();
4457       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4458           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4459         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4460 
4461       T = VAT->getElementType();
4462       break;
4463     }
4464     case Type::FunctionProto:
4465     case Type::FunctionNoProto:
4466       T = cast<FunctionType>(Ty)->getReturnType();
4467       break;
4468     case Type::Paren:
4469     case Type::TypeOf:
4470     case Type::UnaryTransform:
4471     case Type::Attributed:
4472     case Type::SubstTemplateTypeParm:
4473     case Type::MacroQualified:
4474       // Keep walking after single level desugaring.
4475       T = T.getSingleStepDesugaredType(Context);
4476       break;
4477     case Type::Typedef:
4478       T = cast<TypedefType>(Ty)->desugar();
4479       break;
4480     case Type::Decltype:
4481       T = cast<DecltypeType>(Ty)->desugar();
4482       break;
4483     case Type::Using:
4484       T = cast<UsingType>(Ty)->desugar();
4485       break;
4486     case Type::Auto:
4487     case Type::DeducedTemplateSpecialization:
4488       T = cast<DeducedType>(Ty)->getDeducedType();
4489       break;
4490     case Type::TypeOfExpr:
4491       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4492       break;
4493     case Type::Atomic:
4494       T = cast<AtomicType>(Ty)->getValueType();
4495       break;
4496     }
4497   } while (!T.isNull() && T->isVariablyModifiedType());
4498 }
4499 
4500 /// Build a sizeof or alignof expression given a type operand.
4501 ExprResult
4502 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4503                                      SourceLocation OpLoc,
4504                                      UnaryExprOrTypeTrait ExprKind,
4505                                      SourceRange R) {
4506   if (!TInfo)
4507     return ExprError();
4508 
4509   QualType T = TInfo->getType();
4510 
4511   if (!T->isDependentType() &&
4512       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4513     return ExprError();
4514 
4515   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4516     if (auto *TT = T->getAs<TypedefType>()) {
4517       for (auto I = FunctionScopes.rbegin(),
4518                 E = std::prev(FunctionScopes.rend());
4519            I != E; ++I) {
4520         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4521         if (CSI == nullptr)
4522           break;
4523         DeclContext *DC = nullptr;
4524         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4525           DC = LSI->CallOperator;
4526         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4527           DC = CRSI->TheCapturedDecl;
4528         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4529           DC = BSI->TheDecl;
4530         if (DC) {
4531           if (DC->containsDecl(TT->getDecl()))
4532             break;
4533           captureVariablyModifiedType(Context, T, CSI);
4534         }
4535       }
4536     }
4537   }
4538 
4539   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4540   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4541       TInfo->getType()->isVariablyModifiedType())
4542     TInfo = TransformToPotentiallyEvaluated(TInfo);
4543 
4544   return new (Context) UnaryExprOrTypeTraitExpr(
4545       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4546 }
4547 
4548 /// Build a sizeof or alignof expression given an expression
4549 /// operand.
4550 ExprResult
4551 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4552                                      UnaryExprOrTypeTrait ExprKind) {
4553   ExprResult PE = CheckPlaceholderExpr(E);
4554   if (PE.isInvalid())
4555     return ExprError();
4556 
4557   E = PE.get();
4558 
4559   // Verify that the operand is valid.
4560   bool isInvalid = false;
4561   if (E->isTypeDependent()) {
4562     // Delay type-checking for type-dependent expressions.
4563   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4564     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4565   } else if (ExprKind == UETT_VecStep) {
4566     isInvalid = CheckVecStepExpr(E);
4567   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4568       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4569       isInvalid = true;
4570   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4571     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4572     isInvalid = true;
4573   } else {
4574     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4575   }
4576 
4577   if (isInvalid)
4578     return ExprError();
4579 
4580   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4581     PE = TransformToPotentiallyEvaluated(E);
4582     if (PE.isInvalid()) return ExprError();
4583     E = PE.get();
4584   }
4585 
4586   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4587   return new (Context) UnaryExprOrTypeTraitExpr(
4588       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4589 }
4590 
4591 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4592 /// expr and the same for @c alignof and @c __alignof
4593 /// Note that the ArgRange is invalid if isType is false.
4594 ExprResult
4595 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4596                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4597                                     void *TyOrEx, SourceRange ArgRange) {
4598   // If error parsing type, ignore.
4599   if (!TyOrEx) return ExprError();
4600 
4601   if (IsType) {
4602     TypeSourceInfo *TInfo;
4603     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4604     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4605   }
4606 
4607   Expr *ArgEx = (Expr *)TyOrEx;
4608   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4609   return Result;
4610 }
4611 
4612 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4613                                      bool IsReal) {
4614   if (V.get()->isTypeDependent())
4615     return S.Context.DependentTy;
4616 
4617   // _Real and _Imag are only l-values for normal l-values.
4618   if (V.get()->getObjectKind() != OK_Ordinary) {
4619     V = S.DefaultLvalueConversion(V.get());
4620     if (V.isInvalid())
4621       return QualType();
4622   }
4623 
4624   // These operators return the element type of a complex type.
4625   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4626     return CT->getElementType();
4627 
4628   // Otherwise they pass through real integer and floating point types here.
4629   if (V.get()->getType()->isArithmeticType())
4630     return V.get()->getType();
4631 
4632   // Test for placeholders.
4633   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4634   if (PR.isInvalid()) return QualType();
4635   if (PR.get() != V.get()) {
4636     V = PR;
4637     return CheckRealImagOperand(S, V, Loc, IsReal);
4638   }
4639 
4640   // Reject anything else.
4641   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4642     << (IsReal ? "__real" : "__imag");
4643   return QualType();
4644 }
4645 
4646 
4647 
4648 ExprResult
4649 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4650                           tok::TokenKind Kind, Expr *Input) {
4651   UnaryOperatorKind Opc;
4652   switch (Kind) {
4653   default: llvm_unreachable("Unknown unary op!");
4654   case tok::plusplus:   Opc = UO_PostInc; break;
4655   case tok::minusminus: Opc = UO_PostDec; break;
4656   }
4657 
4658   // Since this might is a postfix expression, get rid of ParenListExprs.
4659   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4660   if (Result.isInvalid()) return ExprError();
4661   Input = Result.get();
4662 
4663   return BuildUnaryOp(S, OpLoc, Opc, Input);
4664 }
4665 
4666 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4667 ///
4668 /// \return true on error
4669 static bool checkArithmeticOnObjCPointer(Sema &S,
4670                                          SourceLocation opLoc,
4671                                          Expr *op) {
4672   assert(op->getType()->isObjCObjectPointerType());
4673   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4674       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4675     return false;
4676 
4677   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4678     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4679     << op->getSourceRange();
4680   return true;
4681 }
4682 
4683 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4684   auto *BaseNoParens = Base->IgnoreParens();
4685   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4686     return MSProp->getPropertyDecl()->getType()->isArrayType();
4687   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4688 }
4689 
4690 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4691 // Typically this is DependentTy, but can sometimes be more precise.
4692 //
4693 // There are cases when we could determine a non-dependent type:
4694 //  - LHS and RHS may have non-dependent types despite being type-dependent
4695 //    (e.g. unbounded array static members of the current instantiation)
4696 //  - one may be a dependent-sized array with known element type
4697 //  - one may be a dependent-typed valid index (enum in current instantiation)
4698 //
4699 // We *always* return a dependent type, in such cases it is DependentTy.
4700 // This avoids creating type-dependent expressions with non-dependent types.
4701 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4702 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4703                                                const ASTContext &Ctx) {
4704   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4705   QualType LTy = LHS->getType(), RTy = RHS->getType();
4706   QualType Result = Ctx.DependentTy;
4707   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4708     if (const PointerType *PT = LTy->getAs<PointerType>())
4709       Result = PT->getPointeeType();
4710     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4711       Result = AT->getElementType();
4712   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4713     if (const PointerType *PT = RTy->getAs<PointerType>())
4714       Result = PT->getPointeeType();
4715     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4716       Result = AT->getElementType();
4717   }
4718   // Ensure we return a dependent type.
4719   return Result->isDependentType() ? Result : Ctx.DependentTy;
4720 }
4721 
4722 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4723 
4724 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4725                                          SourceLocation lbLoc,
4726                                          MultiExprArg ArgExprs,
4727                                          SourceLocation rbLoc) {
4728 
4729   if (base && !base->getType().isNull() &&
4730       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4731     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4732                                     SourceLocation(), /*Length*/ nullptr,
4733                                     /*Stride=*/nullptr, rbLoc);
4734 
4735   // Since this might be a postfix expression, get rid of ParenListExprs.
4736   if (isa<ParenListExpr>(base)) {
4737     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4738     if (result.isInvalid())
4739       return ExprError();
4740     base = result.get();
4741   }
4742 
4743   // Check if base and idx form a MatrixSubscriptExpr.
4744   //
4745   // Helper to check for comma expressions, which are not allowed as indices for
4746   // matrix subscript expressions.
4747   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4748     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4749       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4750           << SourceRange(base->getBeginLoc(), rbLoc);
4751       return true;
4752     }
4753     return false;
4754   };
4755   // The matrix subscript operator ([][])is considered a single operator.
4756   // Separating the index expressions by parenthesis is not allowed.
4757   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4758       !isa<MatrixSubscriptExpr>(base)) {
4759     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4760         << SourceRange(base->getBeginLoc(), rbLoc);
4761     return ExprError();
4762   }
4763   // If the base is a MatrixSubscriptExpr, try to create a new
4764   // MatrixSubscriptExpr.
4765   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4766   if (matSubscriptE) {
4767     assert(ArgExprs.size() == 1);
4768     if (CheckAndReportCommaError(ArgExprs.front()))
4769       return ExprError();
4770 
4771     assert(matSubscriptE->isIncomplete() &&
4772            "base has to be an incomplete matrix subscript");
4773     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4774                                             matSubscriptE->getRowIdx(),
4775                                             ArgExprs.front(), rbLoc);
4776   }
4777 
4778   // Handle any non-overload placeholder types in the base and index
4779   // expressions.  We can't handle overloads here because the other
4780   // operand might be an overloadable type, in which case the overload
4781   // resolution for the operator overload should get the first crack
4782   // at the overload.
4783   bool IsMSPropertySubscript = false;
4784   if (base->getType()->isNonOverloadPlaceholderType()) {
4785     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4786     if (!IsMSPropertySubscript) {
4787       ExprResult result = CheckPlaceholderExpr(base);
4788       if (result.isInvalid())
4789         return ExprError();
4790       base = result.get();
4791     }
4792   }
4793 
4794   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4795   if (base->getType()->isMatrixType()) {
4796     assert(ArgExprs.size() == 1);
4797     if (CheckAndReportCommaError(ArgExprs.front()))
4798       return ExprError();
4799 
4800     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4801                                             rbLoc);
4802   }
4803 
4804   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4805     Expr *idx = ArgExprs[0];
4806     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4807         (isa<CXXOperatorCallExpr>(idx) &&
4808          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4809       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4810           << SourceRange(base->getBeginLoc(), rbLoc);
4811     }
4812   }
4813 
4814   if (ArgExprs.size() == 1 &&
4815       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4816     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4817     if (result.isInvalid())
4818       return ExprError();
4819     ArgExprs[0] = result.get();
4820   } else {
4821     if (checkArgsForPlaceholders(*this, ArgExprs))
4822       return ExprError();
4823   }
4824 
4825   // Build an unanalyzed expression if either operand is type-dependent.
4826   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4827       (base->isTypeDependent() ||
4828        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4829     return new (Context) ArraySubscriptExpr(
4830         base, ArgExprs.front(),
4831         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4832         VK_LValue, OK_Ordinary, rbLoc);
4833   }
4834 
4835   // MSDN, property (C++)
4836   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4837   // This attribute can also be used in the declaration of an empty array in a
4838   // class or structure definition. For example:
4839   // __declspec(property(get=GetX, put=PutX)) int x[];
4840   // The above statement indicates that x[] can be used with one or more array
4841   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4842   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4843   if (IsMSPropertySubscript) {
4844     assert(ArgExprs.size() == 1);
4845     // Build MS property subscript expression if base is MS property reference
4846     // or MS property subscript.
4847     return new (Context)
4848         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4849                                 VK_LValue, OK_Ordinary, rbLoc);
4850   }
4851 
4852   // Use C++ overloaded-operator rules if either operand has record
4853   // type.  The spec says to do this if either type is *overloadable*,
4854   // but enum types can't declare subscript operators or conversion
4855   // operators, so there's nothing interesting for overload resolution
4856   // to do if there aren't any record types involved.
4857   //
4858   // ObjC pointers have their own subscripting logic that is not tied
4859   // to overload resolution and so should not take this path.
4860   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4861       ((base->getType()->isRecordType() ||
4862         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4863     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4864   }
4865 
4866   ExprResult Res =
4867       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4868 
4869   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4870     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4871 
4872   return Res;
4873 }
4874 
4875 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4876   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4877   InitializationKind Kind =
4878       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4879   InitializationSequence InitSeq(*this, Entity, Kind, E);
4880   return InitSeq.Perform(*this, Entity, Kind, E);
4881 }
4882 
4883 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4884                                                   Expr *ColumnIdx,
4885                                                   SourceLocation RBLoc) {
4886   ExprResult BaseR = CheckPlaceholderExpr(Base);
4887   if (BaseR.isInvalid())
4888     return BaseR;
4889   Base = BaseR.get();
4890 
4891   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4892   if (RowR.isInvalid())
4893     return RowR;
4894   RowIdx = RowR.get();
4895 
4896   if (!ColumnIdx)
4897     return new (Context) MatrixSubscriptExpr(
4898         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4899 
4900   // Build an unanalyzed expression if any of the operands is type-dependent.
4901   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4902       ColumnIdx->isTypeDependent())
4903     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4904                                              Context.DependentTy, RBLoc);
4905 
4906   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4907   if (ColumnR.isInvalid())
4908     return ColumnR;
4909   ColumnIdx = ColumnR.get();
4910 
4911   // Check that IndexExpr is an integer expression. If it is a constant
4912   // expression, check that it is less than Dim (= the number of elements in the
4913   // corresponding dimension).
4914   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4915                           bool IsColumnIdx) -> Expr * {
4916     if (!IndexExpr->getType()->isIntegerType() &&
4917         !IndexExpr->isTypeDependent()) {
4918       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4919           << IsColumnIdx;
4920       return nullptr;
4921     }
4922 
4923     if (Optional<llvm::APSInt> Idx =
4924             IndexExpr->getIntegerConstantExpr(Context)) {
4925       if ((*Idx < 0 || *Idx >= Dim)) {
4926         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4927             << IsColumnIdx << Dim;
4928         return nullptr;
4929       }
4930     }
4931 
4932     ExprResult ConvExpr =
4933         tryConvertExprToType(IndexExpr, Context.getSizeType());
4934     assert(!ConvExpr.isInvalid() &&
4935            "should be able to convert any integer type to size type");
4936     return ConvExpr.get();
4937   };
4938 
4939   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4940   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4941   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4942   if (!RowIdx || !ColumnIdx)
4943     return ExprError();
4944 
4945   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4946                                            MTy->getElementType(), RBLoc);
4947 }
4948 
4949 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4950   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4951   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4952 
4953   // For expressions like `&(*s).b`, the base is recorded and what should be
4954   // checked.
4955   const MemberExpr *Member = nullptr;
4956   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4957     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4958 
4959   LastRecord.PossibleDerefs.erase(StrippedExpr);
4960 }
4961 
4962 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4963   if (isUnevaluatedContext())
4964     return;
4965 
4966   QualType ResultTy = E->getType();
4967   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4968 
4969   // Bail if the element is an array since it is not memory access.
4970   if (isa<ArrayType>(ResultTy))
4971     return;
4972 
4973   if (ResultTy->hasAttr(attr::NoDeref)) {
4974     LastRecord.PossibleDerefs.insert(E);
4975     return;
4976   }
4977 
4978   // Check if the base type is a pointer to a member access of a struct
4979   // marked with noderef.
4980   const Expr *Base = E->getBase();
4981   QualType BaseTy = Base->getType();
4982   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4983     // Not a pointer access
4984     return;
4985 
4986   const MemberExpr *Member = nullptr;
4987   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4988          Member->isArrow())
4989     Base = Member->getBase();
4990 
4991   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4992     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4993       LastRecord.PossibleDerefs.insert(E);
4994   }
4995 }
4996 
4997 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4998                                           Expr *LowerBound,
4999                                           SourceLocation ColonLocFirst,
5000                                           SourceLocation ColonLocSecond,
5001                                           Expr *Length, Expr *Stride,
5002                                           SourceLocation RBLoc) {
5003   if (Base->hasPlaceholderType() &&
5004       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5005     ExprResult Result = CheckPlaceholderExpr(Base);
5006     if (Result.isInvalid())
5007       return ExprError();
5008     Base = Result.get();
5009   }
5010   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5011     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5012     if (Result.isInvalid())
5013       return ExprError();
5014     Result = DefaultLvalueConversion(Result.get());
5015     if (Result.isInvalid())
5016       return ExprError();
5017     LowerBound = Result.get();
5018   }
5019   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5020     ExprResult Result = CheckPlaceholderExpr(Length);
5021     if (Result.isInvalid())
5022       return ExprError();
5023     Result = DefaultLvalueConversion(Result.get());
5024     if (Result.isInvalid())
5025       return ExprError();
5026     Length = Result.get();
5027   }
5028   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5029     ExprResult Result = CheckPlaceholderExpr(Stride);
5030     if (Result.isInvalid())
5031       return ExprError();
5032     Result = DefaultLvalueConversion(Result.get());
5033     if (Result.isInvalid())
5034       return ExprError();
5035     Stride = Result.get();
5036   }
5037 
5038   // Build an unanalyzed expression if either operand is type-dependent.
5039   if (Base->isTypeDependent() ||
5040       (LowerBound &&
5041        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5042       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5043       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5044     return new (Context) OMPArraySectionExpr(
5045         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5046         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5047   }
5048 
5049   // Perform default conversions.
5050   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5051   QualType ResultTy;
5052   if (OriginalTy->isAnyPointerType()) {
5053     ResultTy = OriginalTy->getPointeeType();
5054   } else if (OriginalTy->isArrayType()) {
5055     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5056   } else {
5057     return ExprError(
5058         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5059         << Base->getSourceRange());
5060   }
5061   // C99 6.5.2.1p1
5062   if (LowerBound) {
5063     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5064                                                       LowerBound);
5065     if (Res.isInvalid())
5066       return ExprError(Diag(LowerBound->getExprLoc(),
5067                             diag::err_omp_typecheck_section_not_integer)
5068                        << 0 << LowerBound->getSourceRange());
5069     LowerBound = Res.get();
5070 
5071     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5072         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5073       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5074           << 0 << LowerBound->getSourceRange();
5075   }
5076   if (Length) {
5077     auto Res =
5078         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5079     if (Res.isInvalid())
5080       return ExprError(Diag(Length->getExprLoc(),
5081                             diag::err_omp_typecheck_section_not_integer)
5082                        << 1 << Length->getSourceRange());
5083     Length = Res.get();
5084 
5085     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5086         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5087       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5088           << 1 << Length->getSourceRange();
5089   }
5090   if (Stride) {
5091     ExprResult Res =
5092         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5093     if (Res.isInvalid())
5094       return ExprError(Diag(Stride->getExprLoc(),
5095                             diag::err_omp_typecheck_section_not_integer)
5096                        << 1 << Stride->getSourceRange());
5097     Stride = Res.get();
5098 
5099     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5100         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5101       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5102           << 1 << Stride->getSourceRange();
5103   }
5104 
5105   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5106   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5107   // type. Note that functions are not objects, and that (in C99 parlance)
5108   // incomplete types are not object types.
5109   if (ResultTy->isFunctionType()) {
5110     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5111         << ResultTy << Base->getSourceRange();
5112     return ExprError();
5113   }
5114 
5115   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5116                           diag::err_omp_section_incomplete_type, Base))
5117     return ExprError();
5118 
5119   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5120     Expr::EvalResult Result;
5121     if (LowerBound->EvaluateAsInt(Result, Context)) {
5122       // OpenMP 5.0, [2.1.5 Array Sections]
5123       // The array section must be a subset of the original array.
5124       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5125       if (LowerBoundValue.isNegative()) {
5126         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5127             << LowerBound->getSourceRange();
5128         return ExprError();
5129       }
5130     }
5131   }
5132 
5133   if (Length) {
5134     Expr::EvalResult Result;
5135     if (Length->EvaluateAsInt(Result, Context)) {
5136       // OpenMP 5.0, [2.1.5 Array Sections]
5137       // The length must evaluate to non-negative integers.
5138       llvm::APSInt LengthValue = Result.Val.getInt();
5139       if (LengthValue.isNegative()) {
5140         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5141             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5142             << Length->getSourceRange();
5143         return ExprError();
5144       }
5145     }
5146   } else if (ColonLocFirst.isValid() &&
5147              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5148                                       !OriginalTy->isVariableArrayType()))) {
5149     // OpenMP 5.0, [2.1.5 Array Sections]
5150     // When the size of the array dimension is not known, the length must be
5151     // specified explicitly.
5152     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5153         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5154     return ExprError();
5155   }
5156 
5157   if (Stride) {
5158     Expr::EvalResult Result;
5159     if (Stride->EvaluateAsInt(Result, Context)) {
5160       // OpenMP 5.0, [2.1.5 Array Sections]
5161       // The stride must evaluate to a positive integer.
5162       llvm::APSInt StrideValue = Result.Val.getInt();
5163       if (!StrideValue.isStrictlyPositive()) {
5164         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5165             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5166             << Stride->getSourceRange();
5167         return ExprError();
5168       }
5169     }
5170   }
5171 
5172   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5173     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5174     if (Result.isInvalid())
5175       return ExprError();
5176     Base = Result.get();
5177   }
5178   return new (Context) OMPArraySectionExpr(
5179       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5180       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5181 }
5182 
5183 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5184                                           SourceLocation RParenLoc,
5185                                           ArrayRef<Expr *> Dims,
5186                                           ArrayRef<SourceRange> Brackets) {
5187   if (Base->hasPlaceholderType()) {
5188     ExprResult Result = CheckPlaceholderExpr(Base);
5189     if (Result.isInvalid())
5190       return ExprError();
5191     Result = DefaultLvalueConversion(Result.get());
5192     if (Result.isInvalid())
5193       return ExprError();
5194     Base = Result.get();
5195   }
5196   QualType BaseTy = Base->getType();
5197   // Delay analysis of the types/expressions if instantiation/specialization is
5198   // required.
5199   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5200     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5201                                        LParenLoc, RParenLoc, Dims, Brackets);
5202   if (!BaseTy->isPointerType() ||
5203       (!Base->isTypeDependent() &&
5204        BaseTy->getPointeeType()->isIncompleteType()))
5205     return ExprError(Diag(Base->getExprLoc(),
5206                           diag::err_omp_non_pointer_type_array_shaping_base)
5207                      << Base->getSourceRange());
5208 
5209   SmallVector<Expr *, 4> NewDims;
5210   bool ErrorFound = false;
5211   for (Expr *Dim : Dims) {
5212     if (Dim->hasPlaceholderType()) {
5213       ExprResult Result = CheckPlaceholderExpr(Dim);
5214       if (Result.isInvalid()) {
5215         ErrorFound = true;
5216         continue;
5217       }
5218       Result = DefaultLvalueConversion(Result.get());
5219       if (Result.isInvalid()) {
5220         ErrorFound = true;
5221         continue;
5222       }
5223       Dim = Result.get();
5224     }
5225     if (!Dim->isTypeDependent()) {
5226       ExprResult Result =
5227           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5228       if (Result.isInvalid()) {
5229         ErrorFound = true;
5230         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5231             << Dim->getSourceRange();
5232         continue;
5233       }
5234       Dim = Result.get();
5235       Expr::EvalResult EvResult;
5236       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5237         // OpenMP 5.0, [2.1.4 Array Shaping]
5238         // Each si is an integral type expression that must evaluate to a
5239         // positive integer.
5240         llvm::APSInt Value = EvResult.Val.getInt();
5241         if (!Value.isStrictlyPositive()) {
5242           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5243               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5244               << Dim->getSourceRange();
5245           ErrorFound = true;
5246           continue;
5247         }
5248       }
5249     }
5250     NewDims.push_back(Dim);
5251   }
5252   if (ErrorFound)
5253     return ExprError();
5254   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5255                                      LParenLoc, RParenLoc, NewDims, Brackets);
5256 }
5257 
5258 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5259                                       SourceLocation LLoc, SourceLocation RLoc,
5260                                       ArrayRef<OMPIteratorData> Data) {
5261   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5262   bool IsCorrect = true;
5263   for (const OMPIteratorData &D : Data) {
5264     TypeSourceInfo *TInfo = nullptr;
5265     SourceLocation StartLoc;
5266     QualType DeclTy;
5267     if (!D.Type.getAsOpaquePtr()) {
5268       // OpenMP 5.0, 2.1.6 Iterators
5269       // In an iterator-specifier, if the iterator-type is not specified then
5270       // the type of that iterator is of int type.
5271       DeclTy = Context.IntTy;
5272       StartLoc = D.DeclIdentLoc;
5273     } else {
5274       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5275       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5276     }
5277 
5278     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5279                              DeclTy->containsUnexpandedParameterPack() ||
5280                              DeclTy->isInstantiationDependentType();
5281     if (!IsDeclTyDependent) {
5282       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5283         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5284         // The iterator-type must be an integral or pointer type.
5285         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5286             << DeclTy;
5287         IsCorrect = false;
5288         continue;
5289       }
5290       if (DeclTy.isConstant(Context)) {
5291         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5292         // The iterator-type must not be const qualified.
5293         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5294             << DeclTy;
5295         IsCorrect = false;
5296         continue;
5297       }
5298     }
5299 
5300     // Iterator declaration.
5301     assert(D.DeclIdent && "Identifier expected.");
5302     // Always try to create iterator declarator to avoid extra error messages
5303     // about unknown declarations use.
5304     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5305                                D.DeclIdent, DeclTy, TInfo, SC_None);
5306     VD->setImplicit();
5307     if (S) {
5308       // Check for conflicting previous declaration.
5309       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5310       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5311                             ForVisibleRedeclaration);
5312       Previous.suppressDiagnostics();
5313       LookupName(Previous, S);
5314 
5315       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5316                            /*AllowInlineNamespace=*/false);
5317       if (!Previous.empty()) {
5318         NamedDecl *Old = Previous.getRepresentativeDecl();
5319         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5320         Diag(Old->getLocation(), diag::note_previous_definition);
5321       } else {
5322         PushOnScopeChains(VD, S);
5323       }
5324     } else {
5325       CurContext->addDecl(VD);
5326     }
5327     Expr *Begin = D.Range.Begin;
5328     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5329       ExprResult BeginRes =
5330           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5331       Begin = BeginRes.get();
5332     }
5333     Expr *End = D.Range.End;
5334     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5335       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5336       End = EndRes.get();
5337     }
5338     Expr *Step = D.Range.Step;
5339     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5340       if (!Step->getType()->isIntegralType(Context)) {
5341         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5342             << Step << Step->getSourceRange();
5343         IsCorrect = false;
5344         continue;
5345       }
5346       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5347       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5348       // If the step expression of a range-specification equals zero, the
5349       // behavior is unspecified.
5350       if (Result && Result->isZero()) {
5351         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5352             << Step << Step->getSourceRange();
5353         IsCorrect = false;
5354         continue;
5355       }
5356     }
5357     if (!Begin || !End || !IsCorrect) {
5358       IsCorrect = false;
5359       continue;
5360     }
5361     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5362     IDElem.IteratorDecl = VD;
5363     IDElem.AssignmentLoc = D.AssignLoc;
5364     IDElem.Range.Begin = Begin;
5365     IDElem.Range.End = End;
5366     IDElem.Range.Step = Step;
5367     IDElem.ColonLoc = D.ColonLoc;
5368     IDElem.SecondColonLoc = D.SecColonLoc;
5369   }
5370   if (!IsCorrect) {
5371     // Invalidate all created iterator declarations if error is found.
5372     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5373       if (Decl *ID = D.IteratorDecl)
5374         ID->setInvalidDecl();
5375     }
5376     return ExprError();
5377   }
5378   SmallVector<OMPIteratorHelperData, 4> Helpers;
5379   if (!CurContext->isDependentContext()) {
5380     // Build number of ityeration for each iteration range.
5381     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5382     // ((Begini-Stepi-1-Endi) / -Stepi);
5383     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5384       // (Endi - Begini)
5385       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5386                                           D.Range.Begin);
5387       if(!Res.isUsable()) {
5388         IsCorrect = false;
5389         continue;
5390       }
5391       ExprResult St, St1;
5392       if (D.Range.Step) {
5393         St = D.Range.Step;
5394         // (Endi - Begini) + Stepi
5395         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5396         if (!Res.isUsable()) {
5397           IsCorrect = false;
5398           continue;
5399         }
5400         // (Endi - Begini) + Stepi - 1
5401         Res =
5402             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5403                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5404         if (!Res.isUsable()) {
5405           IsCorrect = false;
5406           continue;
5407         }
5408         // ((Endi - Begini) + Stepi - 1) / Stepi
5409         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5410         if (!Res.isUsable()) {
5411           IsCorrect = false;
5412           continue;
5413         }
5414         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5415         // (Begini - Endi)
5416         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5417                                              D.Range.Begin, D.Range.End);
5418         if (!Res1.isUsable()) {
5419           IsCorrect = false;
5420           continue;
5421         }
5422         // (Begini - Endi) - Stepi
5423         Res1 =
5424             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5425         if (!Res1.isUsable()) {
5426           IsCorrect = false;
5427           continue;
5428         }
5429         // (Begini - Endi) - Stepi - 1
5430         Res1 =
5431             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5432                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5433         if (!Res1.isUsable()) {
5434           IsCorrect = false;
5435           continue;
5436         }
5437         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5438         Res1 =
5439             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5440         if (!Res1.isUsable()) {
5441           IsCorrect = false;
5442           continue;
5443         }
5444         // Stepi > 0.
5445         ExprResult CmpRes =
5446             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5447                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5448         if (!CmpRes.isUsable()) {
5449           IsCorrect = false;
5450           continue;
5451         }
5452         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5453                                  Res.get(), Res1.get());
5454         if (!Res.isUsable()) {
5455           IsCorrect = false;
5456           continue;
5457         }
5458       }
5459       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5460       if (!Res.isUsable()) {
5461         IsCorrect = false;
5462         continue;
5463       }
5464 
5465       // Build counter update.
5466       // Build counter.
5467       auto *CounterVD =
5468           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5469                           D.IteratorDecl->getBeginLoc(), nullptr,
5470                           Res.get()->getType(), nullptr, SC_None);
5471       CounterVD->setImplicit();
5472       ExprResult RefRes =
5473           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5474                            D.IteratorDecl->getBeginLoc());
5475       // Build counter update.
5476       // I = Begini + counter * Stepi;
5477       ExprResult UpdateRes;
5478       if (D.Range.Step) {
5479         UpdateRes = CreateBuiltinBinOp(
5480             D.AssignmentLoc, BO_Mul,
5481             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5482       } else {
5483         UpdateRes = DefaultLvalueConversion(RefRes.get());
5484       }
5485       if (!UpdateRes.isUsable()) {
5486         IsCorrect = false;
5487         continue;
5488       }
5489       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5490                                      UpdateRes.get());
5491       if (!UpdateRes.isUsable()) {
5492         IsCorrect = false;
5493         continue;
5494       }
5495       ExprResult VDRes =
5496           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5497                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5498                            D.IteratorDecl->getBeginLoc());
5499       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5500                                      UpdateRes.get());
5501       if (!UpdateRes.isUsable()) {
5502         IsCorrect = false;
5503         continue;
5504       }
5505       UpdateRes =
5506           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5507       if (!UpdateRes.isUsable()) {
5508         IsCorrect = false;
5509         continue;
5510       }
5511       ExprResult CounterUpdateRes =
5512           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5513       if (!CounterUpdateRes.isUsable()) {
5514         IsCorrect = false;
5515         continue;
5516       }
5517       CounterUpdateRes =
5518           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5519       if (!CounterUpdateRes.isUsable()) {
5520         IsCorrect = false;
5521         continue;
5522       }
5523       OMPIteratorHelperData &HD = Helpers.emplace_back();
5524       HD.CounterVD = CounterVD;
5525       HD.Upper = Res.get();
5526       HD.Update = UpdateRes.get();
5527       HD.CounterUpdate = CounterUpdateRes.get();
5528     }
5529   } else {
5530     Helpers.assign(ID.size(), {});
5531   }
5532   if (!IsCorrect) {
5533     // Invalidate all created iterator declarations if error is found.
5534     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5535       if (Decl *ID = D.IteratorDecl)
5536         ID->setInvalidDecl();
5537     }
5538     return ExprError();
5539   }
5540   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5541                                  LLoc, RLoc, ID, Helpers);
5542 }
5543 
5544 ExprResult
5545 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5546                                       Expr *Idx, SourceLocation RLoc) {
5547   Expr *LHSExp = Base;
5548   Expr *RHSExp = Idx;
5549 
5550   ExprValueKind VK = VK_LValue;
5551   ExprObjectKind OK = OK_Ordinary;
5552 
5553   // Per C++ core issue 1213, the result is an xvalue if either operand is
5554   // a non-lvalue array, and an lvalue otherwise.
5555   if (getLangOpts().CPlusPlus11) {
5556     for (auto *Op : {LHSExp, RHSExp}) {
5557       Op = Op->IgnoreImplicit();
5558       if (Op->getType()->isArrayType() && !Op->isLValue())
5559         VK = VK_XValue;
5560     }
5561   }
5562 
5563   // Perform default conversions.
5564   if (!LHSExp->getType()->getAs<VectorType>()) {
5565     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5566     if (Result.isInvalid())
5567       return ExprError();
5568     LHSExp = Result.get();
5569   }
5570   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5571   if (Result.isInvalid())
5572     return ExprError();
5573   RHSExp = Result.get();
5574 
5575   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5576 
5577   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5578   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5579   // in the subscript position. As a result, we need to derive the array base
5580   // and index from the expression types.
5581   Expr *BaseExpr, *IndexExpr;
5582   QualType ResultType;
5583   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5584     BaseExpr = LHSExp;
5585     IndexExpr = RHSExp;
5586     ResultType =
5587         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5588   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5589     BaseExpr = LHSExp;
5590     IndexExpr = RHSExp;
5591     ResultType = PTy->getPointeeType();
5592   } else if (const ObjCObjectPointerType *PTy =
5593                LHSTy->getAs<ObjCObjectPointerType>()) {
5594     BaseExpr = LHSExp;
5595     IndexExpr = RHSExp;
5596 
5597     // Use custom logic if this should be the pseudo-object subscript
5598     // expression.
5599     if (!LangOpts.isSubscriptPointerArithmetic())
5600       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5601                                           nullptr);
5602 
5603     ResultType = PTy->getPointeeType();
5604   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5605      // Handle the uncommon case of "123[Ptr]".
5606     BaseExpr = RHSExp;
5607     IndexExpr = LHSExp;
5608     ResultType = PTy->getPointeeType();
5609   } else if (const ObjCObjectPointerType *PTy =
5610                RHSTy->getAs<ObjCObjectPointerType>()) {
5611      // Handle the uncommon case of "123[Ptr]".
5612     BaseExpr = RHSExp;
5613     IndexExpr = LHSExp;
5614     ResultType = PTy->getPointeeType();
5615     if (!LangOpts.isSubscriptPointerArithmetic()) {
5616       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5617         << ResultType << BaseExpr->getSourceRange();
5618       return ExprError();
5619     }
5620   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5621     BaseExpr = LHSExp;    // vectors: V[123]
5622     IndexExpr = RHSExp;
5623     // We apply C++ DR1213 to vector subscripting too.
5624     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5625       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5626       if (Materialized.isInvalid())
5627         return ExprError();
5628       LHSExp = Materialized.get();
5629     }
5630     VK = LHSExp->getValueKind();
5631     if (VK != VK_PRValue)
5632       OK = OK_VectorComponent;
5633 
5634     ResultType = VTy->getElementType();
5635     QualType BaseType = BaseExpr->getType();
5636     Qualifiers BaseQuals = BaseType.getQualifiers();
5637     Qualifiers MemberQuals = ResultType.getQualifiers();
5638     Qualifiers Combined = BaseQuals + MemberQuals;
5639     if (Combined != MemberQuals)
5640       ResultType = Context.getQualifiedType(ResultType, Combined);
5641   } else if (LHSTy->isArrayType()) {
5642     // If we see an array that wasn't promoted by
5643     // DefaultFunctionArrayLvalueConversion, it must be an array that
5644     // wasn't promoted because of the C90 rule that doesn't
5645     // allow promoting non-lvalue arrays.  Warn, then
5646     // force the promotion here.
5647     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5648         << LHSExp->getSourceRange();
5649     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5650                                CK_ArrayToPointerDecay).get();
5651     LHSTy = LHSExp->getType();
5652 
5653     BaseExpr = LHSExp;
5654     IndexExpr = RHSExp;
5655     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5656   } else if (RHSTy->isArrayType()) {
5657     // Same as previous, except for 123[f().a] case
5658     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5659         << RHSExp->getSourceRange();
5660     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5661                                CK_ArrayToPointerDecay).get();
5662     RHSTy = RHSExp->getType();
5663 
5664     BaseExpr = RHSExp;
5665     IndexExpr = LHSExp;
5666     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5667   } else {
5668     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5669        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5670   }
5671   // C99 6.5.2.1p1
5672   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5673     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5674                      << IndexExpr->getSourceRange());
5675 
5676   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5677        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5678          && !IndexExpr->isTypeDependent())
5679     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5680 
5681   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5682   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5683   // type. Note that Functions are not objects, and that (in C99 parlance)
5684   // incomplete types are not object types.
5685   if (ResultType->isFunctionType()) {
5686     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5687         << ResultType << BaseExpr->getSourceRange();
5688     return ExprError();
5689   }
5690 
5691   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5692     // GNU extension: subscripting on pointer to void
5693     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5694       << BaseExpr->getSourceRange();
5695 
5696     // C forbids expressions of unqualified void type from being l-values.
5697     // See IsCForbiddenLValueType.
5698     if (!ResultType.hasQualifiers())
5699       VK = VK_PRValue;
5700   } else if (!ResultType->isDependentType() &&
5701              RequireCompleteSizedType(
5702                  LLoc, ResultType,
5703                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5704     return ExprError();
5705 
5706   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5707          !ResultType.isCForbiddenLValueType());
5708 
5709   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5710       FunctionScopes.size() > 1) {
5711     if (auto *TT =
5712             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5713       for (auto I = FunctionScopes.rbegin(),
5714                 E = std::prev(FunctionScopes.rend());
5715            I != E; ++I) {
5716         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5717         if (CSI == nullptr)
5718           break;
5719         DeclContext *DC = nullptr;
5720         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5721           DC = LSI->CallOperator;
5722         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5723           DC = CRSI->TheCapturedDecl;
5724         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5725           DC = BSI->TheDecl;
5726         if (DC) {
5727           if (DC->containsDecl(TT->getDecl()))
5728             break;
5729           captureVariablyModifiedType(
5730               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5731         }
5732       }
5733     }
5734   }
5735 
5736   return new (Context)
5737       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5738 }
5739 
5740 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5741                                   ParmVarDecl *Param) {
5742   if (Param->hasUnparsedDefaultArg()) {
5743     // If we've already cleared out the location for the default argument,
5744     // that means we're parsing it right now.
5745     if (!UnparsedDefaultArgLocs.count(Param)) {
5746       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5747       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5748       Param->setInvalidDecl();
5749       return true;
5750     }
5751 
5752     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5753         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5754     Diag(UnparsedDefaultArgLocs[Param],
5755          diag::note_default_argument_declared_here);
5756     return true;
5757   }
5758 
5759   if (Param->hasUninstantiatedDefaultArg() &&
5760       InstantiateDefaultArgument(CallLoc, FD, Param))
5761     return true;
5762 
5763   assert(Param->hasInit() && "default argument but no initializer?");
5764 
5765   // If the default expression creates temporaries, we need to
5766   // push them to the current stack of expression temporaries so they'll
5767   // be properly destroyed.
5768   // FIXME: We should really be rebuilding the default argument with new
5769   // bound temporaries; see the comment in PR5810.
5770   // We don't need to do that with block decls, though, because
5771   // blocks in default argument expression can never capture anything.
5772   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5773     // Set the "needs cleanups" bit regardless of whether there are
5774     // any explicit objects.
5775     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5776 
5777     // Append all the objects to the cleanup list.  Right now, this
5778     // should always be a no-op, because blocks in default argument
5779     // expressions should never be able to capture anything.
5780     assert(!Init->getNumObjects() &&
5781            "default argument expression has capturing blocks?");
5782   }
5783 
5784   // We already type-checked the argument, so we know it works.
5785   // Just mark all of the declarations in this potentially-evaluated expression
5786   // as being "referenced".
5787   EnterExpressionEvaluationContext EvalContext(
5788       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5789   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5790                                    /*SkipLocalVariables=*/true);
5791   return false;
5792 }
5793 
5794 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5795                                         FunctionDecl *FD, ParmVarDecl *Param) {
5796   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5797   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5798     return ExprError();
5799   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5800 }
5801 
5802 Sema::VariadicCallType
5803 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5804                           Expr *Fn) {
5805   if (Proto && Proto->isVariadic()) {
5806     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5807       return VariadicConstructor;
5808     else if (Fn && Fn->getType()->isBlockPointerType())
5809       return VariadicBlock;
5810     else if (FDecl) {
5811       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5812         if (Method->isInstance())
5813           return VariadicMethod;
5814     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5815       return VariadicMethod;
5816     return VariadicFunction;
5817   }
5818   return VariadicDoesNotApply;
5819 }
5820 
5821 namespace {
5822 class FunctionCallCCC final : public FunctionCallFilterCCC {
5823 public:
5824   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5825                   unsigned NumArgs, MemberExpr *ME)
5826       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5827         FunctionName(FuncName) {}
5828 
5829   bool ValidateCandidate(const TypoCorrection &candidate) override {
5830     if (!candidate.getCorrectionSpecifier() ||
5831         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5832       return false;
5833     }
5834 
5835     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5836   }
5837 
5838   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5839     return std::make_unique<FunctionCallCCC>(*this);
5840   }
5841 
5842 private:
5843   const IdentifierInfo *const FunctionName;
5844 };
5845 }
5846 
5847 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5848                                                FunctionDecl *FDecl,
5849                                                ArrayRef<Expr *> Args) {
5850   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5851   DeclarationName FuncName = FDecl->getDeclName();
5852   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5853 
5854   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5855   if (TypoCorrection Corrected = S.CorrectTypo(
5856           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5857           S.getScopeForContext(S.CurContext), nullptr, CCC,
5858           Sema::CTK_ErrorRecovery)) {
5859     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5860       if (Corrected.isOverloaded()) {
5861         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5862         OverloadCandidateSet::iterator Best;
5863         for (NamedDecl *CD : Corrected) {
5864           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5865             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5866                                    OCS);
5867         }
5868         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5869         case OR_Success:
5870           ND = Best->FoundDecl;
5871           Corrected.setCorrectionDecl(ND);
5872           break;
5873         default:
5874           break;
5875         }
5876       }
5877       ND = ND->getUnderlyingDecl();
5878       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5879         return Corrected;
5880     }
5881   }
5882   return TypoCorrection();
5883 }
5884 
5885 /// ConvertArgumentsForCall - Converts the arguments specified in
5886 /// Args/NumArgs to the parameter types of the function FDecl with
5887 /// function prototype Proto. Call is the call expression itself, and
5888 /// Fn is the function expression. For a C++ member function, this
5889 /// routine does not attempt to convert the object argument. Returns
5890 /// true if the call is ill-formed.
5891 bool
5892 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5893                               FunctionDecl *FDecl,
5894                               const FunctionProtoType *Proto,
5895                               ArrayRef<Expr *> Args,
5896                               SourceLocation RParenLoc,
5897                               bool IsExecConfig) {
5898   // Bail out early if calling a builtin with custom typechecking.
5899   if (FDecl)
5900     if (unsigned ID = FDecl->getBuiltinID())
5901       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5902         return false;
5903 
5904   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5905   // assignment, to the types of the corresponding parameter, ...
5906   unsigned NumParams = Proto->getNumParams();
5907   bool Invalid = false;
5908   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5909   unsigned FnKind = Fn->getType()->isBlockPointerType()
5910                        ? 1 /* block */
5911                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5912                                        : 0 /* function */);
5913 
5914   // If too few arguments are available (and we don't have default
5915   // arguments for the remaining parameters), don't make the call.
5916   if (Args.size() < NumParams) {
5917     if (Args.size() < MinArgs) {
5918       TypoCorrection TC;
5919       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5920         unsigned diag_id =
5921             MinArgs == NumParams && !Proto->isVariadic()
5922                 ? diag::err_typecheck_call_too_few_args_suggest
5923                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5924         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5925                                         << static_cast<unsigned>(Args.size())
5926                                         << TC.getCorrectionRange());
5927       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5928         Diag(RParenLoc,
5929              MinArgs == NumParams && !Proto->isVariadic()
5930                  ? diag::err_typecheck_call_too_few_args_one
5931                  : diag::err_typecheck_call_too_few_args_at_least_one)
5932             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5933       else
5934         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5935                             ? diag::err_typecheck_call_too_few_args
5936                             : diag::err_typecheck_call_too_few_args_at_least)
5937             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5938             << Fn->getSourceRange();
5939 
5940       // Emit the location of the prototype.
5941       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5942         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5943 
5944       return true;
5945     }
5946     // We reserve space for the default arguments when we create
5947     // the call expression, before calling ConvertArgumentsForCall.
5948     assert((Call->getNumArgs() == NumParams) &&
5949            "We should have reserved space for the default arguments before!");
5950   }
5951 
5952   // If too many are passed and not variadic, error on the extras and drop
5953   // them.
5954   if (Args.size() > NumParams) {
5955     if (!Proto->isVariadic()) {
5956       TypoCorrection TC;
5957       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5958         unsigned diag_id =
5959             MinArgs == NumParams && !Proto->isVariadic()
5960                 ? diag::err_typecheck_call_too_many_args_suggest
5961                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5962         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5963                                         << static_cast<unsigned>(Args.size())
5964                                         << TC.getCorrectionRange());
5965       } else if (NumParams == 1 && FDecl &&
5966                  FDecl->getParamDecl(0)->getDeclName())
5967         Diag(Args[NumParams]->getBeginLoc(),
5968              MinArgs == NumParams
5969                  ? diag::err_typecheck_call_too_many_args_one
5970                  : diag::err_typecheck_call_too_many_args_at_most_one)
5971             << FnKind << FDecl->getParamDecl(0)
5972             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5973             << SourceRange(Args[NumParams]->getBeginLoc(),
5974                            Args.back()->getEndLoc());
5975       else
5976         Diag(Args[NumParams]->getBeginLoc(),
5977              MinArgs == NumParams
5978                  ? diag::err_typecheck_call_too_many_args
5979                  : diag::err_typecheck_call_too_many_args_at_most)
5980             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5981             << Fn->getSourceRange()
5982             << SourceRange(Args[NumParams]->getBeginLoc(),
5983                            Args.back()->getEndLoc());
5984 
5985       // Emit the location of the prototype.
5986       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5987         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5988 
5989       // This deletes the extra arguments.
5990       Call->shrinkNumArgs(NumParams);
5991       return true;
5992     }
5993   }
5994   SmallVector<Expr *, 8> AllArgs;
5995   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5996 
5997   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5998                                    AllArgs, CallType);
5999   if (Invalid)
6000     return true;
6001   unsigned TotalNumArgs = AllArgs.size();
6002   for (unsigned i = 0; i < TotalNumArgs; ++i)
6003     Call->setArg(i, AllArgs[i]);
6004 
6005   Call->computeDependence();
6006   return false;
6007 }
6008 
6009 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6010                                   const FunctionProtoType *Proto,
6011                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6012                                   SmallVectorImpl<Expr *> &AllArgs,
6013                                   VariadicCallType CallType, bool AllowExplicit,
6014                                   bool IsListInitialization) {
6015   unsigned NumParams = Proto->getNumParams();
6016   bool Invalid = false;
6017   size_t ArgIx = 0;
6018   // Continue to check argument types (even if we have too few/many args).
6019   for (unsigned i = FirstParam; i < NumParams; i++) {
6020     QualType ProtoArgType = Proto->getParamType(i);
6021 
6022     Expr *Arg;
6023     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6024     if (ArgIx < Args.size()) {
6025       Arg = Args[ArgIx++];
6026 
6027       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6028                               diag::err_call_incomplete_argument, Arg))
6029         return true;
6030 
6031       // Strip the unbridged-cast placeholder expression off, if applicable.
6032       bool CFAudited = false;
6033       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6034           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6035           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6036         Arg = stripARCUnbridgedCast(Arg);
6037       else if (getLangOpts().ObjCAutoRefCount &&
6038                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6039                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6040         CFAudited = true;
6041 
6042       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6043           ProtoArgType->isBlockPointerType())
6044         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6045           BE->getBlockDecl()->setDoesNotEscape();
6046 
6047       InitializedEntity Entity =
6048           Param ? InitializedEntity::InitializeParameter(Context, Param,
6049                                                          ProtoArgType)
6050                 : InitializedEntity::InitializeParameter(
6051                       Context, ProtoArgType, Proto->isParamConsumed(i));
6052 
6053       // Remember that parameter belongs to a CF audited API.
6054       if (CFAudited)
6055         Entity.setParameterCFAudited();
6056 
6057       ExprResult ArgE = PerformCopyInitialization(
6058           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6059       if (ArgE.isInvalid())
6060         return true;
6061 
6062       Arg = ArgE.getAs<Expr>();
6063     } else {
6064       assert(Param && "can't use default arguments without a known callee");
6065 
6066       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6067       if (ArgExpr.isInvalid())
6068         return true;
6069 
6070       Arg = ArgExpr.getAs<Expr>();
6071     }
6072 
6073     // Check for array bounds violations for each argument to the call. This
6074     // check only triggers warnings when the argument isn't a more complex Expr
6075     // with its own checking, such as a BinaryOperator.
6076     CheckArrayAccess(Arg);
6077 
6078     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6079     CheckStaticArrayArgument(CallLoc, Param, Arg);
6080 
6081     AllArgs.push_back(Arg);
6082   }
6083 
6084   // If this is a variadic call, handle args passed through "...".
6085   if (CallType != VariadicDoesNotApply) {
6086     // Assume that extern "C" functions with variadic arguments that
6087     // return __unknown_anytype aren't *really* variadic.
6088     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6089         FDecl->isExternC()) {
6090       for (Expr *A : Args.slice(ArgIx)) {
6091         QualType paramType; // ignored
6092         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6093         Invalid |= arg.isInvalid();
6094         AllArgs.push_back(arg.get());
6095       }
6096 
6097     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6098     } else {
6099       for (Expr *A : Args.slice(ArgIx)) {
6100         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6101         Invalid |= Arg.isInvalid();
6102         AllArgs.push_back(Arg.get());
6103       }
6104     }
6105 
6106     // Check for array bounds violations.
6107     for (Expr *A : Args.slice(ArgIx))
6108       CheckArrayAccess(A);
6109   }
6110   return Invalid;
6111 }
6112 
6113 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6114   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6115   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6116     TL = DTL.getOriginalLoc();
6117   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6118     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6119       << ATL.getLocalSourceRange();
6120 }
6121 
6122 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6123 /// array parameter, check that it is non-null, and that if it is formed by
6124 /// array-to-pointer decay, the underlying array is sufficiently large.
6125 ///
6126 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6127 /// array type derivation, then for each call to the function, the value of the
6128 /// corresponding actual argument shall provide access to the first element of
6129 /// an array with at least as many elements as specified by the size expression.
6130 void
6131 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6132                                ParmVarDecl *Param,
6133                                const Expr *ArgExpr) {
6134   // Static array parameters are not supported in C++.
6135   if (!Param || getLangOpts().CPlusPlus)
6136     return;
6137 
6138   QualType OrigTy = Param->getOriginalType();
6139 
6140   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6141   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6142     return;
6143 
6144   if (ArgExpr->isNullPointerConstant(Context,
6145                                      Expr::NPC_NeverValueDependent)) {
6146     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6147     DiagnoseCalleeStaticArrayParam(*this, Param);
6148     return;
6149   }
6150 
6151   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6152   if (!CAT)
6153     return;
6154 
6155   const ConstantArrayType *ArgCAT =
6156     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6157   if (!ArgCAT)
6158     return;
6159 
6160   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6161                                              ArgCAT->getElementType())) {
6162     if (ArgCAT->getSize().ult(CAT->getSize())) {
6163       Diag(CallLoc, diag::warn_static_array_too_small)
6164           << ArgExpr->getSourceRange()
6165           << (unsigned)ArgCAT->getSize().getZExtValue()
6166           << (unsigned)CAT->getSize().getZExtValue() << 0;
6167       DiagnoseCalleeStaticArrayParam(*this, Param);
6168     }
6169     return;
6170   }
6171 
6172   Optional<CharUnits> ArgSize =
6173       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6174   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6175   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6176     Diag(CallLoc, diag::warn_static_array_too_small)
6177         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6178         << (unsigned)ParmSize->getQuantity() << 1;
6179     DiagnoseCalleeStaticArrayParam(*this, Param);
6180   }
6181 }
6182 
6183 /// Given a function expression of unknown-any type, try to rebuild it
6184 /// to have a function type.
6185 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6186 
6187 /// Is the given type a placeholder that we need to lower out
6188 /// immediately during argument processing?
6189 static bool isPlaceholderToRemoveAsArg(QualType type) {
6190   // Placeholders are never sugared.
6191   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6192   if (!placeholder) return false;
6193 
6194   switch (placeholder->getKind()) {
6195   // Ignore all the non-placeholder types.
6196 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6197   case BuiltinType::Id:
6198 #include "clang/Basic/OpenCLImageTypes.def"
6199 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6200   case BuiltinType::Id:
6201 #include "clang/Basic/OpenCLExtensionTypes.def"
6202   // In practice we'll never use this, since all SVE types are sugared
6203   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6204 #define SVE_TYPE(Name, Id, SingletonId) \
6205   case BuiltinType::Id:
6206 #include "clang/Basic/AArch64SVEACLETypes.def"
6207 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6208   case BuiltinType::Id:
6209 #include "clang/Basic/PPCTypes.def"
6210 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6211 #include "clang/Basic/RISCVVTypes.def"
6212 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6213 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6214 #include "clang/AST/BuiltinTypes.def"
6215     return false;
6216 
6217   // We cannot lower out overload sets; they might validly be resolved
6218   // by the call machinery.
6219   case BuiltinType::Overload:
6220     return false;
6221 
6222   // Unbridged casts in ARC can be handled in some call positions and
6223   // should be left in place.
6224   case BuiltinType::ARCUnbridgedCast:
6225     return false;
6226 
6227   // Pseudo-objects should be converted as soon as possible.
6228   case BuiltinType::PseudoObject:
6229     return true;
6230 
6231   // The debugger mode could theoretically but currently does not try
6232   // to resolve unknown-typed arguments based on known parameter types.
6233   case BuiltinType::UnknownAny:
6234     return true;
6235 
6236   // These are always invalid as call arguments and should be reported.
6237   case BuiltinType::BoundMember:
6238   case BuiltinType::BuiltinFn:
6239   case BuiltinType::IncompleteMatrixIdx:
6240   case BuiltinType::OMPArraySection:
6241   case BuiltinType::OMPArrayShaping:
6242   case BuiltinType::OMPIterator:
6243     return true;
6244 
6245   }
6246   llvm_unreachable("bad builtin type kind");
6247 }
6248 
6249 /// Check an argument list for placeholders that we won't try to
6250 /// handle later.
6251 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6252   // Apply this processing to all the arguments at once instead of
6253   // dying at the first failure.
6254   bool hasInvalid = false;
6255   for (size_t i = 0, e = args.size(); i != e; i++) {
6256     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6257       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6258       if (result.isInvalid()) hasInvalid = true;
6259       else args[i] = result.get();
6260     }
6261   }
6262   return hasInvalid;
6263 }
6264 
6265 /// If a builtin function has a pointer argument with no explicit address
6266 /// space, then it should be able to accept a pointer to any address
6267 /// space as input.  In order to do this, we need to replace the
6268 /// standard builtin declaration with one that uses the same address space
6269 /// as the call.
6270 ///
6271 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6272 ///                  it does not contain any pointer arguments without
6273 ///                  an address space qualifer.  Otherwise the rewritten
6274 ///                  FunctionDecl is returned.
6275 /// TODO: Handle pointer return types.
6276 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6277                                                 FunctionDecl *FDecl,
6278                                                 MultiExprArg ArgExprs) {
6279 
6280   QualType DeclType = FDecl->getType();
6281   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6282 
6283   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6284       ArgExprs.size() < FT->getNumParams())
6285     return nullptr;
6286 
6287   bool NeedsNewDecl = false;
6288   unsigned i = 0;
6289   SmallVector<QualType, 8> OverloadParams;
6290 
6291   for (QualType ParamType : FT->param_types()) {
6292 
6293     // Convert array arguments to pointer to simplify type lookup.
6294     ExprResult ArgRes =
6295         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6296     if (ArgRes.isInvalid())
6297       return nullptr;
6298     Expr *Arg = ArgRes.get();
6299     QualType ArgType = Arg->getType();
6300     if (!ParamType->isPointerType() ||
6301         ParamType.hasAddressSpace() ||
6302         !ArgType->isPointerType() ||
6303         !ArgType->getPointeeType().hasAddressSpace()) {
6304       OverloadParams.push_back(ParamType);
6305       continue;
6306     }
6307 
6308     QualType PointeeType = ParamType->getPointeeType();
6309     if (PointeeType.hasAddressSpace())
6310       continue;
6311 
6312     NeedsNewDecl = true;
6313     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6314 
6315     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6316     OverloadParams.push_back(Context.getPointerType(PointeeType));
6317   }
6318 
6319   if (!NeedsNewDecl)
6320     return nullptr;
6321 
6322   FunctionProtoType::ExtProtoInfo EPI;
6323   EPI.Variadic = FT->isVariadic();
6324   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6325                                                 OverloadParams, EPI);
6326   DeclContext *Parent = FDecl->getParent();
6327   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6328       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6329       FDecl->getIdentifier(), OverloadTy,
6330       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6331       false,
6332       /*hasPrototype=*/true);
6333   SmallVector<ParmVarDecl*, 16> Params;
6334   FT = cast<FunctionProtoType>(OverloadTy);
6335   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6336     QualType ParamType = FT->getParamType(i);
6337     ParmVarDecl *Parm =
6338         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6339                                 SourceLocation(), nullptr, ParamType,
6340                                 /*TInfo=*/nullptr, SC_None, nullptr);
6341     Parm->setScopeInfo(0, i);
6342     Params.push_back(Parm);
6343   }
6344   OverloadDecl->setParams(Params);
6345   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6346   return OverloadDecl;
6347 }
6348 
6349 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6350                                     FunctionDecl *Callee,
6351                                     MultiExprArg ArgExprs) {
6352   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6353   // similar attributes) really don't like it when functions are called with an
6354   // invalid number of args.
6355   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6356                          /*PartialOverloading=*/false) &&
6357       !Callee->isVariadic())
6358     return;
6359   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6360     return;
6361 
6362   if (const EnableIfAttr *Attr =
6363           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6364     S.Diag(Fn->getBeginLoc(),
6365            isa<CXXMethodDecl>(Callee)
6366                ? diag::err_ovl_no_viable_member_function_in_call
6367                : diag::err_ovl_no_viable_function_in_call)
6368         << Callee << Callee->getSourceRange();
6369     S.Diag(Callee->getLocation(),
6370            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6371         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6372     return;
6373   }
6374 }
6375 
6376 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6377     const UnresolvedMemberExpr *const UME, Sema &S) {
6378 
6379   const auto GetFunctionLevelDCIfCXXClass =
6380       [](Sema &S) -> const CXXRecordDecl * {
6381     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6382     if (!DC || !DC->getParent())
6383       return nullptr;
6384 
6385     // If the call to some member function was made from within a member
6386     // function body 'M' return return 'M's parent.
6387     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6388       return MD->getParent()->getCanonicalDecl();
6389     // else the call was made from within a default member initializer of a
6390     // class, so return the class.
6391     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6392       return RD->getCanonicalDecl();
6393     return nullptr;
6394   };
6395   // If our DeclContext is neither a member function nor a class (in the
6396   // case of a lambda in a default member initializer), we can't have an
6397   // enclosing 'this'.
6398 
6399   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6400   if (!CurParentClass)
6401     return false;
6402 
6403   // The naming class for implicit member functions call is the class in which
6404   // name lookup starts.
6405   const CXXRecordDecl *const NamingClass =
6406       UME->getNamingClass()->getCanonicalDecl();
6407   assert(NamingClass && "Must have naming class even for implicit access");
6408 
6409   // If the unresolved member functions were found in a 'naming class' that is
6410   // related (either the same or derived from) to the class that contains the
6411   // member function that itself contained the implicit member access.
6412 
6413   return CurParentClass == NamingClass ||
6414          CurParentClass->isDerivedFrom(NamingClass);
6415 }
6416 
6417 static void
6418 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6419     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6420 
6421   if (!UME)
6422     return;
6423 
6424   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6425   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6426   // already been captured, or if this is an implicit member function call (if
6427   // it isn't, an attempt to capture 'this' should already have been made).
6428   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6429       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6430     return;
6431 
6432   // Check if the naming class in which the unresolved members were found is
6433   // related (same as or is a base of) to the enclosing class.
6434 
6435   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6436     return;
6437 
6438 
6439   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6440   // If the enclosing function is not dependent, then this lambda is
6441   // capture ready, so if we can capture this, do so.
6442   if (!EnclosingFunctionCtx->isDependentContext()) {
6443     // If the current lambda and all enclosing lambdas can capture 'this' -
6444     // then go ahead and capture 'this' (since our unresolved overload set
6445     // contains at least one non-static member function).
6446     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6447       S.CheckCXXThisCapture(CallLoc);
6448   } else if (S.CurContext->isDependentContext()) {
6449     // ... since this is an implicit member reference, that might potentially
6450     // involve a 'this' capture, mark 'this' for potential capture in
6451     // enclosing lambdas.
6452     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6453       CurLSI->addPotentialThisCapture(CallLoc);
6454   }
6455 }
6456 
6457 // Once a call is fully resolved, warn for unqualified calls to specific
6458 // C++ standard functions, like move and forward.
6459 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6460   // We are only checking unary move and forward so exit early here.
6461   if (Call->getNumArgs() != 1)
6462     return;
6463 
6464   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6465   if (!E || isa<UnresolvedLookupExpr>(E))
6466     return;
6467   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6468   if (!DRE || !DRE->getLocation().isValid())
6469     return;
6470 
6471   if (DRE->getQualifier())
6472     return;
6473 
6474   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6475   if (!D || !D->isInStdNamespace())
6476     return;
6477 
6478   // Only warn for some functions deemed more frequent or problematic.
6479   static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6480   auto it = llvm::find(SpecialFunctions, D->getName());
6481   if (it == std::end(SpecialFunctions))
6482     return;
6483 
6484   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6485       << D->getQualifiedNameAsString()
6486       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6487 }
6488 
6489 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6490                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6491                                Expr *ExecConfig) {
6492   ExprResult Call =
6493       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6494                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6495   if (Call.isInvalid())
6496     return Call;
6497 
6498   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6499   // language modes.
6500   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6501     if (ULE->hasExplicitTemplateArgs() &&
6502         ULE->decls_begin() == ULE->decls_end()) {
6503       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6504                                  ? diag::warn_cxx17_compat_adl_only_template_id
6505                                  : diag::ext_adl_only_template_id)
6506           << ULE->getName();
6507     }
6508   }
6509 
6510   if (LangOpts.OpenMP)
6511     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6512                            ExecConfig);
6513   if (LangOpts.CPlusPlus) {
6514     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6515     if (CE)
6516       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6517   }
6518   return Call;
6519 }
6520 
6521 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6522 /// This provides the location of the left/right parens and a list of comma
6523 /// locations.
6524 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6525                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6526                                Expr *ExecConfig, bool IsExecConfig,
6527                                bool AllowRecovery) {
6528   // Since this might be a postfix expression, get rid of ParenListExprs.
6529   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6530   if (Result.isInvalid()) return ExprError();
6531   Fn = Result.get();
6532 
6533   if (checkArgsForPlaceholders(*this, ArgExprs))
6534     return ExprError();
6535 
6536   if (getLangOpts().CPlusPlus) {
6537     // If this is a pseudo-destructor expression, build the call immediately.
6538     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6539       if (!ArgExprs.empty()) {
6540         // Pseudo-destructor calls should not have any arguments.
6541         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6542             << FixItHint::CreateRemoval(
6543                    SourceRange(ArgExprs.front()->getBeginLoc(),
6544                                ArgExprs.back()->getEndLoc()));
6545       }
6546 
6547       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6548                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6549     }
6550     if (Fn->getType() == Context.PseudoObjectTy) {
6551       ExprResult result = CheckPlaceholderExpr(Fn);
6552       if (result.isInvalid()) return ExprError();
6553       Fn = result.get();
6554     }
6555 
6556     // Determine whether this is a dependent call inside a C++ template,
6557     // in which case we won't do any semantic analysis now.
6558     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6559       if (ExecConfig) {
6560         return CUDAKernelCallExpr::Create(Context, Fn,
6561                                           cast<CallExpr>(ExecConfig), ArgExprs,
6562                                           Context.DependentTy, VK_PRValue,
6563                                           RParenLoc, CurFPFeatureOverrides());
6564       } else {
6565 
6566         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6567             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6568             Fn->getBeginLoc());
6569 
6570         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6571                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6572       }
6573     }
6574 
6575     // Determine whether this is a call to an object (C++ [over.call.object]).
6576     if (Fn->getType()->isRecordType())
6577       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6578                                           RParenLoc);
6579 
6580     if (Fn->getType() == Context.UnknownAnyTy) {
6581       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6582       if (result.isInvalid()) return ExprError();
6583       Fn = result.get();
6584     }
6585 
6586     if (Fn->getType() == Context.BoundMemberTy) {
6587       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6588                                        RParenLoc, ExecConfig, IsExecConfig,
6589                                        AllowRecovery);
6590     }
6591   }
6592 
6593   // Check for overloaded calls.  This can happen even in C due to extensions.
6594   if (Fn->getType() == Context.OverloadTy) {
6595     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6596 
6597     // We aren't supposed to apply this logic if there's an '&' involved.
6598     if (!find.HasFormOfMemberPointer) {
6599       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6600         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6601                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6602       OverloadExpr *ovl = find.Expression;
6603       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6604         return BuildOverloadedCallExpr(
6605             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6606             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6607       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6608                                        RParenLoc, ExecConfig, IsExecConfig,
6609                                        AllowRecovery);
6610     }
6611   }
6612 
6613   // If we're directly calling a function, get the appropriate declaration.
6614   if (Fn->getType() == Context.UnknownAnyTy) {
6615     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6616     if (result.isInvalid()) return ExprError();
6617     Fn = result.get();
6618   }
6619 
6620   Expr *NakedFn = Fn->IgnoreParens();
6621 
6622   bool CallingNDeclIndirectly = false;
6623   NamedDecl *NDecl = nullptr;
6624   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6625     if (UnOp->getOpcode() == UO_AddrOf) {
6626       CallingNDeclIndirectly = true;
6627       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6628     }
6629   }
6630 
6631   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6632     NDecl = DRE->getDecl();
6633 
6634     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6635     if (FDecl && FDecl->getBuiltinID()) {
6636       // Rewrite the function decl for this builtin by replacing parameters
6637       // with no explicit address space with the address space of the arguments
6638       // in ArgExprs.
6639       if ((FDecl =
6640                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6641         NDecl = FDecl;
6642         Fn = DeclRefExpr::Create(
6643             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6644             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6645             nullptr, DRE->isNonOdrUse());
6646       }
6647     }
6648   } else if (isa<MemberExpr>(NakedFn))
6649     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6650 
6651   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6652     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6653                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6654       return ExprError();
6655 
6656     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6657 
6658     // If this expression is a call to a builtin function in HIP device
6659     // compilation, allow a pointer-type argument to default address space to be
6660     // passed as a pointer-type parameter to a non-default address space.
6661     // If Arg is declared in the default address space and Param is declared
6662     // in a non-default address space, perform an implicit address space cast to
6663     // the parameter type.
6664     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6665         FD->getBuiltinID()) {
6666       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6667         ParmVarDecl *Param = FD->getParamDecl(Idx);
6668         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6669             !ArgExprs[Idx]->getType()->isPointerType())
6670           continue;
6671 
6672         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6673         auto ArgTy = ArgExprs[Idx]->getType();
6674         auto ArgPtTy = ArgTy->getPointeeType();
6675         auto ArgAS = ArgPtTy.getAddressSpace();
6676 
6677         // Add address space cast if target address spaces are different
6678         bool NeedImplicitASC =
6679           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6680           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6681                                               // or from specific AS which has target AS matching that of Param.
6682           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6683         if (!NeedImplicitASC)
6684           continue;
6685 
6686         // First, ensure that the Arg is an RValue.
6687         if (ArgExprs[Idx]->isGLValue()) {
6688           ArgExprs[Idx] = ImplicitCastExpr::Create(
6689               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6690               nullptr, VK_PRValue, FPOptionsOverride());
6691         }
6692 
6693         // Construct a new arg type with address space of Param
6694         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6695         ArgPtQuals.setAddressSpace(ParamAS);
6696         auto NewArgPtTy =
6697             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6698         auto NewArgTy =
6699             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6700                                      ArgTy.getQualifiers());
6701 
6702         // Finally perform an implicit address space cast
6703         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6704                                           CK_AddressSpaceConversion)
6705                             .get();
6706       }
6707     }
6708   }
6709 
6710   if (Context.isDependenceAllowed() &&
6711       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6712     assert(!getLangOpts().CPlusPlus);
6713     assert((Fn->containsErrors() ||
6714             llvm::any_of(ArgExprs,
6715                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6716            "should only occur in error-recovery path.");
6717     QualType ReturnType =
6718         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6719             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6720             : Context.DependentTy;
6721     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6722                             Expr::getValueKindForType(ReturnType), RParenLoc,
6723                             CurFPFeatureOverrides());
6724   }
6725   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6726                                ExecConfig, IsExecConfig);
6727 }
6728 
6729 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6730 //  with the specified CallArgs
6731 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6732                                  MultiExprArg CallArgs) {
6733   StringRef Name = Context.BuiltinInfo.getName(Id);
6734   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6735                  Sema::LookupOrdinaryName);
6736   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6737 
6738   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6739   assert(BuiltInDecl && "failed to find builtin declaration");
6740 
6741   ExprResult DeclRef =
6742       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6743   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6744 
6745   ExprResult Call =
6746       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6747 
6748   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6749   return Call.get();
6750 }
6751 
6752 /// Parse a __builtin_astype expression.
6753 ///
6754 /// __builtin_astype( value, dst type )
6755 ///
6756 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6757                                  SourceLocation BuiltinLoc,
6758                                  SourceLocation RParenLoc) {
6759   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6760   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6761 }
6762 
6763 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6764 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6765                                  SourceLocation BuiltinLoc,
6766                                  SourceLocation RParenLoc) {
6767   ExprValueKind VK = VK_PRValue;
6768   ExprObjectKind OK = OK_Ordinary;
6769   QualType SrcTy = E->getType();
6770   if (!SrcTy->isDependentType() &&
6771       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6772     return ExprError(
6773         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6774         << DestTy << SrcTy << E->getSourceRange());
6775   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6776 }
6777 
6778 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6779 /// provided arguments.
6780 ///
6781 /// __builtin_convertvector( value, dst type )
6782 ///
6783 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6784                                         SourceLocation BuiltinLoc,
6785                                         SourceLocation RParenLoc) {
6786   TypeSourceInfo *TInfo;
6787   GetTypeFromParser(ParsedDestTy, &TInfo);
6788   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6789 }
6790 
6791 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6792 /// i.e. an expression not of \p OverloadTy.  The expression should
6793 /// unary-convert to an expression of function-pointer or
6794 /// block-pointer type.
6795 ///
6796 /// \param NDecl the declaration being called, if available
6797 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6798                                        SourceLocation LParenLoc,
6799                                        ArrayRef<Expr *> Args,
6800                                        SourceLocation RParenLoc, Expr *Config,
6801                                        bool IsExecConfig, ADLCallKind UsesADL) {
6802   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6803   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6804 
6805   // Functions with 'interrupt' attribute cannot be called directly.
6806   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6807     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6808     return ExprError();
6809   }
6810 
6811   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6812   // so there's some risk when calling out to non-interrupt handler functions
6813   // that the callee might not preserve them. This is easy to diagnose here,
6814   // but can be very challenging to debug.
6815   // Likewise, X86 interrupt handlers may only call routines with attribute
6816   // no_caller_saved_registers since there is no efficient way to
6817   // save and restore the non-GPR state.
6818   if (auto *Caller = getCurFunctionDecl()) {
6819     if (Caller->hasAttr<ARMInterruptAttr>()) {
6820       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6821       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6822         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6823         if (FDecl)
6824           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6825       }
6826     }
6827     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6828         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6829       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6830       if (FDecl)
6831         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6832     }
6833   }
6834 
6835   // Promote the function operand.
6836   // We special-case function promotion here because we only allow promoting
6837   // builtin functions to function pointers in the callee of a call.
6838   ExprResult Result;
6839   QualType ResultTy;
6840   if (BuiltinID &&
6841       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6842     // Extract the return type from the (builtin) function pointer type.
6843     // FIXME Several builtins still have setType in
6844     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6845     // Builtins.def to ensure they are correct before removing setType calls.
6846     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6847     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6848     ResultTy = FDecl->getCallResultType();
6849   } else {
6850     Result = CallExprUnaryConversions(Fn);
6851     ResultTy = Context.BoolTy;
6852   }
6853   if (Result.isInvalid())
6854     return ExprError();
6855   Fn = Result.get();
6856 
6857   // Check for a valid function type, but only if it is not a builtin which
6858   // requires custom type checking. These will be handled by
6859   // CheckBuiltinFunctionCall below just after creation of the call expression.
6860   const FunctionType *FuncT = nullptr;
6861   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6862   retry:
6863     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6864       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6865       // have type pointer to function".
6866       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6867       if (!FuncT)
6868         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6869                          << Fn->getType() << Fn->getSourceRange());
6870     } else if (const BlockPointerType *BPT =
6871                    Fn->getType()->getAs<BlockPointerType>()) {
6872       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6873     } else {
6874       // Handle calls to expressions of unknown-any type.
6875       if (Fn->getType() == Context.UnknownAnyTy) {
6876         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6877         if (rewrite.isInvalid())
6878           return ExprError();
6879         Fn = rewrite.get();
6880         goto retry;
6881       }
6882 
6883       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6884                        << Fn->getType() << Fn->getSourceRange());
6885     }
6886   }
6887 
6888   // Get the number of parameters in the function prototype, if any.
6889   // We will allocate space for max(Args.size(), NumParams) arguments
6890   // in the call expression.
6891   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6892   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6893 
6894   CallExpr *TheCall;
6895   if (Config) {
6896     assert(UsesADL == ADLCallKind::NotADL &&
6897            "CUDAKernelCallExpr should not use ADL");
6898     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6899                                          Args, ResultTy, VK_PRValue, RParenLoc,
6900                                          CurFPFeatureOverrides(), NumParams);
6901   } else {
6902     TheCall =
6903         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6904                          CurFPFeatureOverrides(), NumParams, UsesADL);
6905   }
6906 
6907   if (!Context.isDependenceAllowed()) {
6908     // Forget about the nulled arguments since typo correction
6909     // do not handle them well.
6910     TheCall->shrinkNumArgs(Args.size());
6911     // C cannot always handle TypoExpr nodes in builtin calls and direct
6912     // function calls as their argument checking don't necessarily handle
6913     // dependent types properly, so make sure any TypoExprs have been
6914     // dealt with.
6915     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6916     if (!Result.isUsable()) return ExprError();
6917     CallExpr *TheOldCall = TheCall;
6918     TheCall = dyn_cast<CallExpr>(Result.get());
6919     bool CorrectedTypos = TheCall != TheOldCall;
6920     if (!TheCall) return Result;
6921     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6922 
6923     // A new call expression node was created if some typos were corrected.
6924     // However it may not have been constructed with enough storage. In this
6925     // case, rebuild the node with enough storage. The waste of space is
6926     // immaterial since this only happens when some typos were corrected.
6927     if (CorrectedTypos && Args.size() < NumParams) {
6928       if (Config)
6929         TheCall = CUDAKernelCallExpr::Create(
6930             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6931             RParenLoc, CurFPFeatureOverrides(), NumParams);
6932       else
6933         TheCall =
6934             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6935                              CurFPFeatureOverrides(), NumParams, UsesADL);
6936     }
6937     // We can now handle the nulled arguments for the default arguments.
6938     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6939   }
6940 
6941   // Bail out early if calling a builtin with custom type checking.
6942   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6943     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6944 
6945   if (getLangOpts().CUDA) {
6946     if (Config) {
6947       // CUDA: Kernel calls must be to global functions
6948       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6949         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6950             << FDecl << Fn->getSourceRange());
6951 
6952       // CUDA: Kernel function must have 'void' return type
6953       if (!FuncT->getReturnType()->isVoidType() &&
6954           !FuncT->getReturnType()->getAs<AutoType>() &&
6955           !FuncT->getReturnType()->isInstantiationDependentType())
6956         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6957             << Fn->getType() << Fn->getSourceRange());
6958     } else {
6959       // CUDA: Calls to global functions must be configured
6960       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6961         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6962             << FDecl << Fn->getSourceRange());
6963     }
6964   }
6965 
6966   // Check for a valid return type
6967   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6968                           FDecl))
6969     return ExprError();
6970 
6971   // We know the result type of the call, set it.
6972   TheCall->setType(FuncT->getCallResultType(Context));
6973   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6974 
6975   if (Proto) {
6976     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6977                                 IsExecConfig))
6978       return ExprError();
6979   } else {
6980     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6981 
6982     if (FDecl) {
6983       // Check if we have too few/too many template arguments, based
6984       // on our knowledge of the function definition.
6985       const FunctionDecl *Def = nullptr;
6986       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6987         Proto = Def->getType()->getAs<FunctionProtoType>();
6988        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6989           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6990           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6991       }
6992 
6993       // If the function we're calling isn't a function prototype, but we have
6994       // a function prototype from a prior declaratiom, use that prototype.
6995       if (!FDecl->hasPrototype())
6996         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6997     }
6998 
6999     // Promote the arguments (C99 6.5.2.2p6).
7000     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7001       Expr *Arg = Args[i];
7002 
7003       if (Proto && i < Proto->getNumParams()) {
7004         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7005             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7006         ExprResult ArgE =
7007             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7008         if (ArgE.isInvalid())
7009           return true;
7010 
7011         Arg = ArgE.getAs<Expr>();
7012 
7013       } else {
7014         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7015 
7016         if (ArgE.isInvalid())
7017           return true;
7018 
7019         Arg = ArgE.getAs<Expr>();
7020       }
7021 
7022       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7023                               diag::err_call_incomplete_argument, Arg))
7024         return ExprError();
7025 
7026       TheCall->setArg(i, Arg);
7027     }
7028     TheCall->computeDependence();
7029   }
7030 
7031   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7032     if (!Method->isStatic())
7033       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7034         << Fn->getSourceRange());
7035 
7036   // Check for sentinels
7037   if (NDecl)
7038     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7039 
7040   // Warn for unions passing across security boundary (CMSE).
7041   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7042     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7043       if (const auto *RT =
7044               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7045         if (RT->getDecl()->isOrContainsUnion())
7046           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7047               << 0 << i;
7048       }
7049     }
7050   }
7051 
7052   // Do special checking on direct calls to functions.
7053   if (FDecl) {
7054     if (CheckFunctionCall(FDecl, TheCall, Proto))
7055       return ExprError();
7056 
7057     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7058 
7059     if (BuiltinID)
7060       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7061   } else if (NDecl) {
7062     if (CheckPointerCall(NDecl, TheCall, Proto))
7063       return ExprError();
7064   } else {
7065     if (CheckOtherCall(TheCall, Proto))
7066       return ExprError();
7067   }
7068 
7069   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7070 }
7071 
7072 ExprResult
7073 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7074                            SourceLocation RParenLoc, Expr *InitExpr) {
7075   assert(Ty && "ActOnCompoundLiteral(): missing type");
7076   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7077 
7078   TypeSourceInfo *TInfo;
7079   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7080   if (!TInfo)
7081     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7082 
7083   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7084 }
7085 
7086 ExprResult
7087 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7088                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7089   QualType literalType = TInfo->getType();
7090 
7091   if (literalType->isArrayType()) {
7092     if (RequireCompleteSizedType(
7093             LParenLoc, Context.getBaseElementType(literalType),
7094             diag::err_array_incomplete_or_sizeless_type,
7095             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7096       return ExprError();
7097     if (literalType->isVariableArrayType()) {
7098       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7099                                            diag::err_variable_object_no_init)) {
7100         return ExprError();
7101       }
7102     }
7103   } else if (!literalType->isDependentType() &&
7104              RequireCompleteType(LParenLoc, literalType,
7105                diag::err_typecheck_decl_incomplete_type,
7106                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7107     return ExprError();
7108 
7109   InitializedEntity Entity
7110     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7111   InitializationKind Kind
7112     = InitializationKind::CreateCStyleCast(LParenLoc,
7113                                            SourceRange(LParenLoc, RParenLoc),
7114                                            /*InitList=*/true);
7115   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7116   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7117                                       &literalType);
7118   if (Result.isInvalid())
7119     return ExprError();
7120   LiteralExpr = Result.get();
7121 
7122   bool isFileScope = !CurContext->isFunctionOrMethod();
7123 
7124   // In C, compound literals are l-values for some reason.
7125   // For GCC compatibility, in C++, file-scope array compound literals with
7126   // constant initializers are also l-values, and compound literals are
7127   // otherwise prvalues.
7128   //
7129   // (GCC also treats C++ list-initialized file-scope array prvalues with
7130   // constant initializers as l-values, but that's non-conforming, so we don't
7131   // follow it there.)
7132   //
7133   // FIXME: It would be better to handle the lvalue cases as materializing and
7134   // lifetime-extending a temporary object, but our materialized temporaries
7135   // representation only supports lifetime extension from a variable, not "out
7136   // of thin air".
7137   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7138   // is bound to the result of applying array-to-pointer decay to the compound
7139   // literal.
7140   // FIXME: GCC supports compound literals of reference type, which should
7141   // obviously have a value kind derived from the kind of reference involved.
7142   ExprValueKind VK =
7143       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7144           ? VK_PRValue
7145           : VK_LValue;
7146 
7147   if (isFileScope)
7148     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7149       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7150         Expr *Init = ILE->getInit(i);
7151         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7152       }
7153 
7154   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7155                                               VK, LiteralExpr, isFileScope);
7156   if (isFileScope) {
7157     if (!LiteralExpr->isTypeDependent() &&
7158         !LiteralExpr->isValueDependent() &&
7159         !literalType->isDependentType()) // C99 6.5.2.5p3
7160       if (CheckForConstantInitializer(LiteralExpr, literalType))
7161         return ExprError();
7162   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7163              literalType.getAddressSpace() != LangAS::Default) {
7164     // Embedded-C extensions to C99 6.5.2.5:
7165     //   "If the compound literal occurs inside the body of a function, the
7166     //   type name shall not be qualified by an address-space qualifier."
7167     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7168       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7169     return ExprError();
7170   }
7171 
7172   if (!isFileScope && !getLangOpts().CPlusPlus) {
7173     // Compound literals that have automatic storage duration are destroyed at
7174     // the end of the scope in C; in C++, they're just temporaries.
7175 
7176     // Emit diagnostics if it is or contains a C union type that is non-trivial
7177     // to destruct.
7178     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7179       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7180                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7181 
7182     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7183     if (literalType.isDestructedType()) {
7184       Cleanup.setExprNeedsCleanups(true);
7185       ExprCleanupObjects.push_back(E);
7186       getCurFunction()->setHasBranchProtectedScope();
7187     }
7188   }
7189 
7190   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7191       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7192     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7193                                        E->getInitializer()->getExprLoc());
7194 
7195   return MaybeBindToTemporary(E);
7196 }
7197 
7198 ExprResult
7199 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7200                     SourceLocation RBraceLoc) {
7201   // Only produce each kind of designated initialization diagnostic once.
7202   SourceLocation FirstDesignator;
7203   bool DiagnosedArrayDesignator = false;
7204   bool DiagnosedNestedDesignator = false;
7205   bool DiagnosedMixedDesignator = false;
7206 
7207   // Check that any designated initializers are syntactically valid in the
7208   // current language mode.
7209   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7210     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7211       if (FirstDesignator.isInvalid())
7212         FirstDesignator = DIE->getBeginLoc();
7213 
7214       if (!getLangOpts().CPlusPlus)
7215         break;
7216 
7217       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7218         DiagnosedNestedDesignator = true;
7219         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7220           << DIE->getDesignatorsSourceRange();
7221       }
7222 
7223       for (auto &Desig : DIE->designators()) {
7224         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7225           DiagnosedArrayDesignator = true;
7226           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7227             << Desig.getSourceRange();
7228         }
7229       }
7230 
7231       if (!DiagnosedMixedDesignator &&
7232           !isa<DesignatedInitExpr>(InitArgList[0])) {
7233         DiagnosedMixedDesignator = true;
7234         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7235           << DIE->getSourceRange();
7236         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7237           << InitArgList[0]->getSourceRange();
7238       }
7239     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7240                isa<DesignatedInitExpr>(InitArgList[0])) {
7241       DiagnosedMixedDesignator = true;
7242       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7243       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7244         << DIE->getSourceRange();
7245       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7246         << InitArgList[I]->getSourceRange();
7247     }
7248   }
7249 
7250   if (FirstDesignator.isValid()) {
7251     // Only diagnose designated initiaization as a C++20 extension if we didn't
7252     // already diagnose use of (non-C++20) C99 designator syntax.
7253     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7254         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7255       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7256                                 ? diag::warn_cxx17_compat_designated_init
7257                                 : diag::ext_cxx_designated_init);
7258     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7259       Diag(FirstDesignator, diag::ext_designated_init);
7260     }
7261   }
7262 
7263   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7264 }
7265 
7266 ExprResult
7267 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7268                     SourceLocation RBraceLoc) {
7269   // Semantic analysis for initializers is done by ActOnDeclarator() and
7270   // CheckInitializer() - it requires knowledge of the object being initialized.
7271 
7272   // Immediately handle non-overload placeholders.  Overloads can be
7273   // resolved contextually, but everything else here can't.
7274   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7275     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7276       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7277 
7278       // Ignore failures; dropping the entire initializer list because
7279       // of one failure would be terrible for indexing/etc.
7280       if (result.isInvalid()) continue;
7281 
7282       InitArgList[I] = result.get();
7283     }
7284   }
7285 
7286   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7287                                                RBraceLoc);
7288   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7289   return E;
7290 }
7291 
7292 /// Do an explicit extend of the given block pointer if we're in ARC.
7293 void Sema::maybeExtendBlockObject(ExprResult &E) {
7294   assert(E.get()->getType()->isBlockPointerType());
7295   assert(E.get()->isPRValue());
7296 
7297   // Only do this in an r-value context.
7298   if (!getLangOpts().ObjCAutoRefCount) return;
7299 
7300   E = ImplicitCastExpr::Create(
7301       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7302       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7303   Cleanup.setExprNeedsCleanups(true);
7304 }
7305 
7306 /// Prepare a conversion of the given expression to an ObjC object
7307 /// pointer type.
7308 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7309   QualType type = E.get()->getType();
7310   if (type->isObjCObjectPointerType()) {
7311     return CK_BitCast;
7312   } else if (type->isBlockPointerType()) {
7313     maybeExtendBlockObject(E);
7314     return CK_BlockPointerToObjCPointerCast;
7315   } else {
7316     assert(type->isPointerType());
7317     return CK_CPointerToObjCPointerCast;
7318   }
7319 }
7320 
7321 /// Prepares for a scalar cast, performing all the necessary stages
7322 /// except the final cast and returning the kind required.
7323 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7324   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7325   // Also, callers should have filtered out the invalid cases with
7326   // pointers.  Everything else should be possible.
7327 
7328   QualType SrcTy = Src.get()->getType();
7329   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7330     return CK_NoOp;
7331 
7332   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7333   case Type::STK_MemberPointer:
7334     llvm_unreachable("member pointer type in C");
7335 
7336   case Type::STK_CPointer:
7337   case Type::STK_BlockPointer:
7338   case Type::STK_ObjCObjectPointer:
7339     switch (DestTy->getScalarTypeKind()) {
7340     case Type::STK_CPointer: {
7341       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7342       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7343       if (SrcAS != DestAS)
7344         return CK_AddressSpaceConversion;
7345       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7346         return CK_NoOp;
7347       return CK_BitCast;
7348     }
7349     case Type::STK_BlockPointer:
7350       return (SrcKind == Type::STK_BlockPointer
7351                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7352     case Type::STK_ObjCObjectPointer:
7353       if (SrcKind == Type::STK_ObjCObjectPointer)
7354         return CK_BitCast;
7355       if (SrcKind == Type::STK_CPointer)
7356         return CK_CPointerToObjCPointerCast;
7357       maybeExtendBlockObject(Src);
7358       return CK_BlockPointerToObjCPointerCast;
7359     case Type::STK_Bool:
7360       return CK_PointerToBoolean;
7361     case Type::STK_Integral:
7362       return CK_PointerToIntegral;
7363     case Type::STK_Floating:
7364     case Type::STK_FloatingComplex:
7365     case Type::STK_IntegralComplex:
7366     case Type::STK_MemberPointer:
7367     case Type::STK_FixedPoint:
7368       llvm_unreachable("illegal cast from pointer");
7369     }
7370     llvm_unreachable("Should have returned before this");
7371 
7372   case Type::STK_FixedPoint:
7373     switch (DestTy->getScalarTypeKind()) {
7374     case Type::STK_FixedPoint:
7375       return CK_FixedPointCast;
7376     case Type::STK_Bool:
7377       return CK_FixedPointToBoolean;
7378     case Type::STK_Integral:
7379       return CK_FixedPointToIntegral;
7380     case Type::STK_Floating:
7381       return CK_FixedPointToFloating;
7382     case Type::STK_IntegralComplex:
7383     case Type::STK_FloatingComplex:
7384       Diag(Src.get()->getExprLoc(),
7385            diag::err_unimplemented_conversion_with_fixed_point_type)
7386           << DestTy;
7387       return CK_IntegralCast;
7388     case Type::STK_CPointer:
7389     case Type::STK_ObjCObjectPointer:
7390     case Type::STK_BlockPointer:
7391     case Type::STK_MemberPointer:
7392       llvm_unreachable("illegal cast to pointer type");
7393     }
7394     llvm_unreachable("Should have returned before this");
7395 
7396   case Type::STK_Bool: // casting from bool is like casting from an integer
7397   case Type::STK_Integral:
7398     switch (DestTy->getScalarTypeKind()) {
7399     case Type::STK_CPointer:
7400     case Type::STK_ObjCObjectPointer:
7401     case Type::STK_BlockPointer:
7402       if (Src.get()->isNullPointerConstant(Context,
7403                                            Expr::NPC_ValueDependentIsNull))
7404         return CK_NullToPointer;
7405       return CK_IntegralToPointer;
7406     case Type::STK_Bool:
7407       return CK_IntegralToBoolean;
7408     case Type::STK_Integral:
7409       return CK_IntegralCast;
7410     case Type::STK_Floating:
7411       return CK_IntegralToFloating;
7412     case Type::STK_IntegralComplex:
7413       Src = ImpCastExprToType(Src.get(),
7414                       DestTy->castAs<ComplexType>()->getElementType(),
7415                       CK_IntegralCast);
7416       return CK_IntegralRealToComplex;
7417     case Type::STK_FloatingComplex:
7418       Src = ImpCastExprToType(Src.get(),
7419                       DestTy->castAs<ComplexType>()->getElementType(),
7420                       CK_IntegralToFloating);
7421       return CK_FloatingRealToComplex;
7422     case Type::STK_MemberPointer:
7423       llvm_unreachable("member pointer type in C");
7424     case Type::STK_FixedPoint:
7425       return CK_IntegralToFixedPoint;
7426     }
7427     llvm_unreachable("Should have returned before this");
7428 
7429   case Type::STK_Floating:
7430     switch (DestTy->getScalarTypeKind()) {
7431     case Type::STK_Floating:
7432       return CK_FloatingCast;
7433     case Type::STK_Bool:
7434       return CK_FloatingToBoolean;
7435     case Type::STK_Integral:
7436       return CK_FloatingToIntegral;
7437     case Type::STK_FloatingComplex:
7438       Src = ImpCastExprToType(Src.get(),
7439                               DestTy->castAs<ComplexType>()->getElementType(),
7440                               CK_FloatingCast);
7441       return CK_FloatingRealToComplex;
7442     case Type::STK_IntegralComplex:
7443       Src = ImpCastExprToType(Src.get(),
7444                               DestTy->castAs<ComplexType>()->getElementType(),
7445                               CK_FloatingToIntegral);
7446       return CK_IntegralRealToComplex;
7447     case Type::STK_CPointer:
7448     case Type::STK_ObjCObjectPointer:
7449     case Type::STK_BlockPointer:
7450       llvm_unreachable("valid float->pointer cast?");
7451     case Type::STK_MemberPointer:
7452       llvm_unreachable("member pointer type in C");
7453     case Type::STK_FixedPoint:
7454       return CK_FloatingToFixedPoint;
7455     }
7456     llvm_unreachable("Should have returned before this");
7457 
7458   case Type::STK_FloatingComplex:
7459     switch (DestTy->getScalarTypeKind()) {
7460     case Type::STK_FloatingComplex:
7461       return CK_FloatingComplexCast;
7462     case Type::STK_IntegralComplex:
7463       return CK_FloatingComplexToIntegralComplex;
7464     case Type::STK_Floating: {
7465       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7466       if (Context.hasSameType(ET, DestTy))
7467         return CK_FloatingComplexToReal;
7468       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7469       return CK_FloatingCast;
7470     }
7471     case Type::STK_Bool:
7472       return CK_FloatingComplexToBoolean;
7473     case Type::STK_Integral:
7474       Src = ImpCastExprToType(Src.get(),
7475                               SrcTy->castAs<ComplexType>()->getElementType(),
7476                               CK_FloatingComplexToReal);
7477       return CK_FloatingToIntegral;
7478     case Type::STK_CPointer:
7479     case Type::STK_ObjCObjectPointer:
7480     case Type::STK_BlockPointer:
7481       llvm_unreachable("valid complex float->pointer cast?");
7482     case Type::STK_MemberPointer:
7483       llvm_unreachable("member pointer type in C");
7484     case Type::STK_FixedPoint:
7485       Diag(Src.get()->getExprLoc(),
7486            diag::err_unimplemented_conversion_with_fixed_point_type)
7487           << SrcTy;
7488       return CK_IntegralCast;
7489     }
7490     llvm_unreachable("Should have returned before this");
7491 
7492   case Type::STK_IntegralComplex:
7493     switch (DestTy->getScalarTypeKind()) {
7494     case Type::STK_FloatingComplex:
7495       return CK_IntegralComplexToFloatingComplex;
7496     case Type::STK_IntegralComplex:
7497       return CK_IntegralComplexCast;
7498     case Type::STK_Integral: {
7499       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7500       if (Context.hasSameType(ET, DestTy))
7501         return CK_IntegralComplexToReal;
7502       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7503       return CK_IntegralCast;
7504     }
7505     case Type::STK_Bool:
7506       return CK_IntegralComplexToBoolean;
7507     case Type::STK_Floating:
7508       Src = ImpCastExprToType(Src.get(),
7509                               SrcTy->castAs<ComplexType>()->getElementType(),
7510                               CK_IntegralComplexToReal);
7511       return CK_IntegralToFloating;
7512     case Type::STK_CPointer:
7513     case Type::STK_ObjCObjectPointer:
7514     case Type::STK_BlockPointer:
7515       llvm_unreachable("valid complex int->pointer cast?");
7516     case Type::STK_MemberPointer:
7517       llvm_unreachable("member pointer type in C");
7518     case Type::STK_FixedPoint:
7519       Diag(Src.get()->getExprLoc(),
7520            diag::err_unimplemented_conversion_with_fixed_point_type)
7521           << SrcTy;
7522       return CK_IntegralCast;
7523     }
7524     llvm_unreachable("Should have returned before this");
7525   }
7526 
7527   llvm_unreachable("Unhandled scalar cast");
7528 }
7529 
7530 static bool breakDownVectorType(QualType type, uint64_t &len,
7531                                 QualType &eltType) {
7532   // Vectors are simple.
7533   if (const VectorType *vecType = type->getAs<VectorType>()) {
7534     len = vecType->getNumElements();
7535     eltType = vecType->getElementType();
7536     assert(eltType->isScalarType());
7537     return true;
7538   }
7539 
7540   // We allow lax conversion to and from non-vector types, but only if
7541   // they're real types (i.e. non-complex, non-pointer scalar types).
7542   if (!type->isRealType()) return false;
7543 
7544   len = 1;
7545   eltType = type;
7546   return true;
7547 }
7548 
7549 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7550 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7551 /// allowed?
7552 ///
7553 /// This will also return false if the two given types do not make sense from
7554 /// the perspective of SVE bitcasts.
7555 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7556   assert(srcTy->isVectorType() || destTy->isVectorType());
7557 
7558   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7559     if (!FirstType->isSizelessBuiltinType())
7560       return false;
7561 
7562     const auto *VecTy = SecondType->getAs<VectorType>();
7563     return VecTy &&
7564            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7565   };
7566 
7567   return ValidScalableConversion(srcTy, destTy) ||
7568          ValidScalableConversion(destTy, srcTy);
7569 }
7570 
7571 /// Are the two types matrix types and do they have the same dimensions i.e.
7572 /// do they have the same number of rows and the same number of columns?
7573 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7574   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7575     return false;
7576 
7577   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7578   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7579 
7580   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7581          matSrcType->getNumColumns() == matDestType->getNumColumns();
7582 }
7583 
7584 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7585   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7586 
7587   uint64_t SrcLen, DestLen;
7588   QualType SrcEltTy, DestEltTy;
7589   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7590     return false;
7591   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7592     return false;
7593 
7594   // ASTContext::getTypeSize will return the size rounded up to a
7595   // power of 2, so instead of using that, we need to use the raw
7596   // element size multiplied by the element count.
7597   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7598   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7599 
7600   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7601 }
7602 
7603 /// Are the two types lax-compatible vector types?  That is, given
7604 /// that one of them is a vector, do they have equal storage sizes,
7605 /// where the storage size is the number of elements times the element
7606 /// size?
7607 ///
7608 /// This will also return false if either of the types is neither a
7609 /// vector nor a real type.
7610 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7611   assert(destTy->isVectorType() || srcTy->isVectorType());
7612 
7613   // Disallow lax conversions between scalars and ExtVectors (these
7614   // conversions are allowed for other vector types because common headers
7615   // depend on them).  Most scalar OP ExtVector cases are handled by the
7616   // splat path anyway, which does what we want (convert, not bitcast).
7617   // What this rules out for ExtVectors is crazy things like char4*float.
7618   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7619   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7620 
7621   return areVectorTypesSameSize(srcTy, destTy);
7622 }
7623 
7624 /// Is this a legal conversion between two types, one of which is
7625 /// known to be a vector type?
7626 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7627   assert(destTy->isVectorType() || srcTy->isVectorType());
7628 
7629   switch (Context.getLangOpts().getLaxVectorConversions()) {
7630   case LangOptions::LaxVectorConversionKind::None:
7631     return false;
7632 
7633   case LangOptions::LaxVectorConversionKind::Integer:
7634     if (!srcTy->isIntegralOrEnumerationType()) {
7635       auto *Vec = srcTy->getAs<VectorType>();
7636       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7637         return false;
7638     }
7639     if (!destTy->isIntegralOrEnumerationType()) {
7640       auto *Vec = destTy->getAs<VectorType>();
7641       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7642         return false;
7643     }
7644     // OK, integer (vector) -> integer (vector) bitcast.
7645     break;
7646 
7647     case LangOptions::LaxVectorConversionKind::All:
7648     break;
7649   }
7650 
7651   return areLaxCompatibleVectorTypes(srcTy, destTy);
7652 }
7653 
7654 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7655                            CastKind &Kind) {
7656   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7657     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7658       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7659              << DestTy << SrcTy << R;
7660     }
7661   } else if (SrcTy->isMatrixType()) {
7662     return Diag(R.getBegin(),
7663                 diag::err_invalid_conversion_between_matrix_and_type)
7664            << SrcTy << DestTy << R;
7665   } else if (DestTy->isMatrixType()) {
7666     return Diag(R.getBegin(),
7667                 diag::err_invalid_conversion_between_matrix_and_type)
7668            << DestTy << SrcTy << R;
7669   }
7670 
7671   Kind = CK_MatrixCast;
7672   return false;
7673 }
7674 
7675 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7676                            CastKind &Kind) {
7677   assert(VectorTy->isVectorType() && "Not a vector type!");
7678 
7679   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7680     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7681       return Diag(R.getBegin(),
7682                   Ty->isVectorType() ?
7683                   diag::err_invalid_conversion_between_vectors :
7684                   diag::err_invalid_conversion_between_vector_and_integer)
7685         << VectorTy << Ty << R;
7686   } else
7687     return Diag(R.getBegin(),
7688                 diag::err_invalid_conversion_between_vector_and_scalar)
7689       << VectorTy << Ty << R;
7690 
7691   Kind = CK_BitCast;
7692   return false;
7693 }
7694 
7695 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7696   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7697 
7698   if (DestElemTy == SplattedExpr->getType())
7699     return SplattedExpr;
7700 
7701   assert(DestElemTy->isFloatingType() ||
7702          DestElemTy->isIntegralOrEnumerationType());
7703 
7704   CastKind CK;
7705   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7706     // OpenCL requires that we convert `true` boolean expressions to -1, but
7707     // only when splatting vectors.
7708     if (DestElemTy->isFloatingType()) {
7709       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7710       // in two steps: boolean to signed integral, then to floating.
7711       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7712                                                  CK_BooleanToSignedIntegral);
7713       SplattedExpr = CastExprRes.get();
7714       CK = CK_IntegralToFloating;
7715     } else {
7716       CK = CK_BooleanToSignedIntegral;
7717     }
7718   } else {
7719     ExprResult CastExprRes = SplattedExpr;
7720     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7721     if (CastExprRes.isInvalid())
7722       return ExprError();
7723     SplattedExpr = CastExprRes.get();
7724   }
7725   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7726 }
7727 
7728 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7729                                     Expr *CastExpr, CastKind &Kind) {
7730   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7731 
7732   QualType SrcTy = CastExpr->getType();
7733 
7734   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7735   // an ExtVectorType.
7736   // In OpenCL, casts between vectors of different types are not allowed.
7737   // (See OpenCL 6.2).
7738   if (SrcTy->isVectorType()) {
7739     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7740         (getLangOpts().OpenCL &&
7741          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7742       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7743         << DestTy << SrcTy << R;
7744       return ExprError();
7745     }
7746     Kind = CK_BitCast;
7747     return CastExpr;
7748   }
7749 
7750   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7751   // conversion will take place first from scalar to elt type, and then
7752   // splat from elt type to vector.
7753   if (SrcTy->isPointerType())
7754     return Diag(R.getBegin(),
7755                 diag::err_invalid_conversion_between_vector_and_scalar)
7756       << DestTy << SrcTy << R;
7757 
7758   Kind = CK_VectorSplat;
7759   return prepareVectorSplat(DestTy, CastExpr);
7760 }
7761 
7762 ExprResult
7763 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7764                     Declarator &D, ParsedType &Ty,
7765                     SourceLocation RParenLoc, Expr *CastExpr) {
7766   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7767          "ActOnCastExpr(): missing type or expr");
7768 
7769   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7770   if (D.isInvalidType())
7771     return ExprError();
7772 
7773   if (getLangOpts().CPlusPlus) {
7774     // Check that there are no default arguments (C++ only).
7775     CheckExtraCXXDefaultArguments(D);
7776   } else {
7777     // Make sure any TypoExprs have been dealt with.
7778     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7779     if (!Res.isUsable())
7780       return ExprError();
7781     CastExpr = Res.get();
7782   }
7783 
7784   checkUnusedDeclAttributes(D);
7785 
7786   QualType castType = castTInfo->getType();
7787   Ty = CreateParsedType(castType, castTInfo);
7788 
7789   bool isVectorLiteral = false;
7790 
7791   // Check for an altivec or OpenCL literal,
7792   // i.e. all the elements are integer constants.
7793   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7794   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7795   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7796        && castType->isVectorType() && (PE || PLE)) {
7797     if (PLE && PLE->getNumExprs() == 0) {
7798       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7799       return ExprError();
7800     }
7801     if (PE || PLE->getNumExprs() == 1) {
7802       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7803       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7804         isVectorLiteral = true;
7805     }
7806     else
7807       isVectorLiteral = true;
7808   }
7809 
7810   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7811   // then handle it as such.
7812   if (isVectorLiteral)
7813     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7814 
7815   // If the Expr being casted is a ParenListExpr, handle it specially.
7816   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7817   // sequence of BinOp comma operators.
7818   if (isa<ParenListExpr>(CastExpr)) {
7819     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7820     if (Result.isInvalid()) return ExprError();
7821     CastExpr = Result.get();
7822   }
7823 
7824   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7825     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7826 
7827   CheckTollFreeBridgeCast(castType, CastExpr);
7828 
7829   CheckObjCBridgeRelatedCast(castType, CastExpr);
7830 
7831   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7832 
7833   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7834 }
7835 
7836 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7837                                     SourceLocation RParenLoc, Expr *E,
7838                                     TypeSourceInfo *TInfo) {
7839   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7840          "Expected paren or paren list expression");
7841 
7842   Expr **exprs;
7843   unsigned numExprs;
7844   Expr *subExpr;
7845   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7846   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7847     LiteralLParenLoc = PE->getLParenLoc();
7848     LiteralRParenLoc = PE->getRParenLoc();
7849     exprs = PE->getExprs();
7850     numExprs = PE->getNumExprs();
7851   } else { // isa<ParenExpr> by assertion at function entrance
7852     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7853     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7854     subExpr = cast<ParenExpr>(E)->getSubExpr();
7855     exprs = &subExpr;
7856     numExprs = 1;
7857   }
7858 
7859   QualType Ty = TInfo->getType();
7860   assert(Ty->isVectorType() && "Expected vector type");
7861 
7862   SmallVector<Expr *, 8> initExprs;
7863   const VectorType *VTy = Ty->castAs<VectorType>();
7864   unsigned numElems = VTy->getNumElements();
7865 
7866   // '(...)' form of vector initialization in AltiVec: the number of
7867   // initializers must be one or must match the size of the vector.
7868   // If a single value is specified in the initializer then it will be
7869   // replicated to all the components of the vector
7870   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7871                                  VTy->getElementType()))
7872     return ExprError();
7873   if (ShouldSplatAltivecScalarInCast(VTy)) {
7874     // The number of initializers must be one or must match the size of the
7875     // vector. If a single value is specified in the initializer then it will
7876     // be replicated to all the components of the vector
7877     if (numExprs == 1) {
7878       QualType ElemTy = VTy->getElementType();
7879       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7880       if (Literal.isInvalid())
7881         return ExprError();
7882       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7883                                   PrepareScalarCast(Literal, ElemTy));
7884       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7885     }
7886     else if (numExprs < numElems) {
7887       Diag(E->getExprLoc(),
7888            diag::err_incorrect_number_of_vector_initializers);
7889       return ExprError();
7890     }
7891     else
7892       initExprs.append(exprs, exprs + numExprs);
7893   }
7894   else {
7895     // For OpenCL, when the number of initializers is a single value,
7896     // it will be replicated to all components of the vector.
7897     if (getLangOpts().OpenCL &&
7898         VTy->getVectorKind() == VectorType::GenericVector &&
7899         numExprs == 1) {
7900         QualType ElemTy = VTy->getElementType();
7901         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7902         if (Literal.isInvalid())
7903           return ExprError();
7904         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7905                                     PrepareScalarCast(Literal, ElemTy));
7906         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7907     }
7908 
7909     initExprs.append(exprs, exprs + numExprs);
7910   }
7911   // FIXME: This means that pretty-printing the final AST will produce curly
7912   // braces instead of the original commas.
7913   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7914                                                    initExprs, LiteralRParenLoc);
7915   initE->setType(Ty);
7916   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7917 }
7918 
7919 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7920 /// the ParenListExpr into a sequence of comma binary operators.
7921 ExprResult
7922 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7923   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7924   if (!E)
7925     return OrigExpr;
7926 
7927   ExprResult Result(E->getExpr(0));
7928 
7929   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7930     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7931                         E->getExpr(i));
7932 
7933   if (Result.isInvalid()) return ExprError();
7934 
7935   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7936 }
7937 
7938 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7939                                     SourceLocation R,
7940                                     MultiExprArg Val) {
7941   return ParenListExpr::Create(Context, L, Val, R);
7942 }
7943 
7944 /// Emit a specialized diagnostic when one expression is a null pointer
7945 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7946 /// emitted.
7947 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7948                                       SourceLocation QuestionLoc) {
7949   Expr *NullExpr = LHSExpr;
7950   Expr *NonPointerExpr = RHSExpr;
7951   Expr::NullPointerConstantKind NullKind =
7952       NullExpr->isNullPointerConstant(Context,
7953                                       Expr::NPC_ValueDependentIsNotNull);
7954 
7955   if (NullKind == Expr::NPCK_NotNull) {
7956     NullExpr = RHSExpr;
7957     NonPointerExpr = LHSExpr;
7958     NullKind =
7959         NullExpr->isNullPointerConstant(Context,
7960                                         Expr::NPC_ValueDependentIsNotNull);
7961   }
7962 
7963   if (NullKind == Expr::NPCK_NotNull)
7964     return false;
7965 
7966   if (NullKind == Expr::NPCK_ZeroExpression)
7967     return false;
7968 
7969   if (NullKind == Expr::NPCK_ZeroLiteral) {
7970     // In this case, check to make sure that we got here from a "NULL"
7971     // string in the source code.
7972     NullExpr = NullExpr->IgnoreParenImpCasts();
7973     SourceLocation loc = NullExpr->getExprLoc();
7974     if (!findMacroSpelling(loc, "NULL"))
7975       return false;
7976   }
7977 
7978   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7979   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7980       << NonPointerExpr->getType() << DiagType
7981       << NonPointerExpr->getSourceRange();
7982   return true;
7983 }
7984 
7985 /// Return false if the condition expression is valid, true otherwise.
7986 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7987   QualType CondTy = Cond->getType();
7988 
7989   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7990   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7991     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7992       << CondTy << Cond->getSourceRange();
7993     return true;
7994   }
7995 
7996   // C99 6.5.15p2
7997   if (CondTy->isScalarType()) return false;
7998 
7999   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8000     << CondTy << Cond->getSourceRange();
8001   return true;
8002 }
8003 
8004 /// Handle when one or both operands are void type.
8005 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8006                                          ExprResult &RHS) {
8007     Expr *LHSExpr = LHS.get();
8008     Expr *RHSExpr = RHS.get();
8009 
8010     if (!LHSExpr->getType()->isVoidType())
8011       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8012           << RHSExpr->getSourceRange();
8013     if (!RHSExpr->getType()->isVoidType())
8014       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8015           << LHSExpr->getSourceRange();
8016     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8017     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8018     return S.Context.VoidTy;
8019 }
8020 
8021 /// Return false if the NullExpr can be promoted to PointerTy,
8022 /// true otherwise.
8023 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8024                                         QualType PointerTy) {
8025   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8026       !NullExpr.get()->isNullPointerConstant(S.Context,
8027                                             Expr::NPC_ValueDependentIsNull))
8028     return true;
8029 
8030   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8031   return false;
8032 }
8033 
8034 /// Checks compatibility between two pointers and return the resulting
8035 /// type.
8036 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8037                                                      ExprResult &RHS,
8038                                                      SourceLocation Loc) {
8039   QualType LHSTy = LHS.get()->getType();
8040   QualType RHSTy = RHS.get()->getType();
8041 
8042   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8043     // Two identical pointers types are always compatible.
8044     return LHSTy;
8045   }
8046 
8047   QualType lhptee, rhptee;
8048 
8049   // Get the pointee types.
8050   bool IsBlockPointer = false;
8051   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8052     lhptee = LHSBTy->getPointeeType();
8053     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8054     IsBlockPointer = true;
8055   } else {
8056     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8057     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8058   }
8059 
8060   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8061   // differently qualified versions of compatible types, the result type is
8062   // a pointer to an appropriately qualified version of the composite
8063   // type.
8064 
8065   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8066   // clause doesn't make sense for our extensions. E.g. address space 2 should
8067   // be incompatible with address space 3: they may live on different devices or
8068   // anything.
8069   Qualifiers lhQual = lhptee.getQualifiers();
8070   Qualifiers rhQual = rhptee.getQualifiers();
8071 
8072   LangAS ResultAddrSpace = LangAS::Default;
8073   LangAS LAddrSpace = lhQual.getAddressSpace();
8074   LangAS RAddrSpace = rhQual.getAddressSpace();
8075 
8076   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8077   // spaces is disallowed.
8078   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8079     ResultAddrSpace = LAddrSpace;
8080   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8081     ResultAddrSpace = RAddrSpace;
8082   else {
8083     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8084         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8085         << RHS.get()->getSourceRange();
8086     return QualType();
8087   }
8088 
8089   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8090   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8091   lhQual.removeCVRQualifiers();
8092   rhQual.removeCVRQualifiers();
8093 
8094   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8095   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8096   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8097   // qual types are compatible iff
8098   //  * corresponded types are compatible
8099   //  * CVR qualifiers are equal
8100   //  * address spaces are equal
8101   // Thus for conditional operator we merge CVR and address space unqualified
8102   // pointees and if there is a composite type we return a pointer to it with
8103   // merged qualifiers.
8104   LHSCastKind =
8105       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8106   RHSCastKind =
8107       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8108   lhQual.removeAddressSpace();
8109   rhQual.removeAddressSpace();
8110 
8111   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8112   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8113 
8114   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8115 
8116   if (CompositeTy.isNull()) {
8117     // In this situation, we assume void* type. No especially good
8118     // reason, but this is what gcc does, and we do have to pick
8119     // to get a consistent AST.
8120     QualType incompatTy;
8121     incompatTy = S.Context.getPointerType(
8122         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8123     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8124     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8125 
8126     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8127     // for casts between types with incompatible address space qualifiers.
8128     // For the following code the compiler produces casts between global and
8129     // local address spaces of the corresponded innermost pointees:
8130     // local int *global *a;
8131     // global int *global *b;
8132     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8133     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8134         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8135         << RHS.get()->getSourceRange();
8136 
8137     return incompatTy;
8138   }
8139 
8140   // The pointer types are compatible.
8141   // In case of OpenCL ResultTy should have the address space qualifier
8142   // which is a superset of address spaces of both the 2nd and the 3rd
8143   // operands of the conditional operator.
8144   QualType ResultTy = [&, ResultAddrSpace]() {
8145     if (S.getLangOpts().OpenCL) {
8146       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8147       CompositeQuals.setAddressSpace(ResultAddrSpace);
8148       return S.Context
8149           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8150           .withCVRQualifiers(MergedCVRQual);
8151     }
8152     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8153   }();
8154   if (IsBlockPointer)
8155     ResultTy = S.Context.getBlockPointerType(ResultTy);
8156   else
8157     ResultTy = S.Context.getPointerType(ResultTy);
8158 
8159   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8160   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8161   return ResultTy;
8162 }
8163 
8164 /// Return the resulting type when the operands are both block pointers.
8165 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8166                                                           ExprResult &LHS,
8167                                                           ExprResult &RHS,
8168                                                           SourceLocation Loc) {
8169   QualType LHSTy = LHS.get()->getType();
8170   QualType RHSTy = RHS.get()->getType();
8171 
8172   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8173     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8174       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8175       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8176       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8177       return destType;
8178     }
8179     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8180       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8181       << RHS.get()->getSourceRange();
8182     return QualType();
8183   }
8184 
8185   // We have 2 block pointer types.
8186   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8187 }
8188 
8189 /// Return the resulting type when the operands are both pointers.
8190 static QualType
8191 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8192                                             ExprResult &RHS,
8193                                             SourceLocation Loc) {
8194   // get the pointer types
8195   QualType LHSTy = LHS.get()->getType();
8196   QualType RHSTy = RHS.get()->getType();
8197 
8198   // get the "pointed to" types
8199   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8200   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8201 
8202   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8203   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8204     // Figure out necessary qualifiers (C99 6.5.15p6)
8205     QualType destPointee
8206       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8207     QualType destType = S.Context.getPointerType(destPointee);
8208     // Add qualifiers if necessary.
8209     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8210     // Promote to void*.
8211     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8212     return destType;
8213   }
8214   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8215     QualType destPointee
8216       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8217     QualType destType = S.Context.getPointerType(destPointee);
8218     // Add qualifiers if necessary.
8219     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8220     // Promote to void*.
8221     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8222     return destType;
8223   }
8224 
8225   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8226 }
8227 
8228 /// Return false if the first expression is not an integer and the second
8229 /// expression is not a pointer, true otherwise.
8230 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8231                                         Expr* PointerExpr, SourceLocation Loc,
8232                                         bool IsIntFirstExpr) {
8233   if (!PointerExpr->getType()->isPointerType() ||
8234       !Int.get()->getType()->isIntegerType())
8235     return false;
8236 
8237   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8238   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8239 
8240   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8241     << Expr1->getType() << Expr2->getType()
8242     << Expr1->getSourceRange() << Expr2->getSourceRange();
8243   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8244                             CK_IntegralToPointer);
8245   return true;
8246 }
8247 
8248 /// Simple conversion between integer and floating point types.
8249 ///
8250 /// Used when handling the OpenCL conditional operator where the
8251 /// condition is a vector while the other operands are scalar.
8252 ///
8253 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8254 /// types are either integer or floating type. Between the two
8255 /// operands, the type with the higher rank is defined as the "result
8256 /// type". The other operand needs to be promoted to the same type. No
8257 /// other type promotion is allowed. We cannot use
8258 /// UsualArithmeticConversions() for this purpose, since it always
8259 /// promotes promotable types.
8260 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8261                                             ExprResult &RHS,
8262                                             SourceLocation QuestionLoc) {
8263   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8264   if (LHS.isInvalid())
8265     return QualType();
8266   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8267   if (RHS.isInvalid())
8268     return QualType();
8269 
8270   // For conversion purposes, we ignore any qualifiers.
8271   // For example, "const float" and "float" are equivalent.
8272   QualType LHSType =
8273     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8274   QualType RHSType =
8275     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8276 
8277   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8278     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8279       << LHSType << LHS.get()->getSourceRange();
8280     return QualType();
8281   }
8282 
8283   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8284     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8285       << RHSType << RHS.get()->getSourceRange();
8286     return QualType();
8287   }
8288 
8289   // If both types are identical, no conversion is needed.
8290   if (LHSType == RHSType)
8291     return LHSType;
8292 
8293   // Now handle "real" floating types (i.e. float, double, long double).
8294   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8295     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8296                                  /*IsCompAssign = */ false);
8297 
8298   // Finally, we have two differing integer types.
8299   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8300   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8301 }
8302 
8303 /// Convert scalar operands to a vector that matches the
8304 ///        condition in length.
8305 ///
8306 /// Used when handling the OpenCL conditional operator where the
8307 /// condition is a vector while the other operands are scalar.
8308 ///
8309 /// We first compute the "result type" for the scalar operands
8310 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8311 /// into a vector of that type where the length matches the condition
8312 /// vector type. s6.11.6 requires that the element types of the result
8313 /// and the condition must have the same number of bits.
8314 static QualType
8315 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8316                               QualType CondTy, SourceLocation QuestionLoc) {
8317   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8318   if (ResTy.isNull()) return QualType();
8319 
8320   const VectorType *CV = CondTy->getAs<VectorType>();
8321   assert(CV);
8322 
8323   // Determine the vector result type
8324   unsigned NumElements = CV->getNumElements();
8325   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8326 
8327   // Ensure that all types have the same number of bits
8328   if (S.Context.getTypeSize(CV->getElementType())
8329       != S.Context.getTypeSize(ResTy)) {
8330     // Since VectorTy is created internally, it does not pretty print
8331     // with an OpenCL name. Instead, we just print a description.
8332     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8333     SmallString<64> Str;
8334     llvm::raw_svector_ostream OS(Str);
8335     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8336     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8337       << CondTy << OS.str();
8338     return QualType();
8339   }
8340 
8341   // Convert operands to the vector result type
8342   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8343   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8344 
8345   return VectorTy;
8346 }
8347 
8348 /// Return false if this is a valid OpenCL condition vector
8349 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8350                                        SourceLocation QuestionLoc) {
8351   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8352   // integral type.
8353   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8354   assert(CondTy);
8355   QualType EleTy = CondTy->getElementType();
8356   if (EleTy->isIntegerType()) return false;
8357 
8358   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8359     << Cond->getType() << Cond->getSourceRange();
8360   return true;
8361 }
8362 
8363 /// Return false if the vector condition type and the vector
8364 ///        result type are compatible.
8365 ///
8366 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8367 /// number of elements, and their element types have the same number
8368 /// of bits.
8369 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8370                               SourceLocation QuestionLoc) {
8371   const VectorType *CV = CondTy->getAs<VectorType>();
8372   const VectorType *RV = VecResTy->getAs<VectorType>();
8373   assert(CV && RV);
8374 
8375   if (CV->getNumElements() != RV->getNumElements()) {
8376     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8377       << CondTy << VecResTy;
8378     return true;
8379   }
8380 
8381   QualType CVE = CV->getElementType();
8382   QualType RVE = RV->getElementType();
8383 
8384   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8385     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8386       << CondTy << VecResTy;
8387     return true;
8388   }
8389 
8390   return false;
8391 }
8392 
8393 /// Return the resulting type for the conditional operator in
8394 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8395 ///        s6.3.i) when the condition is a vector type.
8396 static QualType
8397 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8398                              ExprResult &LHS, ExprResult &RHS,
8399                              SourceLocation QuestionLoc) {
8400   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8401   if (Cond.isInvalid())
8402     return QualType();
8403   QualType CondTy = Cond.get()->getType();
8404 
8405   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8406     return QualType();
8407 
8408   // If either operand is a vector then find the vector type of the
8409   // result as specified in OpenCL v1.1 s6.3.i.
8410   if (LHS.get()->getType()->isVectorType() ||
8411       RHS.get()->getType()->isVectorType()) {
8412     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8413                                               /*isCompAssign*/false,
8414                                               /*AllowBothBool*/true,
8415                                               /*AllowBoolConversions*/false);
8416     if (VecResTy.isNull()) return QualType();
8417     // The result type must match the condition type as specified in
8418     // OpenCL v1.1 s6.11.6.
8419     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8420       return QualType();
8421     return VecResTy;
8422   }
8423 
8424   // Both operands are scalar.
8425   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8426 }
8427 
8428 /// Return true if the Expr is block type
8429 static bool checkBlockType(Sema &S, const Expr *E) {
8430   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8431     QualType Ty = CE->getCallee()->getType();
8432     if (Ty->isBlockPointerType()) {
8433       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8434       return true;
8435     }
8436   }
8437   return false;
8438 }
8439 
8440 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8441 /// In that case, LHS = cond.
8442 /// C99 6.5.15
8443 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8444                                         ExprResult &RHS, ExprValueKind &VK,
8445                                         ExprObjectKind &OK,
8446                                         SourceLocation QuestionLoc) {
8447 
8448   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8449   if (!LHSResult.isUsable()) return QualType();
8450   LHS = LHSResult;
8451 
8452   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8453   if (!RHSResult.isUsable()) return QualType();
8454   RHS = RHSResult;
8455 
8456   // C++ is sufficiently different to merit its own checker.
8457   if (getLangOpts().CPlusPlus)
8458     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8459 
8460   VK = VK_PRValue;
8461   OK = OK_Ordinary;
8462 
8463   if (Context.isDependenceAllowed() &&
8464       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8465        RHS.get()->isTypeDependent())) {
8466     assert(!getLangOpts().CPlusPlus);
8467     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8468             RHS.get()->containsErrors()) &&
8469            "should only occur in error-recovery path.");
8470     return Context.DependentTy;
8471   }
8472 
8473   // The OpenCL operator with a vector condition is sufficiently
8474   // different to merit its own checker.
8475   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8476       Cond.get()->getType()->isExtVectorType())
8477     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8478 
8479   // First, check the condition.
8480   Cond = UsualUnaryConversions(Cond.get());
8481   if (Cond.isInvalid())
8482     return QualType();
8483   if (checkCondition(*this, Cond.get(), QuestionLoc))
8484     return QualType();
8485 
8486   // Now check the two expressions.
8487   if (LHS.get()->getType()->isVectorType() ||
8488       RHS.get()->getType()->isVectorType())
8489     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8490                                /*AllowBothBool*/true,
8491                                /*AllowBoolConversions*/false);
8492 
8493   QualType ResTy =
8494       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8495   if (LHS.isInvalid() || RHS.isInvalid())
8496     return QualType();
8497 
8498   QualType LHSTy = LHS.get()->getType();
8499   QualType RHSTy = RHS.get()->getType();
8500 
8501   // Diagnose attempts to convert between __ibm128, __float128 and long double
8502   // where such conversions currently can't be handled.
8503   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8504     Diag(QuestionLoc,
8505          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8506       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8507     return QualType();
8508   }
8509 
8510   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8511   // selection operator (?:).
8512   if (getLangOpts().OpenCL &&
8513       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8514     return QualType();
8515   }
8516 
8517   // If both operands have arithmetic type, do the usual arithmetic conversions
8518   // to find a common type: C99 6.5.15p3,5.
8519   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8520     // Disallow invalid arithmetic conversions, such as those between bit-
8521     // precise integers types of different sizes, or between a bit-precise
8522     // integer and another type.
8523     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8524       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8525           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8526           << RHS.get()->getSourceRange();
8527       return QualType();
8528     }
8529 
8530     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8531     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8532 
8533     return ResTy;
8534   }
8535 
8536   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8537   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8538     return LHSTy;
8539   }
8540 
8541   // If both operands are the same structure or union type, the result is that
8542   // type.
8543   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8544     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8545       if (LHSRT->getDecl() == RHSRT->getDecl())
8546         // "If both the operands have structure or union type, the result has
8547         // that type."  This implies that CV qualifiers are dropped.
8548         return LHSTy.getUnqualifiedType();
8549     // FIXME: Type of conditional expression must be complete in C mode.
8550   }
8551 
8552   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8553   // The following || allows only one side to be void (a GCC-ism).
8554   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8555     return checkConditionalVoidType(*this, LHS, RHS);
8556   }
8557 
8558   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8559   // the type of the other operand."
8560   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8561   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8562 
8563   // All objective-c pointer type analysis is done here.
8564   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8565                                                         QuestionLoc);
8566   if (LHS.isInvalid() || RHS.isInvalid())
8567     return QualType();
8568   if (!compositeType.isNull())
8569     return compositeType;
8570 
8571 
8572   // Handle block pointer types.
8573   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8574     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8575                                                      QuestionLoc);
8576 
8577   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8578   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8579     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8580                                                        QuestionLoc);
8581 
8582   // GCC compatibility: soften pointer/integer mismatch.  Note that
8583   // null pointers have been filtered out by this point.
8584   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8585       /*IsIntFirstExpr=*/true))
8586     return RHSTy;
8587   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8588       /*IsIntFirstExpr=*/false))
8589     return LHSTy;
8590 
8591   // Allow ?: operations in which both operands have the same
8592   // built-in sizeless type.
8593   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8594     return LHSTy;
8595 
8596   // Emit a better diagnostic if one of the expressions is a null pointer
8597   // constant and the other is not a pointer type. In this case, the user most
8598   // likely forgot to take the address of the other expression.
8599   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8600     return QualType();
8601 
8602   // Otherwise, the operands are not compatible.
8603   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8604     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8605     << RHS.get()->getSourceRange();
8606   return QualType();
8607 }
8608 
8609 /// FindCompositeObjCPointerType - Helper method to find composite type of
8610 /// two objective-c pointer types of the two input expressions.
8611 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8612                                             SourceLocation QuestionLoc) {
8613   QualType LHSTy = LHS.get()->getType();
8614   QualType RHSTy = RHS.get()->getType();
8615 
8616   // Handle things like Class and struct objc_class*.  Here we case the result
8617   // to the pseudo-builtin, because that will be implicitly cast back to the
8618   // redefinition type if an attempt is made to access its fields.
8619   if (LHSTy->isObjCClassType() &&
8620       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8621     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8622     return LHSTy;
8623   }
8624   if (RHSTy->isObjCClassType() &&
8625       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8626     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8627     return RHSTy;
8628   }
8629   // And the same for struct objc_object* / id
8630   if (LHSTy->isObjCIdType() &&
8631       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8632     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8633     return LHSTy;
8634   }
8635   if (RHSTy->isObjCIdType() &&
8636       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8637     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8638     return RHSTy;
8639   }
8640   // And the same for struct objc_selector* / SEL
8641   if (Context.isObjCSelType(LHSTy) &&
8642       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8643     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8644     return LHSTy;
8645   }
8646   if (Context.isObjCSelType(RHSTy) &&
8647       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8648     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8649     return RHSTy;
8650   }
8651   // Check constraints for Objective-C object pointers types.
8652   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8653 
8654     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8655       // Two identical object pointer types are always compatible.
8656       return LHSTy;
8657     }
8658     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8659     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8660     QualType compositeType = LHSTy;
8661 
8662     // If both operands are interfaces and either operand can be
8663     // assigned to the other, use that type as the composite
8664     // type. This allows
8665     //   xxx ? (A*) a : (B*) b
8666     // where B is a subclass of A.
8667     //
8668     // Additionally, as for assignment, if either type is 'id'
8669     // allow silent coercion. Finally, if the types are
8670     // incompatible then make sure to use 'id' as the composite
8671     // type so the result is acceptable for sending messages to.
8672 
8673     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8674     // It could return the composite type.
8675     if (!(compositeType =
8676           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8677       // Nothing more to do.
8678     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8679       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8680     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8681       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8682     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8683                 RHSOPT->isObjCQualifiedIdType()) &&
8684                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8685                                                          true)) {
8686       // Need to handle "id<xx>" explicitly.
8687       // GCC allows qualified id and any Objective-C type to devolve to
8688       // id. Currently localizing to here until clear this should be
8689       // part of ObjCQualifiedIdTypesAreCompatible.
8690       compositeType = Context.getObjCIdType();
8691     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8692       compositeType = Context.getObjCIdType();
8693     } else {
8694       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8695       << LHSTy << RHSTy
8696       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8697       QualType incompatTy = Context.getObjCIdType();
8698       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8699       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8700       return incompatTy;
8701     }
8702     // The object pointer types are compatible.
8703     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8704     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8705     return compositeType;
8706   }
8707   // Check Objective-C object pointer types and 'void *'
8708   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8709     if (getLangOpts().ObjCAutoRefCount) {
8710       // ARC forbids the implicit conversion of object pointers to 'void *',
8711       // so these types are not compatible.
8712       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8713           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8714       LHS = RHS = true;
8715       return QualType();
8716     }
8717     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8718     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8719     QualType destPointee
8720     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8721     QualType destType = Context.getPointerType(destPointee);
8722     // Add qualifiers if necessary.
8723     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8724     // Promote to void*.
8725     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8726     return destType;
8727   }
8728   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8729     if (getLangOpts().ObjCAutoRefCount) {
8730       // ARC forbids the implicit conversion of object pointers to 'void *',
8731       // so these types are not compatible.
8732       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8733           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8734       LHS = RHS = true;
8735       return QualType();
8736     }
8737     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8738     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8739     QualType destPointee
8740     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8741     QualType destType = Context.getPointerType(destPointee);
8742     // Add qualifiers if necessary.
8743     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8744     // Promote to void*.
8745     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8746     return destType;
8747   }
8748   return QualType();
8749 }
8750 
8751 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8752 /// ParenRange in parentheses.
8753 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8754                                const PartialDiagnostic &Note,
8755                                SourceRange ParenRange) {
8756   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8757   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8758       EndLoc.isValid()) {
8759     Self.Diag(Loc, Note)
8760       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8761       << FixItHint::CreateInsertion(EndLoc, ")");
8762   } else {
8763     // We can't display the parentheses, so just show the bare note.
8764     Self.Diag(Loc, Note) << ParenRange;
8765   }
8766 }
8767 
8768 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8769   return BinaryOperator::isAdditiveOp(Opc) ||
8770          BinaryOperator::isMultiplicativeOp(Opc) ||
8771          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8772   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8773   // not any of the logical operators.  Bitwise-xor is commonly used as a
8774   // logical-xor because there is no logical-xor operator.  The logical
8775   // operators, including uses of xor, have a high false positive rate for
8776   // precedence warnings.
8777 }
8778 
8779 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8780 /// expression, either using a built-in or overloaded operator,
8781 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8782 /// expression.
8783 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8784                                    Expr **RHSExprs) {
8785   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8786   E = E->IgnoreImpCasts();
8787   E = E->IgnoreConversionOperatorSingleStep();
8788   E = E->IgnoreImpCasts();
8789   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8790     E = MTE->getSubExpr();
8791     E = E->IgnoreImpCasts();
8792   }
8793 
8794   // Built-in binary operator.
8795   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8796     if (IsArithmeticOp(OP->getOpcode())) {
8797       *Opcode = OP->getOpcode();
8798       *RHSExprs = OP->getRHS();
8799       return true;
8800     }
8801   }
8802 
8803   // Overloaded operator.
8804   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8805     if (Call->getNumArgs() != 2)
8806       return false;
8807 
8808     // Make sure this is really a binary operator that is safe to pass into
8809     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8810     OverloadedOperatorKind OO = Call->getOperator();
8811     if (OO < OO_Plus || OO > OO_Arrow ||
8812         OO == OO_PlusPlus || OO == OO_MinusMinus)
8813       return false;
8814 
8815     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8816     if (IsArithmeticOp(OpKind)) {
8817       *Opcode = OpKind;
8818       *RHSExprs = Call->getArg(1);
8819       return true;
8820     }
8821   }
8822 
8823   return false;
8824 }
8825 
8826 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8827 /// or is a logical expression such as (x==y) which has int type, but is
8828 /// commonly interpreted as boolean.
8829 static bool ExprLooksBoolean(Expr *E) {
8830   E = E->IgnoreParenImpCasts();
8831 
8832   if (E->getType()->isBooleanType())
8833     return true;
8834   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8835     return OP->isComparisonOp() || OP->isLogicalOp();
8836   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8837     return OP->getOpcode() == UO_LNot;
8838   if (E->getType()->isPointerType())
8839     return true;
8840   // FIXME: What about overloaded operator calls returning "unspecified boolean
8841   // type"s (commonly pointer-to-members)?
8842 
8843   return false;
8844 }
8845 
8846 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8847 /// and binary operator are mixed in a way that suggests the programmer assumed
8848 /// the conditional operator has higher precedence, for example:
8849 /// "int x = a + someBinaryCondition ? 1 : 2".
8850 static void DiagnoseConditionalPrecedence(Sema &Self,
8851                                           SourceLocation OpLoc,
8852                                           Expr *Condition,
8853                                           Expr *LHSExpr,
8854                                           Expr *RHSExpr) {
8855   BinaryOperatorKind CondOpcode;
8856   Expr *CondRHS;
8857 
8858   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8859     return;
8860   if (!ExprLooksBoolean(CondRHS))
8861     return;
8862 
8863   // The condition is an arithmetic binary expression, with a right-
8864   // hand side that looks boolean, so warn.
8865 
8866   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8867                         ? diag::warn_precedence_bitwise_conditional
8868                         : diag::warn_precedence_conditional;
8869 
8870   Self.Diag(OpLoc, DiagID)
8871       << Condition->getSourceRange()
8872       << BinaryOperator::getOpcodeStr(CondOpcode);
8873 
8874   SuggestParentheses(
8875       Self, OpLoc,
8876       Self.PDiag(diag::note_precedence_silence)
8877           << BinaryOperator::getOpcodeStr(CondOpcode),
8878       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8879 
8880   SuggestParentheses(Self, OpLoc,
8881                      Self.PDiag(diag::note_precedence_conditional_first),
8882                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8883 }
8884 
8885 /// Compute the nullability of a conditional expression.
8886 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8887                                               QualType LHSTy, QualType RHSTy,
8888                                               ASTContext &Ctx) {
8889   if (!ResTy->isAnyPointerType())
8890     return ResTy;
8891 
8892   auto GetNullability = [&Ctx](QualType Ty) {
8893     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8894     if (Kind) {
8895       // For our purposes, treat _Nullable_result as _Nullable.
8896       if (*Kind == NullabilityKind::NullableResult)
8897         return NullabilityKind::Nullable;
8898       return *Kind;
8899     }
8900     return NullabilityKind::Unspecified;
8901   };
8902 
8903   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8904   NullabilityKind MergedKind;
8905 
8906   // Compute nullability of a binary conditional expression.
8907   if (IsBin) {
8908     if (LHSKind == NullabilityKind::NonNull)
8909       MergedKind = NullabilityKind::NonNull;
8910     else
8911       MergedKind = RHSKind;
8912   // Compute nullability of a normal conditional expression.
8913   } else {
8914     if (LHSKind == NullabilityKind::Nullable ||
8915         RHSKind == NullabilityKind::Nullable)
8916       MergedKind = NullabilityKind::Nullable;
8917     else if (LHSKind == NullabilityKind::NonNull)
8918       MergedKind = RHSKind;
8919     else if (RHSKind == NullabilityKind::NonNull)
8920       MergedKind = LHSKind;
8921     else
8922       MergedKind = NullabilityKind::Unspecified;
8923   }
8924 
8925   // Return if ResTy already has the correct nullability.
8926   if (GetNullability(ResTy) == MergedKind)
8927     return ResTy;
8928 
8929   // Strip all nullability from ResTy.
8930   while (ResTy->getNullability(Ctx))
8931     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8932 
8933   // Create a new AttributedType with the new nullability kind.
8934   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8935   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8936 }
8937 
8938 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8939 /// in the case of a the GNU conditional expr extension.
8940 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8941                                     SourceLocation ColonLoc,
8942                                     Expr *CondExpr, Expr *LHSExpr,
8943                                     Expr *RHSExpr) {
8944   if (!Context.isDependenceAllowed()) {
8945     // C cannot handle TypoExpr nodes in the condition because it
8946     // doesn't handle dependent types properly, so make sure any TypoExprs have
8947     // been dealt with before checking the operands.
8948     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8949     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8950     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8951 
8952     if (!CondResult.isUsable())
8953       return ExprError();
8954 
8955     if (LHSExpr) {
8956       if (!LHSResult.isUsable())
8957         return ExprError();
8958     }
8959 
8960     if (!RHSResult.isUsable())
8961       return ExprError();
8962 
8963     CondExpr = CondResult.get();
8964     LHSExpr = LHSResult.get();
8965     RHSExpr = RHSResult.get();
8966   }
8967 
8968   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8969   // was the condition.
8970   OpaqueValueExpr *opaqueValue = nullptr;
8971   Expr *commonExpr = nullptr;
8972   if (!LHSExpr) {
8973     commonExpr = CondExpr;
8974     // Lower out placeholder types first.  This is important so that we don't
8975     // try to capture a placeholder. This happens in few cases in C++; such
8976     // as Objective-C++'s dictionary subscripting syntax.
8977     if (commonExpr->hasPlaceholderType()) {
8978       ExprResult result = CheckPlaceholderExpr(commonExpr);
8979       if (!result.isUsable()) return ExprError();
8980       commonExpr = result.get();
8981     }
8982     // We usually want to apply unary conversions *before* saving, except
8983     // in the special case of a C++ l-value conditional.
8984     if (!(getLangOpts().CPlusPlus
8985           && !commonExpr->isTypeDependent()
8986           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8987           && commonExpr->isGLValue()
8988           && commonExpr->isOrdinaryOrBitFieldObject()
8989           && RHSExpr->isOrdinaryOrBitFieldObject()
8990           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8991       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8992       if (commonRes.isInvalid())
8993         return ExprError();
8994       commonExpr = commonRes.get();
8995     }
8996 
8997     // If the common expression is a class or array prvalue, materialize it
8998     // so that we can safely refer to it multiple times.
8999     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9000                                     commonExpr->getType()->isArrayType())) {
9001       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9002       if (MatExpr.isInvalid())
9003         return ExprError();
9004       commonExpr = MatExpr.get();
9005     }
9006 
9007     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9008                                                 commonExpr->getType(),
9009                                                 commonExpr->getValueKind(),
9010                                                 commonExpr->getObjectKind(),
9011                                                 commonExpr);
9012     LHSExpr = CondExpr = opaqueValue;
9013   }
9014 
9015   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9016   ExprValueKind VK = VK_PRValue;
9017   ExprObjectKind OK = OK_Ordinary;
9018   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9019   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9020                                              VK, OK, QuestionLoc);
9021   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9022       RHS.isInvalid())
9023     return ExprError();
9024 
9025   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9026                                 RHS.get());
9027 
9028   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9029 
9030   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9031                                          Context);
9032 
9033   if (!commonExpr)
9034     return new (Context)
9035         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9036                             RHS.get(), result, VK, OK);
9037 
9038   return new (Context) BinaryConditionalOperator(
9039       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9040       ColonLoc, result, VK, OK);
9041 }
9042 
9043 // Check if we have a conversion between incompatible cmse function pointer
9044 // types, that is, a conversion between a function pointer with the
9045 // cmse_nonsecure_call attribute and one without.
9046 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9047                                           QualType ToType) {
9048   if (const auto *ToFn =
9049           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9050     if (const auto *FromFn =
9051             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9052       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9053       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9054 
9055       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9056     }
9057   }
9058   return false;
9059 }
9060 
9061 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9062 // being closely modeled after the C99 spec:-). The odd characteristic of this
9063 // routine is it effectively iqnores the qualifiers on the top level pointee.
9064 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9065 // FIXME: add a couple examples in this comment.
9066 static Sema::AssignConvertType
9067 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9068   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9069   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9070 
9071   // get the "pointed to" type (ignoring qualifiers at the top level)
9072   const Type *lhptee, *rhptee;
9073   Qualifiers lhq, rhq;
9074   std::tie(lhptee, lhq) =
9075       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9076   std::tie(rhptee, rhq) =
9077       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9078 
9079   Sema::AssignConvertType ConvTy = Sema::Compatible;
9080 
9081   // C99 6.5.16.1p1: This following citation is common to constraints
9082   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9083   // qualifiers of the type *pointed to* by the right;
9084 
9085   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9086   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9087       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9088     // Ignore lifetime for further calculation.
9089     lhq.removeObjCLifetime();
9090     rhq.removeObjCLifetime();
9091   }
9092 
9093   if (!lhq.compatiblyIncludes(rhq)) {
9094     // Treat address-space mismatches as fatal.
9095     if (!lhq.isAddressSpaceSupersetOf(rhq))
9096       return Sema::IncompatiblePointerDiscardsQualifiers;
9097 
9098     // It's okay to add or remove GC or lifetime qualifiers when converting to
9099     // and from void*.
9100     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9101                         .compatiblyIncludes(
9102                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9103              && (lhptee->isVoidType() || rhptee->isVoidType()))
9104       ; // keep old
9105 
9106     // Treat lifetime mismatches as fatal.
9107     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9108       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9109 
9110     // For GCC/MS compatibility, other qualifier mismatches are treated
9111     // as still compatible in C.
9112     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9113   }
9114 
9115   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9116   // incomplete type and the other is a pointer to a qualified or unqualified
9117   // version of void...
9118   if (lhptee->isVoidType()) {
9119     if (rhptee->isIncompleteOrObjectType())
9120       return ConvTy;
9121 
9122     // As an extension, we allow cast to/from void* to function pointer.
9123     assert(rhptee->isFunctionType());
9124     return Sema::FunctionVoidPointer;
9125   }
9126 
9127   if (rhptee->isVoidType()) {
9128     if (lhptee->isIncompleteOrObjectType())
9129       return ConvTy;
9130 
9131     // As an extension, we allow cast to/from void* to function pointer.
9132     assert(lhptee->isFunctionType());
9133     return Sema::FunctionVoidPointer;
9134   }
9135 
9136   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9137   // unqualified versions of compatible types, ...
9138   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9139   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9140     // Check if the pointee types are compatible ignoring the sign.
9141     // We explicitly check for char so that we catch "char" vs
9142     // "unsigned char" on systems where "char" is unsigned.
9143     if (lhptee->isCharType())
9144       ltrans = S.Context.UnsignedCharTy;
9145     else if (lhptee->hasSignedIntegerRepresentation())
9146       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9147 
9148     if (rhptee->isCharType())
9149       rtrans = S.Context.UnsignedCharTy;
9150     else if (rhptee->hasSignedIntegerRepresentation())
9151       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9152 
9153     if (ltrans == rtrans) {
9154       // Types are compatible ignoring the sign. Qualifier incompatibility
9155       // takes priority over sign incompatibility because the sign
9156       // warning can be disabled.
9157       if (ConvTy != Sema::Compatible)
9158         return ConvTy;
9159 
9160       return Sema::IncompatiblePointerSign;
9161     }
9162 
9163     // If we are a multi-level pointer, it's possible that our issue is simply
9164     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9165     // the eventual target type is the same and the pointers have the same
9166     // level of indirection, this must be the issue.
9167     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9168       do {
9169         std::tie(lhptee, lhq) =
9170           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9171         std::tie(rhptee, rhq) =
9172           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9173 
9174         // Inconsistent address spaces at this point is invalid, even if the
9175         // address spaces would be compatible.
9176         // FIXME: This doesn't catch address space mismatches for pointers of
9177         // different nesting levels, like:
9178         //   __local int *** a;
9179         //   int ** b = a;
9180         // It's not clear how to actually determine when such pointers are
9181         // invalidly incompatible.
9182         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9183           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9184 
9185       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9186 
9187       if (lhptee == rhptee)
9188         return Sema::IncompatibleNestedPointerQualifiers;
9189     }
9190 
9191     // General pointer incompatibility takes priority over qualifiers.
9192     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9193       return Sema::IncompatibleFunctionPointer;
9194     return Sema::IncompatiblePointer;
9195   }
9196   if (!S.getLangOpts().CPlusPlus &&
9197       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9198     return Sema::IncompatibleFunctionPointer;
9199   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9200     return Sema::IncompatibleFunctionPointer;
9201   return ConvTy;
9202 }
9203 
9204 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9205 /// block pointer types are compatible or whether a block and normal pointer
9206 /// are compatible. It is more restrict than comparing two function pointer
9207 // types.
9208 static Sema::AssignConvertType
9209 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9210                                     QualType RHSType) {
9211   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9212   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9213 
9214   QualType lhptee, rhptee;
9215 
9216   // get the "pointed to" type (ignoring qualifiers at the top level)
9217   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9218   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9219 
9220   // In C++, the types have to match exactly.
9221   if (S.getLangOpts().CPlusPlus)
9222     return Sema::IncompatibleBlockPointer;
9223 
9224   Sema::AssignConvertType ConvTy = Sema::Compatible;
9225 
9226   // For blocks we enforce that qualifiers are identical.
9227   Qualifiers LQuals = lhptee.getLocalQualifiers();
9228   Qualifiers RQuals = rhptee.getLocalQualifiers();
9229   if (S.getLangOpts().OpenCL) {
9230     LQuals.removeAddressSpace();
9231     RQuals.removeAddressSpace();
9232   }
9233   if (LQuals != RQuals)
9234     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9235 
9236   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9237   // assignment.
9238   // The current behavior is similar to C++ lambdas. A block might be
9239   // assigned to a variable iff its return type and parameters are compatible
9240   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9241   // an assignment. Presumably it should behave in way that a function pointer
9242   // assignment does in C, so for each parameter and return type:
9243   //  * CVR and address space of LHS should be a superset of CVR and address
9244   //  space of RHS.
9245   //  * unqualified types should be compatible.
9246   if (S.getLangOpts().OpenCL) {
9247     if (!S.Context.typesAreBlockPointerCompatible(
9248             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9249             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9250       return Sema::IncompatibleBlockPointer;
9251   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9252     return Sema::IncompatibleBlockPointer;
9253 
9254   return ConvTy;
9255 }
9256 
9257 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9258 /// for assignment compatibility.
9259 static Sema::AssignConvertType
9260 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9261                                    QualType RHSType) {
9262   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9263   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9264 
9265   if (LHSType->isObjCBuiltinType()) {
9266     // Class is not compatible with ObjC object pointers.
9267     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9268         !RHSType->isObjCQualifiedClassType())
9269       return Sema::IncompatiblePointer;
9270     return Sema::Compatible;
9271   }
9272   if (RHSType->isObjCBuiltinType()) {
9273     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9274         !LHSType->isObjCQualifiedClassType())
9275       return Sema::IncompatiblePointer;
9276     return Sema::Compatible;
9277   }
9278   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9279   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9280 
9281   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9282       // make an exception for id<P>
9283       !LHSType->isObjCQualifiedIdType())
9284     return Sema::CompatiblePointerDiscardsQualifiers;
9285 
9286   if (S.Context.typesAreCompatible(LHSType, RHSType))
9287     return Sema::Compatible;
9288   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9289     return Sema::IncompatibleObjCQualifiedId;
9290   return Sema::IncompatiblePointer;
9291 }
9292 
9293 Sema::AssignConvertType
9294 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9295                                  QualType LHSType, QualType RHSType) {
9296   // Fake up an opaque expression.  We don't actually care about what
9297   // cast operations are required, so if CheckAssignmentConstraints
9298   // adds casts to this they'll be wasted, but fortunately that doesn't
9299   // usually happen on valid code.
9300   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9301   ExprResult RHSPtr = &RHSExpr;
9302   CastKind K;
9303 
9304   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9305 }
9306 
9307 /// This helper function returns true if QT is a vector type that has element
9308 /// type ElementType.
9309 static bool isVector(QualType QT, QualType ElementType) {
9310   if (const VectorType *VT = QT->getAs<VectorType>())
9311     return VT->getElementType().getCanonicalType() == ElementType;
9312   return false;
9313 }
9314 
9315 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9316 /// has code to accommodate several GCC extensions when type checking
9317 /// pointers. Here are some objectionable examples that GCC considers warnings:
9318 ///
9319 ///  int a, *pint;
9320 ///  short *pshort;
9321 ///  struct foo *pfoo;
9322 ///
9323 ///  pint = pshort; // warning: assignment from incompatible pointer type
9324 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9325 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9326 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9327 ///
9328 /// As a result, the code for dealing with pointers is more complex than the
9329 /// C99 spec dictates.
9330 ///
9331 /// Sets 'Kind' for any result kind except Incompatible.
9332 Sema::AssignConvertType
9333 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9334                                  CastKind &Kind, bool ConvertRHS) {
9335   QualType RHSType = RHS.get()->getType();
9336   QualType OrigLHSType = LHSType;
9337 
9338   // Get canonical types.  We're not formatting these types, just comparing
9339   // them.
9340   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9341   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9342 
9343   // Common case: no conversion required.
9344   if (LHSType == RHSType) {
9345     Kind = CK_NoOp;
9346     return Compatible;
9347   }
9348 
9349   // If we have an atomic type, try a non-atomic assignment, then just add an
9350   // atomic qualification step.
9351   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9352     Sema::AssignConvertType result =
9353       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9354     if (result != Compatible)
9355       return result;
9356     if (Kind != CK_NoOp && ConvertRHS)
9357       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9358     Kind = CK_NonAtomicToAtomic;
9359     return Compatible;
9360   }
9361 
9362   // If the left-hand side is a reference type, then we are in a
9363   // (rare!) case where we've allowed the use of references in C,
9364   // e.g., as a parameter type in a built-in function. In this case,
9365   // just make sure that the type referenced is compatible with the
9366   // right-hand side type. The caller is responsible for adjusting
9367   // LHSType so that the resulting expression does not have reference
9368   // type.
9369   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9370     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9371       Kind = CK_LValueBitCast;
9372       return Compatible;
9373     }
9374     return Incompatible;
9375   }
9376 
9377   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9378   // to the same ExtVector type.
9379   if (LHSType->isExtVectorType()) {
9380     if (RHSType->isExtVectorType())
9381       return Incompatible;
9382     if (RHSType->isArithmeticType()) {
9383       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9384       if (ConvertRHS)
9385         RHS = prepareVectorSplat(LHSType, RHS.get());
9386       Kind = CK_VectorSplat;
9387       return Compatible;
9388     }
9389   }
9390 
9391   // Conversions to or from vector type.
9392   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9393     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9394       // Allow assignments of an AltiVec vector type to an equivalent GCC
9395       // vector type and vice versa
9396       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9397         Kind = CK_BitCast;
9398         return Compatible;
9399       }
9400 
9401       // If we are allowing lax vector conversions, and LHS and RHS are both
9402       // vectors, the total size only needs to be the same. This is a bitcast;
9403       // no bits are changed but the result type is different.
9404       if (isLaxVectorConversion(RHSType, LHSType)) {
9405         Kind = CK_BitCast;
9406         return IncompatibleVectors;
9407       }
9408     }
9409 
9410     // When the RHS comes from another lax conversion (e.g. binops between
9411     // scalars and vectors) the result is canonicalized as a vector. When the
9412     // LHS is also a vector, the lax is allowed by the condition above. Handle
9413     // the case where LHS is a scalar.
9414     if (LHSType->isScalarType()) {
9415       const VectorType *VecType = RHSType->getAs<VectorType>();
9416       if (VecType && VecType->getNumElements() == 1 &&
9417           isLaxVectorConversion(RHSType, LHSType)) {
9418         ExprResult *VecExpr = &RHS;
9419         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9420         Kind = CK_BitCast;
9421         return Compatible;
9422       }
9423     }
9424 
9425     // Allow assignments between fixed-length and sizeless SVE vectors.
9426     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9427         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9428       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9429           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9430         Kind = CK_BitCast;
9431         return Compatible;
9432       }
9433 
9434     return Incompatible;
9435   }
9436 
9437   // Diagnose attempts to convert between __ibm128, __float128 and long double
9438   // where such conversions currently can't be handled.
9439   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9440     return Incompatible;
9441 
9442   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9443   // discards the imaginary part.
9444   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9445       !LHSType->getAs<ComplexType>())
9446     return Incompatible;
9447 
9448   // Arithmetic conversions.
9449   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9450       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9451     if (ConvertRHS)
9452       Kind = PrepareScalarCast(RHS, LHSType);
9453     return Compatible;
9454   }
9455 
9456   // Conversions to normal pointers.
9457   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9458     // U* -> T*
9459     if (isa<PointerType>(RHSType)) {
9460       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9461       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9462       if (AddrSpaceL != AddrSpaceR)
9463         Kind = CK_AddressSpaceConversion;
9464       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9465         Kind = CK_NoOp;
9466       else
9467         Kind = CK_BitCast;
9468       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9469     }
9470 
9471     // int -> T*
9472     if (RHSType->isIntegerType()) {
9473       Kind = CK_IntegralToPointer; // FIXME: null?
9474       return IntToPointer;
9475     }
9476 
9477     // C pointers are not compatible with ObjC object pointers,
9478     // with two exceptions:
9479     if (isa<ObjCObjectPointerType>(RHSType)) {
9480       //  - conversions to void*
9481       if (LHSPointer->getPointeeType()->isVoidType()) {
9482         Kind = CK_BitCast;
9483         return Compatible;
9484       }
9485 
9486       //  - conversions from 'Class' to the redefinition type
9487       if (RHSType->isObjCClassType() &&
9488           Context.hasSameType(LHSType,
9489                               Context.getObjCClassRedefinitionType())) {
9490         Kind = CK_BitCast;
9491         return Compatible;
9492       }
9493 
9494       Kind = CK_BitCast;
9495       return IncompatiblePointer;
9496     }
9497 
9498     // U^ -> void*
9499     if (RHSType->getAs<BlockPointerType>()) {
9500       if (LHSPointer->getPointeeType()->isVoidType()) {
9501         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9502         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9503                                 ->getPointeeType()
9504                                 .getAddressSpace();
9505         Kind =
9506             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9507         return Compatible;
9508       }
9509     }
9510 
9511     return Incompatible;
9512   }
9513 
9514   // Conversions to block pointers.
9515   if (isa<BlockPointerType>(LHSType)) {
9516     // U^ -> T^
9517     if (RHSType->isBlockPointerType()) {
9518       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9519                               ->getPointeeType()
9520                               .getAddressSpace();
9521       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9522                               ->getPointeeType()
9523                               .getAddressSpace();
9524       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9525       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9526     }
9527 
9528     // int or null -> T^
9529     if (RHSType->isIntegerType()) {
9530       Kind = CK_IntegralToPointer; // FIXME: null
9531       return IntToBlockPointer;
9532     }
9533 
9534     // id -> T^
9535     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9536       Kind = CK_AnyPointerToBlockPointerCast;
9537       return Compatible;
9538     }
9539 
9540     // void* -> T^
9541     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9542       if (RHSPT->getPointeeType()->isVoidType()) {
9543         Kind = CK_AnyPointerToBlockPointerCast;
9544         return Compatible;
9545       }
9546 
9547     return Incompatible;
9548   }
9549 
9550   // Conversions to Objective-C pointers.
9551   if (isa<ObjCObjectPointerType>(LHSType)) {
9552     // A* -> B*
9553     if (RHSType->isObjCObjectPointerType()) {
9554       Kind = CK_BitCast;
9555       Sema::AssignConvertType result =
9556         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9557       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9558           result == Compatible &&
9559           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9560         result = IncompatibleObjCWeakRef;
9561       return result;
9562     }
9563 
9564     // int or null -> A*
9565     if (RHSType->isIntegerType()) {
9566       Kind = CK_IntegralToPointer; // FIXME: null
9567       return IntToPointer;
9568     }
9569 
9570     // In general, C pointers are not compatible with ObjC object pointers,
9571     // with two exceptions:
9572     if (isa<PointerType>(RHSType)) {
9573       Kind = CK_CPointerToObjCPointerCast;
9574 
9575       //  - conversions from 'void*'
9576       if (RHSType->isVoidPointerType()) {
9577         return Compatible;
9578       }
9579 
9580       //  - conversions to 'Class' from its redefinition type
9581       if (LHSType->isObjCClassType() &&
9582           Context.hasSameType(RHSType,
9583                               Context.getObjCClassRedefinitionType())) {
9584         return Compatible;
9585       }
9586 
9587       return IncompatiblePointer;
9588     }
9589 
9590     // Only under strict condition T^ is compatible with an Objective-C pointer.
9591     if (RHSType->isBlockPointerType() &&
9592         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9593       if (ConvertRHS)
9594         maybeExtendBlockObject(RHS);
9595       Kind = CK_BlockPointerToObjCPointerCast;
9596       return Compatible;
9597     }
9598 
9599     return Incompatible;
9600   }
9601 
9602   // Conversions from pointers that are not covered by the above.
9603   if (isa<PointerType>(RHSType)) {
9604     // T* -> _Bool
9605     if (LHSType == Context.BoolTy) {
9606       Kind = CK_PointerToBoolean;
9607       return Compatible;
9608     }
9609 
9610     // T* -> int
9611     if (LHSType->isIntegerType()) {
9612       Kind = CK_PointerToIntegral;
9613       return PointerToInt;
9614     }
9615 
9616     return Incompatible;
9617   }
9618 
9619   // Conversions from Objective-C pointers that are not covered by the above.
9620   if (isa<ObjCObjectPointerType>(RHSType)) {
9621     // T* -> _Bool
9622     if (LHSType == Context.BoolTy) {
9623       Kind = CK_PointerToBoolean;
9624       return Compatible;
9625     }
9626 
9627     // T* -> int
9628     if (LHSType->isIntegerType()) {
9629       Kind = CK_PointerToIntegral;
9630       return PointerToInt;
9631     }
9632 
9633     return Incompatible;
9634   }
9635 
9636   // struct A -> struct B
9637   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9638     if (Context.typesAreCompatible(LHSType, RHSType)) {
9639       Kind = CK_NoOp;
9640       return Compatible;
9641     }
9642   }
9643 
9644   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9645     Kind = CK_IntToOCLSampler;
9646     return Compatible;
9647   }
9648 
9649   return Incompatible;
9650 }
9651 
9652 /// Constructs a transparent union from an expression that is
9653 /// used to initialize the transparent union.
9654 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9655                                       ExprResult &EResult, QualType UnionType,
9656                                       FieldDecl *Field) {
9657   // Build an initializer list that designates the appropriate member
9658   // of the transparent union.
9659   Expr *E = EResult.get();
9660   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9661                                                    E, SourceLocation());
9662   Initializer->setType(UnionType);
9663   Initializer->setInitializedFieldInUnion(Field);
9664 
9665   // Build a compound literal constructing a value of the transparent
9666   // union type from this initializer list.
9667   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9668   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9669                                         VK_PRValue, Initializer, false);
9670 }
9671 
9672 Sema::AssignConvertType
9673 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9674                                                ExprResult &RHS) {
9675   QualType RHSType = RHS.get()->getType();
9676 
9677   // If the ArgType is a Union type, we want to handle a potential
9678   // transparent_union GCC extension.
9679   const RecordType *UT = ArgType->getAsUnionType();
9680   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9681     return Incompatible;
9682 
9683   // The field to initialize within the transparent union.
9684   RecordDecl *UD = UT->getDecl();
9685   FieldDecl *InitField = nullptr;
9686   // It's compatible if the expression matches any of the fields.
9687   for (auto *it : UD->fields()) {
9688     if (it->getType()->isPointerType()) {
9689       // If the transparent union contains a pointer type, we allow:
9690       // 1) void pointer
9691       // 2) null pointer constant
9692       if (RHSType->isPointerType())
9693         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9694           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9695           InitField = it;
9696           break;
9697         }
9698 
9699       if (RHS.get()->isNullPointerConstant(Context,
9700                                            Expr::NPC_ValueDependentIsNull)) {
9701         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9702                                 CK_NullToPointer);
9703         InitField = it;
9704         break;
9705       }
9706     }
9707 
9708     CastKind Kind;
9709     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9710           == Compatible) {
9711       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9712       InitField = it;
9713       break;
9714     }
9715   }
9716 
9717   if (!InitField)
9718     return Incompatible;
9719 
9720   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9721   return Compatible;
9722 }
9723 
9724 Sema::AssignConvertType
9725 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9726                                        bool Diagnose,
9727                                        bool DiagnoseCFAudited,
9728                                        bool ConvertRHS) {
9729   // We need to be able to tell the caller whether we diagnosed a problem, if
9730   // they ask us to issue diagnostics.
9731   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9732 
9733   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9734   // we can't avoid *all* modifications at the moment, so we need some somewhere
9735   // to put the updated value.
9736   ExprResult LocalRHS = CallerRHS;
9737   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9738 
9739   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9740     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9741       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9742           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9743         Diag(RHS.get()->getExprLoc(),
9744              diag::warn_noderef_to_dereferenceable_pointer)
9745             << RHS.get()->getSourceRange();
9746       }
9747     }
9748   }
9749 
9750   if (getLangOpts().CPlusPlus) {
9751     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9752       // C++ 5.17p3: If the left operand is not of class type, the
9753       // expression is implicitly converted (C++ 4) to the
9754       // cv-unqualified type of the left operand.
9755       QualType RHSType = RHS.get()->getType();
9756       if (Diagnose) {
9757         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9758                                         AA_Assigning);
9759       } else {
9760         ImplicitConversionSequence ICS =
9761             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9762                                   /*SuppressUserConversions=*/false,
9763                                   AllowedExplicit::None,
9764                                   /*InOverloadResolution=*/false,
9765                                   /*CStyle=*/false,
9766                                   /*AllowObjCWritebackConversion=*/false);
9767         if (ICS.isFailure())
9768           return Incompatible;
9769         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9770                                         ICS, AA_Assigning);
9771       }
9772       if (RHS.isInvalid())
9773         return Incompatible;
9774       Sema::AssignConvertType result = Compatible;
9775       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9776           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9777         result = IncompatibleObjCWeakRef;
9778       return result;
9779     }
9780 
9781     // FIXME: Currently, we fall through and treat C++ classes like C
9782     // structures.
9783     // FIXME: We also fall through for atomics; not sure what should
9784     // happen there, though.
9785   } else if (RHS.get()->getType() == Context.OverloadTy) {
9786     // As a set of extensions to C, we support overloading on functions. These
9787     // functions need to be resolved here.
9788     DeclAccessPair DAP;
9789     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9790             RHS.get(), LHSType, /*Complain=*/false, DAP))
9791       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9792     else
9793       return Incompatible;
9794   }
9795 
9796   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9797   // a null pointer constant.
9798   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9799        LHSType->isBlockPointerType()) &&
9800       RHS.get()->isNullPointerConstant(Context,
9801                                        Expr::NPC_ValueDependentIsNull)) {
9802     if (Diagnose || ConvertRHS) {
9803       CastKind Kind;
9804       CXXCastPath Path;
9805       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9806                              /*IgnoreBaseAccess=*/false, Diagnose);
9807       if (ConvertRHS)
9808         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9809     }
9810     return Compatible;
9811   }
9812 
9813   // OpenCL queue_t type assignment.
9814   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9815                                  Context, Expr::NPC_ValueDependentIsNull)) {
9816     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9817     return Compatible;
9818   }
9819 
9820   // This check seems unnatural, however it is necessary to ensure the proper
9821   // conversion of functions/arrays. If the conversion were done for all
9822   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9823   // expressions that suppress this implicit conversion (&, sizeof).
9824   //
9825   // Suppress this for references: C++ 8.5.3p5.
9826   if (!LHSType->isReferenceType()) {
9827     // FIXME: We potentially allocate here even if ConvertRHS is false.
9828     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9829     if (RHS.isInvalid())
9830       return Incompatible;
9831   }
9832   CastKind Kind;
9833   Sema::AssignConvertType result =
9834     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9835 
9836   // C99 6.5.16.1p2: The value of the right operand is converted to the
9837   // type of the assignment expression.
9838   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9839   // so that we can use references in built-in functions even in C.
9840   // The getNonReferenceType() call makes sure that the resulting expression
9841   // does not have reference type.
9842   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9843     QualType Ty = LHSType.getNonLValueExprType(Context);
9844     Expr *E = RHS.get();
9845 
9846     // Check for various Objective-C errors. If we are not reporting
9847     // diagnostics and just checking for errors, e.g., during overload
9848     // resolution, return Incompatible to indicate the failure.
9849     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9850         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9851                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9852       if (!Diagnose)
9853         return Incompatible;
9854     }
9855     if (getLangOpts().ObjC &&
9856         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9857                                            E->getType(), E, Diagnose) ||
9858          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9859       if (!Diagnose)
9860         return Incompatible;
9861       // Replace the expression with a corrected version and continue so we
9862       // can find further errors.
9863       RHS = E;
9864       return Compatible;
9865     }
9866 
9867     if (ConvertRHS)
9868       RHS = ImpCastExprToType(E, Ty, Kind);
9869   }
9870 
9871   return result;
9872 }
9873 
9874 namespace {
9875 /// The original operand to an operator, prior to the application of the usual
9876 /// arithmetic conversions and converting the arguments of a builtin operator
9877 /// candidate.
9878 struct OriginalOperand {
9879   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9880     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9881       Op = MTE->getSubExpr();
9882     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9883       Op = BTE->getSubExpr();
9884     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9885       Orig = ICE->getSubExprAsWritten();
9886       Conversion = ICE->getConversionFunction();
9887     }
9888   }
9889 
9890   QualType getType() const { return Orig->getType(); }
9891 
9892   Expr *Orig;
9893   NamedDecl *Conversion;
9894 };
9895 }
9896 
9897 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9898                                ExprResult &RHS) {
9899   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9900 
9901   Diag(Loc, diag::err_typecheck_invalid_operands)
9902     << OrigLHS.getType() << OrigRHS.getType()
9903     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9904 
9905   // If a user-defined conversion was applied to either of the operands prior
9906   // to applying the built-in operator rules, tell the user about it.
9907   if (OrigLHS.Conversion) {
9908     Diag(OrigLHS.Conversion->getLocation(),
9909          diag::note_typecheck_invalid_operands_converted)
9910       << 0 << LHS.get()->getType();
9911   }
9912   if (OrigRHS.Conversion) {
9913     Diag(OrigRHS.Conversion->getLocation(),
9914          diag::note_typecheck_invalid_operands_converted)
9915       << 1 << RHS.get()->getType();
9916   }
9917 
9918   return QualType();
9919 }
9920 
9921 // Diagnose cases where a scalar was implicitly converted to a vector and
9922 // diagnose the underlying types. Otherwise, diagnose the error
9923 // as invalid vector logical operands for non-C++ cases.
9924 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9925                                             ExprResult &RHS) {
9926   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9927   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9928 
9929   bool LHSNatVec = LHSType->isVectorType();
9930   bool RHSNatVec = RHSType->isVectorType();
9931 
9932   if (!(LHSNatVec && RHSNatVec)) {
9933     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9934     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9935     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9936         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9937         << Vector->getSourceRange();
9938     return QualType();
9939   }
9940 
9941   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9942       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9943       << RHS.get()->getSourceRange();
9944 
9945   return QualType();
9946 }
9947 
9948 /// Try to convert a value of non-vector type to a vector type by converting
9949 /// the type to the element type of the vector and then performing a splat.
9950 /// If the language is OpenCL, we only use conversions that promote scalar
9951 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9952 /// for float->int.
9953 ///
9954 /// OpenCL V2.0 6.2.6.p2:
9955 /// An error shall occur if any scalar operand type has greater rank
9956 /// than the type of the vector element.
9957 ///
9958 /// \param scalar - if non-null, actually perform the conversions
9959 /// \return true if the operation fails (but without diagnosing the failure)
9960 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9961                                      QualType scalarTy,
9962                                      QualType vectorEltTy,
9963                                      QualType vectorTy,
9964                                      unsigned &DiagID) {
9965   // The conversion to apply to the scalar before splatting it,
9966   // if necessary.
9967   CastKind scalarCast = CK_NoOp;
9968 
9969   if (vectorEltTy->isIntegralType(S.Context)) {
9970     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9971         (scalarTy->isIntegerType() &&
9972          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9973       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9974       return true;
9975     }
9976     if (!scalarTy->isIntegralType(S.Context))
9977       return true;
9978     scalarCast = CK_IntegralCast;
9979   } else if (vectorEltTy->isRealFloatingType()) {
9980     if (scalarTy->isRealFloatingType()) {
9981       if (S.getLangOpts().OpenCL &&
9982           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9983         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9984         return true;
9985       }
9986       scalarCast = CK_FloatingCast;
9987     }
9988     else if (scalarTy->isIntegralType(S.Context))
9989       scalarCast = CK_IntegralToFloating;
9990     else
9991       return true;
9992   } else {
9993     return true;
9994   }
9995 
9996   // Adjust scalar if desired.
9997   if (scalar) {
9998     if (scalarCast != CK_NoOp)
9999       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10000     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10001   }
10002   return false;
10003 }
10004 
10005 /// Convert vector E to a vector with the same number of elements but different
10006 /// element type.
10007 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10008   const auto *VecTy = E->getType()->getAs<VectorType>();
10009   assert(VecTy && "Expression E must be a vector");
10010   QualType NewVecTy = S.Context.getVectorType(ElementType,
10011                                               VecTy->getNumElements(),
10012                                               VecTy->getVectorKind());
10013 
10014   // Look through the implicit cast. Return the subexpression if its type is
10015   // NewVecTy.
10016   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10017     if (ICE->getSubExpr()->getType() == NewVecTy)
10018       return ICE->getSubExpr();
10019 
10020   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10021   return S.ImpCastExprToType(E, NewVecTy, Cast);
10022 }
10023 
10024 /// Test if a (constant) integer Int can be casted to another integer type
10025 /// IntTy without losing precision.
10026 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10027                                       QualType OtherIntTy) {
10028   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10029 
10030   // Reject cases where the value of the Int is unknown as that would
10031   // possibly cause truncation, but accept cases where the scalar can be
10032   // demoted without loss of precision.
10033   Expr::EvalResult EVResult;
10034   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10035   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10036   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10037   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10038 
10039   if (CstInt) {
10040     // If the scalar is constant and is of a higher order and has more active
10041     // bits that the vector element type, reject it.
10042     llvm::APSInt Result = EVResult.Val.getInt();
10043     unsigned NumBits = IntSigned
10044                            ? (Result.isNegative() ? Result.getMinSignedBits()
10045                                                   : Result.getActiveBits())
10046                            : Result.getActiveBits();
10047     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10048       return true;
10049 
10050     // If the signedness of the scalar type and the vector element type
10051     // differs and the number of bits is greater than that of the vector
10052     // element reject it.
10053     return (IntSigned != OtherIntSigned &&
10054             NumBits > S.Context.getIntWidth(OtherIntTy));
10055   }
10056 
10057   // Reject cases where the value of the scalar is not constant and it's
10058   // order is greater than that of the vector element type.
10059   return (Order < 0);
10060 }
10061 
10062 /// Test if a (constant) integer Int can be casted to floating point type
10063 /// FloatTy without losing precision.
10064 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10065                                      QualType FloatTy) {
10066   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10067 
10068   // Determine if the integer constant can be expressed as a floating point
10069   // number of the appropriate type.
10070   Expr::EvalResult EVResult;
10071   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10072 
10073   uint64_t Bits = 0;
10074   if (CstInt) {
10075     // Reject constants that would be truncated if they were converted to
10076     // the floating point type. Test by simple to/from conversion.
10077     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10078     //        could be avoided if there was a convertFromAPInt method
10079     //        which could signal back if implicit truncation occurred.
10080     llvm::APSInt Result = EVResult.Val.getInt();
10081     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10082     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10083                            llvm::APFloat::rmTowardZero);
10084     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10085                              !IntTy->hasSignedIntegerRepresentation());
10086     bool Ignored = false;
10087     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10088                            &Ignored);
10089     if (Result != ConvertBack)
10090       return true;
10091   } else {
10092     // Reject types that cannot be fully encoded into the mantissa of
10093     // the float.
10094     Bits = S.Context.getTypeSize(IntTy);
10095     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10096         S.Context.getFloatTypeSemantics(FloatTy));
10097     if (Bits > FloatPrec)
10098       return true;
10099   }
10100 
10101   return false;
10102 }
10103 
10104 /// Attempt to convert and splat Scalar into a vector whose types matches
10105 /// Vector following GCC conversion rules. The rule is that implicit
10106 /// conversion can occur when Scalar can be casted to match Vector's element
10107 /// type without causing truncation of Scalar.
10108 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10109                                         ExprResult *Vector) {
10110   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10111   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10112   const auto *VT = VectorTy->castAs<VectorType>();
10113 
10114   assert(!isa<ExtVectorType>(VT) &&
10115          "ExtVectorTypes should not be handled here!");
10116 
10117   QualType VectorEltTy = VT->getElementType();
10118 
10119   // Reject cases where the vector element type or the scalar element type are
10120   // not integral or floating point types.
10121   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10122     return true;
10123 
10124   // The conversion to apply to the scalar before splatting it,
10125   // if necessary.
10126   CastKind ScalarCast = CK_NoOp;
10127 
10128   // Accept cases where the vector elements are integers and the scalar is
10129   // an integer.
10130   // FIXME: Notionally if the scalar was a floating point value with a precise
10131   //        integral representation, we could cast it to an appropriate integer
10132   //        type and then perform the rest of the checks here. GCC will perform
10133   //        this conversion in some cases as determined by the input language.
10134   //        We should accept it on a language independent basis.
10135   if (VectorEltTy->isIntegralType(S.Context) &&
10136       ScalarTy->isIntegralType(S.Context) &&
10137       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10138 
10139     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10140       return true;
10141 
10142     ScalarCast = CK_IntegralCast;
10143   } else if (VectorEltTy->isIntegralType(S.Context) &&
10144              ScalarTy->isRealFloatingType()) {
10145     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10146       ScalarCast = CK_FloatingToIntegral;
10147     else
10148       return true;
10149   } else if (VectorEltTy->isRealFloatingType()) {
10150     if (ScalarTy->isRealFloatingType()) {
10151 
10152       // Reject cases where the scalar type is not a constant and has a higher
10153       // Order than the vector element type.
10154       llvm::APFloat Result(0.0);
10155 
10156       // Determine whether this is a constant scalar. In the event that the
10157       // value is dependent (and thus cannot be evaluated by the constant
10158       // evaluator), skip the evaluation. This will then diagnose once the
10159       // expression is instantiated.
10160       bool CstScalar = Scalar->get()->isValueDependent() ||
10161                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10162       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10163       if (!CstScalar && Order < 0)
10164         return true;
10165 
10166       // If the scalar cannot be safely casted to the vector element type,
10167       // reject it.
10168       if (CstScalar) {
10169         bool Truncated = false;
10170         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10171                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10172         if (Truncated)
10173           return true;
10174       }
10175 
10176       ScalarCast = CK_FloatingCast;
10177     } else if (ScalarTy->isIntegralType(S.Context)) {
10178       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10179         return true;
10180 
10181       ScalarCast = CK_IntegralToFloating;
10182     } else
10183       return true;
10184   } else if (ScalarTy->isEnumeralType())
10185     return true;
10186 
10187   // Adjust scalar if desired.
10188   if (Scalar) {
10189     if (ScalarCast != CK_NoOp)
10190       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10191     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10192   }
10193   return false;
10194 }
10195 
10196 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10197                                    SourceLocation Loc, bool IsCompAssign,
10198                                    bool AllowBothBool,
10199                                    bool AllowBoolConversions) {
10200   if (!IsCompAssign) {
10201     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10202     if (LHS.isInvalid())
10203       return QualType();
10204   }
10205   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10206   if (RHS.isInvalid())
10207     return QualType();
10208 
10209   // For conversion purposes, we ignore any qualifiers.
10210   // For example, "const float" and "float" are equivalent.
10211   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10212   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10213 
10214   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10215   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10216   assert(LHSVecType || RHSVecType);
10217 
10218   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10219       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10220     return InvalidOperands(Loc, LHS, RHS);
10221 
10222   // AltiVec-style "vector bool op vector bool" combinations are allowed
10223   // for some operators but not others.
10224   if (!AllowBothBool &&
10225       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10226       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10227     return InvalidOperands(Loc, LHS, RHS);
10228 
10229   // If the vector types are identical, return.
10230   if (Context.hasSameType(LHSType, RHSType))
10231     return LHSType;
10232 
10233   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10234   if (LHSVecType && RHSVecType &&
10235       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10236     if (isa<ExtVectorType>(LHSVecType)) {
10237       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10238       return LHSType;
10239     }
10240 
10241     if (!IsCompAssign)
10242       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10243     return RHSType;
10244   }
10245 
10246   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10247   // can be mixed, with the result being the non-bool type.  The non-bool
10248   // operand must have integer element type.
10249   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10250       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10251       (Context.getTypeSize(LHSVecType->getElementType()) ==
10252        Context.getTypeSize(RHSVecType->getElementType()))) {
10253     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10254         LHSVecType->getElementType()->isIntegerType() &&
10255         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10256       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10257       return LHSType;
10258     }
10259     if (!IsCompAssign &&
10260         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10261         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10262         RHSVecType->getElementType()->isIntegerType()) {
10263       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10264       return RHSType;
10265     }
10266   }
10267 
10268   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10269   // since the ambiguity can affect the ABI.
10270   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10271     const VectorType *VecType = SecondType->getAs<VectorType>();
10272     return FirstType->isSizelessBuiltinType() && VecType &&
10273            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10274             VecType->getVectorKind() ==
10275                 VectorType::SveFixedLengthPredicateVector);
10276   };
10277 
10278   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10279     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10280     return QualType();
10281   }
10282 
10283   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10284   // since the ambiguity can affect the ABI.
10285   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10286     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10287     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10288 
10289     if (FirstVecType && SecondVecType)
10290       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10291              (SecondVecType->getVectorKind() ==
10292                   VectorType::SveFixedLengthDataVector ||
10293               SecondVecType->getVectorKind() ==
10294                   VectorType::SveFixedLengthPredicateVector);
10295 
10296     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10297            SecondVecType->getVectorKind() == VectorType::GenericVector;
10298   };
10299 
10300   if (IsSveGnuConversion(LHSType, RHSType) ||
10301       IsSveGnuConversion(RHSType, LHSType)) {
10302     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10303     return QualType();
10304   }
10305 
10306   // If there's a vector type and a scalar, try to convert the scalar to
10307   // the vector element type and splat.
10308   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10309   if (!RHSVecType) {
10310     if (isa<ExtVectorType>(LHSVecType)) {
10311       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10312                                     LHSVecType->getElementType(), LHSType,
10313                                     DiagID))
10314         return LHSType;
10315     } else {
10316       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10317         return LHSType;
10318     }
10319   }
10320   if (!LHSVecType) {
10321     if (isa<ExtVectorType>(RHSVecType)) {
10322       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10323                                     LHSType, RHSVecType->getElementType(),
10324                                     RHSType, DiagID))
10325         return RHSType;
10326     } else {
10327       if (LHS.get()->isLValue() ||
10328           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10329         return RHSType;
10330     }
10331   }
10332 
10333   // FIXME: The code below also handles conversion between vectors and
10334   // non-scalars, we should break this down into fine grained specific checks
10335   // and emit proper diagnostics.
10336   QualType VecType = LHSVecType ? LHSType : RHSType;
10337   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10338   QualType OtherType = LHSVecType ? RHSType : LHSType;
10339   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10340   if (isLaxVectorConversion(OtherType, VecType)) {
10341     // If we're allowing lax vector conversions, only the total (data) size
10342     // needs to be the same. For non compound assignment, if one of the types is
10343     // scalar, the result is always the vector type.
10344     if (!IsCompAssign) {
10345       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10346       return VecType;
10347     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10348     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10349     // type. Note that this is already done by non-compound assignments in
10350     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10351     // <1 x T> -> T. The result is also a vector type.
10352     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10353                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10354       ExprResult *RHSExpr = &RHS;
10355       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10356       return VecType;
10357     }
10358   }
10359 
10360   // Okay, the expression is invalid.
10361 
10362   // If there's a non-vector, non-real operand, diagnose that.
10363   if ((!RHSVecType && !RHSType->isRealType()) ||
10364       (!LHSVecType && !LHSType->isRealType())) {
10365     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10366       << LHSType << RHSType
10367       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10368     return QualType();
10369   }
10370 
10371   // OpenCL V1.1 6.2.6.p1:
10372   // If the operands are of more than one vector type, then an error shall
10373   // occur. Implicit conversions between vector types are not permitted, per
10374   // section 6.2.1.
10375   if (getLangOpts().OpenCL &&
10376       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10377       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10378     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10379                                                            << RHSType;
10380     return QualType();
10381   }
10382 
10383 
10384   // If there is a vector type that is not a ExtVector and a scalar, we reach
10385   // this point if scalar could not be converted to the vector's element type
10386   // without truncation.
10387   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10388       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10389     QualType Scalar = LHSVecType ? RHSType : LHSType;
10390     QualType Vector = LHSVecType ? LHSType : RHSType;
10391     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10392     Diag(Loc,
10393          diag::err_typecheck_vector_not_convertable_implict_truncation)
10394         << ScalarOrVector << Scalar << Vector;
10395 
10396     return QualType();
10397   }
10398 
10399   // Otherwise, use the generic diagnostic.
10400   Diag(Loc, DiagID)
10401     << LHSType << RHSType
10402     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10403   return QualType();
10404 }
10405 
10406 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10407 // expression.  These are mainly cases where the null pointer is used as an
10408 // integer instead of a pointer.
10409 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10410                                 SourceLocation Loc, bool IsCompare) {
10411   // The canonical way to check for a GNU null is with isNullPointerConstant,
10412   // but we use a bit of a hack here for speed; this is a relatively
10413   // hot path, and isNullPointerConstant is slow.
10414   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10415   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10416 
10417   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10418 
10419   // Avoid analyzing cases where the result will either be invalid (and
10420   // diagnosed as such) or entirely valid and not something to warn about.
10421   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10422       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10423     return;
10424 
10425   // Comparison operations would not make sense with a null pointer no matter
10426   // what the other expression is.
10427   if (!IsCompare) {
10428     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10429         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10430         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10431     return;
10432   }
10433 
10434   // The rest of the operations only make sense with a null pointer
10435   // if the other expression is a pointer.
10436   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10437       NonNullType->canDecayToPointerType())
10438     return;
10439 
10440   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10441       << LHSNull /* LHS is NULL */ << NonNullType
10442       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10443 }
10444 
10445 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10446                                           SourceLocation Loc) {
10447   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10448   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10449   if (!LUE || !RUE)
10450     return;
10451   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10452       RUE->getKind() != UETT_SizeOf)
10453     return;
10454 
10455   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10456   QualType LHSTy = LHSArg->getType();
10457   QualType RHSTy;
10458 
10459   if (RUE->isArgumentType())
10460     RHSTy = RUE->getArgumentType().getNonReferenceType();
10461   else
10462     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10463 
10464   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10465     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10466       return;
10467 
10468     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10469     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10470       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10471         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10472             << LHSArgDecl;
10473     }
10474   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10475     QualType ArrayElemTy = ArrayTy->getElementType();
10476     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10477         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10478         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10479         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10480       return;
10481     S.Diag(Loc, diag::warn_division_sizeof_array)
10482         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10483     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10484       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10485         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10486             << LHSArgDecl;
10487     }
10488 
10489     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10490   }
10491 }
10492 
10493 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10494                                                ExprResult &RHS,
10495                                                SourceLocation Loc, bool IsDiv) {
10496   // Check for division/remainder by zero.
10497   Expr::EvalResult RHSValue;
10498   if (!RHS.get()->isValueDependent() &&
10499       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10500       RHSValue.Val.getInt() == 0)
10501     S.DiagRuntimeBehavior(Loc, RHS.get(),
10502                           S.PDiag(diag::warn_remainder_division_by_zero)
10503                             << IsDiv << RHS.get()->getSourceRange());
10504 }
10505 
10506 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10507                                            SourceLocation Loc,
10508                                            bool IsCompAssign, bool IsDiv) {
10509   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10510 
10511   QualType LHSTy = LHS.get()->getType();
10512   QualType RHSTy = RHS.get()->getType();
10513   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10514     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10515                                /*AllowBothBool*/getLangOpts().AltiVec,
10516                                /*AllowBoolConversions*/false);
10517   if (!IsDiv &&
10518       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10519     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10520   // For division, only matrix-by-scalar is supported. Other combinations with
10521   // matrix types are invalid.
10522   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10523     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10524 
10525   QualType compType = UsualArithmeticConversions(
10526       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10527   if (LHS.isInvalid() || RHS.isInvalid())
10528     return QualType();
10529 
10530 
10531   if (compType.isNull() || !compType->isArithmeticType())
10532     return InvalidOperands(Loc, LHS, RHS);
10533   if (IsDiv) {
10534     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10535     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10536   }
10537   return compType;
10538 }
10539 
10540 QualType Sema::CheckRemainderOperands(
10541   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10542   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10543 
10544   if (LHS.get()->getType()->isVectorType() ||
10545       RHS.get()->getType()->isVectorType()) {
10546     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10547         RHS.get()->getType()->hasIntegerRepresentation())
10548       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10549                                  /*AllowBothBool*/getLangOpts().AltiVec,
10550                                  /*AllowBoolConversions*/false);
10551     return InvalidOperands(Loc, LHS, RHS);
10552   }
10553 
10554   QualType compType = UsualArithmeticConversions(
10555       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10556   if (LHS.isInvalid() || RHS.isInvalid())
10557     return QualType();
10558 
10559   if (compType.isNull() || !compType->isIntegerType())
10560     return InvalidOperands(Loc, LHS, RHS);
10561   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10562   return compType;
10563 }
10564 
10565 /// Diagnose invalid arithmetic on two void pointers.
10566 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10567                                                 Expr *LHSExpr, Expr *RHSExpr) {
10568   S.Diag(Loc, S.getLangOpts().CPlusPlus
10569                 ? diag::err_typecheck_pointer_arith_void_type
10570                 : diag::ext_gnu_void_ptr)
10571     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10572                             << RHSExpr->getSourceRange();
10573 }
10574 
10575 /// Diagnose invalid arithmetic on a void pointer.
10576 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10577                                             Expr *Pointer) {
10578   S.Diag(Loc, S.getLangOpts().CPlusPlus
10579                 ? diag::err_typecheck_pointer_arith_void_type
10580                 : diag::ext_gnu_void_ptr)
10581     << 0 /* one pointer */ << Pointer->getSourceRange();
10582 }
10583 
10584 /// Diagnose invalid arithmetic on a null pointer.
10585 ///
10586 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10587 /// idiom, which we recognize as a GNU extension.
10588 ///
10589 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10590                                             Expr *Pointer, bool IsGNUIdiom) {
10591   if (IsGNUIdiom)
10592     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10593       << Pointer->getSourceRange();
10594   else
10595     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10596       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10597 }
10598 
10599 /// Diagnose invalid subraction on a null pointer.
10600 ///
10601 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10602                                              Expr *Pointer, bool BothNull) {
10603   // Null - null is valid in C++ [expr.add]p7
10604   if (BothNull && S.getLangOpts().CPlusPlus)
10605     return;
10606 
10607   // Is this s a macro from a system header?
10608   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10609     return;
10610 
10611   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10612       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10613 }
10614 
10615 /// Diagnose invalid arithmetic on two function pointers.
10616 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10617                                                     Expr *LHS, Expr *RHS) {
10618   assert(LHS->getType()->isAnyPointerType());
10619   assert(RHS->getType()->isAnyPointerType());
10620   S.Diag(Loc, S.getLangOpts().CPlusPlus
10621                 ? diag::err_typecheck_pointer_arith_function_type
10622                 : diag::ext_gnu_ptr_func_arith)
10623     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10624     // We only show the second type if it differs from the first.
10625     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10626                                                    RHS->getType())
10627     << RHS->getType()->getPointeeType()
10628     << LHS->getSourceRange() << RHS->getSourceRange();
10629 }
10630 
10631 /// Diagnose invalid arithmetic on a function pointer.
10632 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10633                                                 Expr *Pointer) {
10634   assert(Pointer->getType()->isAnyPointerType());
10635   S.Diag(Loc, S.getLangOpts().CPlusPlus
10636                 ? diag::err_typecheck_pointer_arith_function_type
10637                 : diag::ext_gnu_ptr_func_arith)
10638     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10639     << 0 /* one pointer, so only one type */
10640     << Pointer->getSourceRange();
10641 }
10642 
10643 /// Emit error if Operand is incomplete pointer type
10644 ///
10645 /// \returns True if pointer has incomplete type
10646 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10647                                                  Expr *Operand) {
10648   QualType ResType = Operand->getType();
10649   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10650     ResType = ResAtomicType->getValueType();
10651 
10652   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10653   QualType PointeeTy = ResType->getPointeeType();
10654   return S.RequireCompleteSizedType(
10655       Loc, PointeeTy,
10656       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10657       Operand->getSourceRange());
10658 }
10659 
10660 /// Check the validity of an arithmetic pointer operand.
10661 ///
10662 /// If the operand has pointer type, this code will check for pointer types
10663 /// which are invalid in arithmetic operations. These will be diagnosed
10664 /// appropriately, including whether or not the use is supported as an
10665 /// extension.
10666 ///
10667 /// \returns True when the operand is valid to use (even if as an extension).
10668 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10669                                             Expr *Operand) {
10670   QualType ResType = Operand->getType();
10671   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10672     ResType = ResAtomicType->getValueType();
10673 
10674   if (!ResType->isAnyPointerType()) return true;
10675 
10676   QualType PointeeTy = ResType->getPointeeType();
10677   if (PointeeTy->isVoidType()) {
10678     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10679     return !S.getLangOpts().CPlusPlus;
10680   }
10681   if (PointeeTy->isFunctionType()) {
10682     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10683     return !S.getLangOpts().CPlusPlus;
10684   }
10685 
10686   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10687 
10688   return true;
10689 }
10690 
10691 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10692 /// operands.
10693 ///
10694 /// This routine will diagnose any invalid arithmetic on pointer operands much
10695 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10696 /// for emitting a single diagnostic even for operations where both LHS and RHS
10697 /// are (potentially problematic) pointers.
10698 ///
10699 /// \returns True when the operand is valid to use (even if as an extension).
10700 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10701                                                 Expr *LHSExpr, Expr *RHSExpr) {
10702   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10703   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10704   if (!isLHSPointer && !isRHSPointer) return true;
10705 
10706   QualType LHSPointeeTy, RHSPointeeTy;
10707   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10708   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10709 
10710   // if both are pointers check if operation is valid wrt address spaces
10711   if (isLHSPointer && isRHSPointer) {
10712     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10713       S.Diag(Loc,
10714              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10715           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10716           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10717       return false;
10718     }
10719   }
10720 
10721   // Check for arithmetic on pointers to incomplete types.
10722   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10723   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10724   if (isLHSVoidPtr || isRHSVoidPtr) {
10725     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10726     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10727     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10728 
10729     return !S.getLangOpts().CPlusPlus;
10730   }
10731 
10732   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10733   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10734   if (isLHSFuncPtr || isRHSFuncPtr) {
10735     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10736     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10737                                                                 RHSExpr);
10738     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10739 
10740     return !S.getLangOpts().CPlusPlus;
10741   }
10742 
10743   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10744     return false;
10745   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10746     return false;
10747 
10748   return true;
10749 }
10750 
10751 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10752 /// literal.
10753 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10754                                   Expr *LHSExpr, Expr *RHSExpr) {
10755   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10756   Expr* IndexExpr = RHSExpr;
10757   if (!StrExpr) {
10758     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10759     IndexExpr = LHSExpr;
10760   }
10761 
10762   bool IsStringPlusInt = StrExpr &&
10763       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10764   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10765     return;
10766 
10767   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10768   Self.Diag(OpLoc, diag::warn_string_plus_int)
10769       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10770 
10771   // Only print a fixit for "str" + int, not for int + "str".
10772   if (IndexExpr == RHSExpr) {
10773     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10774     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10775         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10776         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10777         << FixItHint::CreateInsertion(EndLoc, "]");
10778   } else
10779     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10780 }
10781 
10782 /// Emit a warning when adding a char literal to a string.
10783 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10784                                    Expr *LHSExpr, Expr *RHSExpr) {
10785   const Expr *StringRefExpr = LHSExpr;
10786   const CharacterLiteral *CharExpr =
10787       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10788 
10789   if (!CharExpr) {
10790     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10791     StringRefExpr = RHSExpr;
10792   }
10793 
10794   if (!CharExpr || !StringRefExpr)
10795     return;
10796 
10797   const QualType StringType = StringRefExpr->getType();
10798 
10799   // Return if not a PointerType.
10800   if (!StringType->isAnyPointerType())
10801     return;
10802 
10803   // Return if not a CharacterType.
10804   if (!StringType->getPointeeType()->isAnyCharacterType())
10805     return;
10806 
10807   ASTContext &Ctx = Self.getASTContext();
10808   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10809 
10810   const QualType CharType = CharExpr->getType();
10811   if (!CharType->isAnyCharacterType() &&
10812       CharType->isIntegerType() &&
10813       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10814     Self.Diag(OpLoc, diag::warn_string_plus_char)
10815         << DiagRange << Ctx.CharTy;
10816   } else {
10817     Self.Diag(OpLoc, diag::warn_string_plus_char)
10818         << DiagRange << CharExpr->getType();
10819   }
10820 
10821   // Only print a fixit for str + char, not for char + str.
10822   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10823     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10824     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10825         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10826         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10827         << FixItHint::CreateInsertion(EndLoc, "]");
10828   } else {
10829     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10830   }
10831 }
10832 
10833 /// Emit error when two pointers are incompatible.
10834 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10835                                            Expr *LHSExpr, Expr *RHSExpr) {
10836   assert(LHSExpr->getType()->isAnyPointerType());
10837   assert(RHSExpr->getType()->isAnyPointerType());
10838   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10839     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10840     << RHSExpr->getSourceRange();
10841 }
10842 
10843 // C99 6.5.6
10844 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10845                                      SourceLocation Loc, BinaryOperatorKind Opc,
10846                                      QualType* CompLHSTy) {
10847   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10848 
10849   if (LHS.get()->getType()->isVectorType() ||
10850       RHS.get()->getType()->isVectorType()) {
10851     QualType compType = CheckVectorOperands(
10852         LHS, RHS, Loc, CompLHSTy,
10853         /*AllowBothBool*/getLangOpts().AltiVec,
10854         /*AllowBoolConversions*/getLangOpts().ZVector);
10855     if (CompLHSTy) *CompLHSTy = compType;
10856     return compType;
10857   }
10858 
10859   if (LHS.get()->getType()->isConstantMatrixType() ||
10860       RHS.get()->getType()->isConstantMatrixType()) {
10861     QualType compType =
10862         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10863     if (CompLHSTy)
10864       *CompLHSTy = compType;
10865     return compType;
10866   }
10867 
10868   QualType compType = UsualArithmeticConversions(
10869       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10870   if (LHS.isInvalid() || RHS.isInvalid())
10871     return QualType();
10872 
10873   // Diagnose "string literal" '+' int and string '+' "char literal".
10874   if (Opc == BO_Add) {
10875     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10876     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10877   }
10878 
10879   // handle the common case first (both operands are arithmetic).
10880   if (!compType.isNull() && compType->isArithmeticType()) {
10881     if (CompLHSTy) *CompLHSTy = compType;
10882     return compType;
10883   }
10884 
10885   // Type-checking.  Ultimately the pointer's going to be in PExp;
10886   // note that we bias towards the LHS being the pointer.
10887   Expr *PExp = LHS.get(), *IExp = RHS.get();
10888 
10889   bool isObjCPointer;
10890   if (PExp->getType()->isPointerType()) {
10891     isObjCPointer = false;
10892   } else if (PExp->getType()->isObjCObjectPointerType()) {
10893     isObjCPointer = true;
10894   } else {
10895     std::swap(PExp, IExp);
10896     if (PExp->getType()->isPointerType()) {
10897       isObjCPointer = false;
10898     } else if (PExp->getType()->isObjCObjectPointerType()) {
10899       isObjCPointer = true;
10900     } else {
10901       return InvalidOperands(Loc, LHS, RHS);
10902     }
10903   }
10904   assert(PExp->getType()->isAnyPointerType());
10905 
10906   if (!IExp->getType()->isIntegerType())
10907     return InvalidOperands(Loc, LHS, RHS);
10908 
10909   // Adding to a null pointer results in undefined behavior.
10910   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10911           Context, Expr::NPC_ValueDependentIsNotNull)) {
10912     // In C++ adding zero to a null pointer is defined.
10913     Expr::EvalResult KnownVal;
10914     if (!getLangOpts().CPlusPlus ||
10915         (!IExp->isValueDependent() &&
10916          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10917           KnownVal.Val.getInt() != 0))) {
10918       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10919       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10920           Context, BO_Add, PExp, IExp);
10921       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10922     }
10923   }
10924 
10925   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10926     return QualType();
10927 
10928   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10929     return QualType();
10930 
10931   // Check array bounds for pointer arithemtic
10932   CheckArrayAccess(PExp, IExp);
10933 
10934   if (CompLHSTy) {
10935     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10936     if (LHSTy.isNull()) {
10937       LHSTy = LHS.get()->getType();
10938       if (LHSTy->isPromotableIntegerType())
10939         LHSTy = Context.getPromotedIntegerType(LHSTy);
10940     }
10941     *CompLHSTy = LHSTy;
10942   }
10943 
10944   return PExp->getType();
10945 }
10946 
10947 // C99 6.5.6
10948 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10949                                         SourceLocation Loc,
10950                                         QualType* CompLHSTy) {
10951   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10952 
10953   if (LHS.get()->getType()->isVectorType() ||
10954       RHS.get()->getType()->isVectorType()) {
10955     QualType compType = CheckVectorOperands(
10956         LHS, RHS, Loc, CompLHSTy,
10957         /*AllowBothBool*/getLangOpts().AltiVec,
10958         /*AllowBoolConversions*/getLangOpts().ZVector);
10959     if (CompLHSTy) *CompLHSTy = compType;
10960     return compType;
10961   }
10962 
10963   if (LHS.get()->getType()->isConstantMatrixType() ||
10964       RHS.get()->getType()->isConstantMatrixType()) {
10965     QualType compType =
10966         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10967     if (CompLHSTy)
10968       *CompLHSTy = compType;
10969     return compType;
10970   }
10971 
10972   QualType compType = UsualArithmeticConversions(
10973       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10974   if (LHS.isInvalid() || RHS.isInvalid())
10975     return QualType();
10976 
10977   // Enforce type constraints: C99 6.5.6p3.
10978 
10979   // Handle the common case first (both operands are arithmetic).
10980   if (!compType.isNull() && compType->isArithmeticType()) {
10981     if (CompLHSTy) *CompLHSTy = compType;
10982     return compType;
10983   }
10984 
10985   // Either ptr - int   or   ptr - ptr.
10986   if (LHS.get()->getType()->isAnyPointerType()) {
10987     QualType lpointee = LHS.get()->getType()->getPointeeType();
10988 
10989     // Diagnose bad cases where we step over interface counts.
10990     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10991         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10992       return QualType();
10993 
10994     // The result type of a pointer-int computation is the pointer type.
10995     if (RHS.get()->getType()->isIntegerType()) {
10996       // Subtracting from a null pointer should produce a warning.
10997       // The last argument to the diagnose call says this doesn't match the
10998       // GNU int-to-pointer idiom.
10999       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11000                                            Expr::NPC_ValueDependentIsNotNull)) {
11001         // In C++ adding zero to a null pointer is defined.
11002         Expr::EvalResult KnownVal;
11003         if (!getLangOpts().CPlusPlus ||
11004             (!RHS.get()->isValueDependent() &&
11005              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11006               KnownVal.Val.getInt() != 0))) {
11007           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11008         }
11009       }
11010 
11011       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11012         return QualType();
11013 
11014       // Check array bounds for pointer arithemtic
11015       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11016                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11017 
11018       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11019       return LHS.get()->getType();
11020     }
11021 
11022     // Handle pointer-pointer subtractions.
11023     if (const PointerType *RHSPTy
11024           = RHS.get()->getType()->getAs<PointerType>()) {
11025       QualType rpointee = RHSPTy->getPointeeType();
11026 
11027       if (getLangOpts().CPlusPlus) {
11028         // Pointee types must be the same: C++ [expr.add]
11029         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11030           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11031         }
11032       } else {
11033         // Pointee types must be compatible C99 6.5.6p3
11034         if (!Context.typesAreCompatible(
11035                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11036                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11037           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11038           return QualType();
11039         }
11040       }
11041 
11042       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11043                                                LHS.get(), RHS.get()))
11044         return QualType();
11045 
11046       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11047           Context, Expr::NPC_ValueDependentIsNotNull);
11048       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11049           Context, Expr::NPC_ValueDependentIsNotNull);
11050 
11051       // Subtracting nullptr or from nullptr is suspect
11052       if (LHSIsNullPtr)
11053         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11054       if (RHSIsNullPtr)
11055         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11056 
11057       // The pointee type may have zero size.  As an extension, a structure or
11058       // union may have zero size or an array may have zero length.  In this
11059       // case subtraction does not make sense.
11060       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11061         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11062         if (ElementSize.isZero()) {
11063           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11064             << rpointee.getUnqualifiedType()
11065             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11066         }
11067       }
11068 
11069       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11070       return Context.getPointerDiffType();
11071     }
11072   }
11073 
11074   return InvalidOperands(Loc, LHS, RHS);
11075 }
11076 
11077 static bool isScopedEnumerationType(QualType T) {
11078   if (const EnumType *ET = T->getAs<EnumType>())
11079     return ET->getDecl()->isScoped();
11080   return false;
11081 }
11082 
11083 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11084                                    SourceLocation Loc, BinaryOperatorKind Opc,
11085                                    QualType LHSType) {
11086   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11087   // so skip remaining warnings as we don't want to modify values within Sema.
11088   if (S.getLangOpts().OpenCL)
11089     return;
11090 
11091   // Check right/shifter operand
11092   Expr::EvalResult RHSResult;
11093   if (RHS.get()->isValueDependent() ||
11094       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11095     return;
11096   llvm::APSInt Right = RHSResult.Val.getInt();
11097 
11098   if (Right.isNegative()) {
11099     S.DiagRuntimeBehavior(Loc, RHS.get(),
11100                           S.PDiag(diag::warn_shift_negative)
11101                             << RHS.get()->getSourceRange());
11102     return;
11103   }
11104 
11105   QualType LHSExprType = LHS.get()->getType();
11106   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11107   if (LHSExprType->isBitIntType())
11108     LeftSize = S.Context.getIntWidth(LHSExprType);
11109   else if (LHSExprType->isFixedPointType()) {
11110     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11111     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11112   }
11113   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11114   if (Right.uge(LeftBits)) {
11115     S.DiagRuntimeBehavior(Loc, RHS.get(),
11116                           S.PDiag(diag::warn_shift_gt_typewidth)
11117                             << RHS.get()->getSourceRange());
11118     return;
11119   }
11120 
11121   // FIXME: We probably need to handle fixed point types specially here.
11122   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11123     return;
11124 
11125   // When left shifting an ICE which is signed, we can check for overflow which
11126   // according to C++ standards prior to C++2a has undefined behavior
11127   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11128   // more than the maximum value representable in the result type, so never
11129   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11130   // expression is still probably a bug.)
11131   Expr::EvalResult LHSResult;
11132   if (LHS.get()->isValueDependent() ||
11133       LHSType->hasUnsignedIntegerRepresentation() ||
11134       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11135     return;
11136   llvm::APSInt Left = LHSResult.Val.getInt();
11137 
11138   // If LHS does not have a signed type and non-negative value
11139   // then, the behavior is undefined before C++2a. Warn about it.
11140   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11141       !S.getLangOpts().CPlusPlus20) {
11142     S.DiagRuntimeBehavior(Loc, LHS.get(),
11143                           S.PDiag(diag::warn_shift_lhs_negative)
11144                             << LHS.get()->getSourceRange());
11145     return;
11146   }
11147 
11148   llvm::APInt ResultBits =
11149       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11150   if (LeftBits.uge(ResultBits))
11151     return;
11152   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11153   Result = Result.shl(Right);
11154 
11155   // Print the bit representation of the signed integer as an unsigned
11156   // hexadecimal number.
11157   SmallString<40> HexResult;
11158   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11159 
11160   // If we are only missing a sign bit, this is less likely to result in actual
11161   // bugs -- if the result is cast back to an unsigned type, it will have the
11162   // expected value. Thus we place this behind a different warning that can be
11163   // turned off separately if needed.
11164   if (LeftBits == ResultBits - 1) {
11165     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11166         << HexResult << LHSType
11167         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11168     return;
11169   }
11170 
11171   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11172     << HexResult.str() << Result.getMinSignedBits() << LHSType
11173     << Left.getBitWidth() << LHS.get()->getSourceRange()
11174     << RHS.get()->getSourceRange();
11175 }
11176 
11177 /// Return the resulting type when a vector is shifted
11178 ///        by a scalar or vector shift amount.
11179 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11180                                  SourceLocation Loc, bool IsCompAssign) {
11181   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11182   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11183       !LHS.get()->getType()->isVectorType()) {
11184     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11185       << RHS.get()->getType() << LHS.get()->getType()
11186       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11187     return QualType();
11188   }
11189 
11190   if (!IsCompAssign) {
11191     LHS = S.UsualUnaryConversions(LHS.get());
11192     if (LHS.isInvalid()) return QualType();
11193   }
11194 
11195   RHS = S.UsualUnaryConversions(RHS.get());
11196   if (RHS.isInvalid()) return QualType();
11197 
11198   QualType LHSType = LHS.get()->getType();
11199   // Note that LHS might be a scalar because the routine calls not only in
11200   // OpenCL case.
11201   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11202   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11203 
11204   // Note that RHS might not be a vector.
11205   QualType RHSType = RHS.get()->getType();
11206   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11207   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11208 
11209   // The operands need to be integers.
11210   if (!LHSEleType->isIntegerType()) {
11211     S.Diag(Loc, diag::err_typecheck_expect_int)
11212       << LHS.get()->getType() << LHS.get()->getSourceRange();
11213     return QualType();
11214   }
11215 
11216   if (!RHSEleType->isIntegerType()) {
11217     S.Diag(Loc, diag::err_typecheck_expect_int)
11218       << RHS.get()->getType() << RHS.get()->getSourceRange();
11219     return QualType();
11220   }
11221 
11222   if (!LHSVecTy) {
11223     assert(RHSVecTy);
11224     if (IsCompAssign)
11225       return RHSType;
11226     if (LHSEleType != RHSEleType) {
11227       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11228       LHSEleType = RHSEleType;
11229     }
11230     QualType VecTy =
11231         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11232     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11233     LHSType = VecTy;
11234   } else if (RHSVecTy) {
11235     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11236     // are applied component-wise. So if RHS is a vector, then ensure
11237     // that the number of elements is the same as LHS...
11238     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11239       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11240         << LHS.get()->getType() << RHS.get()->getType()
11241         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11242       return QualType();
11243     }
11244     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11245       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11246       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11247       if (LHSBT != RHSBT &&
11248           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11249         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11250             << LHS.get()->getType() << RHS.get()->getType()
11251             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11252       }
11253     }
11254   } else {
11255     // ...else expand RHS to match the number of elements in LHS.
11256     QualType VecTy =
11257       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11258     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11259   }
11260 
11261   return LHSType;
11262 }
11263 
11264 // C99 6.5.7
11265 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11266                                   SourceLocation Loc, BinaryOperatorKind Opc,
11267                                   bool IsCompAssign) {
11268   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11269 
11270   // Vector shifts promote their scalar inputs to vector type.
11271   if (LHS.get()->getType()->isVectorType() ||
11272       RHS.get()->getType()->isVectorType()) {
11273     if (LangOpts.ZVector) {
11274       // The shift operators for the z vector extensions work basically
11275       // like general shifts, except that neither the LHS nor the RHS is
11276       // allowed to be a "vector bool".
11277       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11278         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11279           return InvalidOperands(Loc, LHS, RHS);
11280       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11281         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11282           return InvalidOperands(Loc, LHS, RHS);
11283     }
11284     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11285   }
11286 
11287   // Shifts don't perform usual arithmetic conversions, they just do integer
11288   // promotions on each operand. C99 6.5.7p3
11289 
11290   // For the LHS, do usual unary conversions, but then reset them away
11291   // if this is a compound assignment.
11292   ExprResult OldLHS = LHS;
11293   LHS = UsualUnaryConversions(LHS.get());
11294   if (LHS.isInvalid())
11295     return QualType();
11296   QualType LHSType = LHS.get()->getType();
11297   if (IsCompAssign) LHS = OldLHS;
11298 
11299   // The RHS is simpler.
11300   RHS = UsualUnaryConversions(RHS.get());
11301   if (RHS.isInvalid())
11302     return QualType();
11303   QualType RHSType = RHS.get()->getType();
11304 
11305   // C99 6.5.7p2: Each of the operands shall have integer type.
11306   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11307   if ((!LHSType->isFixedPointOrIntegerType() &&
11308        !LHSType->hasIntegerRepresentation()) ||
11309       !RHSType->hasIntegerRepresentation())
11310     return InvalidOperands(Loc, LHS, RHS);
11311 
11312   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11313   // hasIntegerRepresentation() above instead of this.
11314   if (isScopedEnumerationType(LHSType) ||
11315       isScopedEnumerationType(RHSType)) {
11316     return InvalidOperands(Loc, LHS, RHS);
11317   }
11318   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11319 
11320   // "The type of the result is that of the promoted left operand."
11321   return LHSType;
11322 }
11323 
11324 /// Diagnose bad pointer comparisons.
11325 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11326                                               ExprResult &LHS, ExprResult &RHS,
11327                                               bool IsError) {
11328   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11329                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11330     << LHS.get()->getType() << RHS.get()->getType()
11331     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11332 }
11333 
11334 /// Returns false if the pointers are converted to a composite type,
11335 /// true otherwise.
11336 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11337                                            ExprResult &LHS, ExprResult &RHS) {
11338   // C++ [expr.rel]p2:
11339   //   [...] Pointer conversions (4.10) and qualification
11340   //   conversions (4.4) are performed on pointer operands (or on
11341   //   a pointer operand and a null pointer constant) to bring
11342   //   them to their composite pointer type. [...]
11343   //
11344   // C++ [expr.eq]p1 uses the same notion for (in)equality
11345   // comparisons of pointers.
11346 
11347   QualType LHSType = LHS.get()->getType();
11348   QualType RHSType = RHS.get()->getType();
11349   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11350          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11351 
11352   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11353   if (T.isNull()) {
11354     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11355         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11356       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11357     else
11358       S.InvalidOperands(Loc, LHS, RHS);
11359     return true;
11360   }
11361 
11362   return false;
11363 }
11364 
11365 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11366                                                     ExprResult &LHS,
11367                                                     ExprResult &RHS,
11368                                                     bool IsError) {
11369   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11370                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11371     << LHS.get()->getType() << RHS.get()->getType()
11372     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11373 }
11374 
11375 static bool isObjCObjectLiteral(ExprResult &E) {
11376   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11377   case Stmt::ObjCArrayLiteralClass:
11378   case Stmt::ObjCDictionaryLiteralClass:
11379   case Stmt::ObjCStringLiteralClass:
11380   case Stmt::ObjCBoxedExprClass:
11381     return true;
11382   default:
11383     // Note that ObjCBoolLiteral is NOT an object literal!
11384     return false;
11385   }
11386 }
11387 
11388 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11389   const ObjCObjectPointerType *Type =
11390     LHS->getType()->getAs<ObjCObjectPointerType>();
11391 
11392   // If this is not actually an Objective-C object, bail out.
11393   if (!Type)
11394     return false;
11395 
11396   // Get the LHS object's interface type.
11397   QualType InterfaceType = Type->getPointeeType();
11398 
11399   // If the RHS isn't an Objective-C object, bail out.
11400   if (!RHS->getType()->isObjCObjectPointerType())
11401     return false;
11402 
11403   // Try to find the -isEqual: method.
11404   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11405   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11406                                                       InterfaceType,
11407                                                       /*IsInstance=*/true);
11408   if (!Method) {
11409     if (Type->isObjCIdType()) {
11410       // For 'id', just check the global pool.
11411       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11412                                                   /*receiverId=*/true);
11413     } else {
11414       // Check protocols.
11415       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11416                                              /*IsInstance=*/true);
11417     }
11418   }
11419 
11420   if (!Method)
11421     return false;
11422 
11423   QualType T = Method->parameters()[0]->getType();
11424   if (!T->isObjCObjectPointerType())
11425     return false;
11426 
11427   QualType R = Method->getReturnType();
11428   if (!R->isScalarType())
11429     return false;
11430 
11431   return true;
11432 }
11433 
11434 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11435   FromE = FromE->IgnoreParenImpCasts();
11436   switch (FromE->getStmtClass()) {
11437     default:
11438       break;
11439     case Stmt::ObjCStringLiteralClass:
11440       // "string literal"
11441       return LK_String;
11442     case Stmt::ObjCArrayLiteralClass:
11443       // "array literal"
11444       return LK_Array;
11445     case Stmt::ObjCDictionaryLiteralClass:
11446       // "dictionary literal"
11447       return LK_Dictionary;
11448     case Stmt::BlockExprClass:
11449       return LK_Block;
11450     case Stmt::ObjCBoxedExprClass: {
11451       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11452       switch (Inner->getStmtClass()) {
11453         case Stmt::IntegerLiteralClass:
11454         case Stmt::FloatingLiteralClass:
11455         case Stmt::CharacterLiteralClass:
11456         case Stmt::ObjCBoolLiteralExprClass:
11457         case Stmt::CXXBoolLiteralExprClass:
11458           // "numeric literal"
11459           return LK_Numeric;
11460         case Stmt::ImplicitCastExprClass: {
11461           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11462           // Boolean literals can be represented by implicit casts.
11463           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11464             return LK_Numeric;
11465           break;
11466         }
11467         default:
11468           break;
11469       }
11470       return LK_Boxed;
11471     }
11472   }
11473   return LK_None;
11474 }
11475 
11476 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11477                                           ExprResult &LHS, ExprResult &RHS,
11478                                           BinaryOperator::Opcode Opc){
11479   Expr *Literal;
11480   Expr *Other;
11481   if (isObjCObjectLiteral(LHS)) {
11482     Literal = LHS.get();
11483     Other = RHS.get();
11484   } else {
11485     Literal = RHS.get();
11486     Other = LHS.get();
11487   }
11488 
11489   // Don't warn on comparisons against nil.
11490   Other = Other->IgnoreParenCasts();
11491   if (Other->isNullPointerConstant(S.getASTContext(),
11492                                    Expr::NPC_ValueDependentIsNotNull))
11493     return;
11494 
11495   // This should be kept in sync with warn_objc_literal_comparison.
11496   // LK_String should always be after the other literals, since it has its own
11497   // warning flag.
11498   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11499   assert(LiteralKind != Sema::LK_Block);
11500   if (LiteralKind == Sema::LK_None) {
11501     llvm_unreachable("Unknown Objective-C object literal kind");
11502   }
11503 
11504   if (LiteralKind == Sema::LK_String)
11505     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11506       << Literal->getSourceRange();
11507   else
11508     S.Diag(Loc, diag::warn_objc_literal_comparison)
11509       << LiteralKind << Literal->getSourceRange();
11510 
11511   if (BinaryOperator::isEqualityOp(Opc) &&
11512       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11513     SourceLocation Start = LHS.get()->getBeginLoc();
11514     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11515     CharSourceRange OpRange =
11516       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11517 
11518     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11519       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11520       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11521       << FixItHint::CreateInsertion(End, "]");
11522   }
11523 }
11524 
11525 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11526 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11527                                            ExprResult &RHS, SourceLocation Loc,
11528                                            BinaryOperatorKind Opc) {
11529   // Check that left hand side is !something.
11530   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11531   if (!UO || UO->getOpcode() != UO_LNot) return;
11532 
11533   // Only check if the right hand side is non-bool arithmetic type.
11534   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11535 
11536   // Make sure that the something in !something is not bool.
11537   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11538   if (SubExpr->isKnownToHaveBooleanValue()) return;
11539 
11540   // Emit warning.
11541   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11542   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11543       << Loc << IsBitwiseOp;
11544 
11545   // First note suggest !(x < y)
11546   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11547   SourceLocation FirstClose = RHS.get()->getEndLoc();
11548   FirstClose = S.getLocForEndOfToken(FirstClose);
11549   if (FirstClose.isInvalid())
11550     FirstOpen = SourceLocation();
11551   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11552       << IsBitwiseOp
11553       << FixItHint::CreateInsertion(FirstOpen, "(")
11554       << FixItHint::CreateInsertion(FirstClose, ")");
11555 
11556   // Second note suggests (!x) < y
11557   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11558   SourceLocation SecondClose = LHS.get()->getEndLoc();
11559   SecondClose = S.getLocForEndOfToken(SecondClose);
11560   if (SecondClose.isInvalid())
11561     SecondOpen = SourceLocation();
11562   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11563       << FixItHint::CreateInsertion(SecondOpen, "(")
11564       << FixItHint::CreateInsertion(SecondClose, ")");
11565 }
11566 
11567 // Returns true if E refers to a non-weak array.
11568 static bool checkForArray(const Expr *E) {
11569   const ValueDecl *D = nullptr;
11570   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11571     D = DR->getDecl();
11572   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11573     if (Mem->isImplicitAccess())
11574       D = Mem->getMemberDecl();
11575   }
11576   if (!D)
11577     return false;
11578   return D->getType()->isArrayType() && !D->isWeak();
11579 }
11580 
11581 /// Diagnose some forms of syntactically-obvious tautological comparison.
11582 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11583                                            Expr *LHS, Expr *RHS,
11584                                            BinaryOperatorKind Opc) {
11585   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11586   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11587 
11588   QualType LHSType = LHS->getType();
11589   QualType RHSType = RHS->getType();
11590   if (LHSType->hasFloatingRepresentation() ||
11591       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11592       S.inTemplateInstantiation())
11593     return;
11594 
11595   // Comparisons between two array types are ill-formed for operator<=>, so
11596   // we shouldn't emit any additional warnings about it.
11597   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11598     return;
11599 
11600   // For non-floating point types, check for self-comparisons of the form
11601   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11602   // often indicate logic errors in the program.
11603   //
11604   // NOTE: Don't warn about comparison expressions resulting from macro
11605   // expansion. Also don't warn about comparisons which are only self
11606   // comparisons within a template instantiation. The warnings should catch
11607   // obvious cases in the definition of the template anyways. The idea is to
11608   // warn when the typed comparison operator will always evaluate to the same
11609   // result.
11610 
11611   // Used for indexing into %select in warn_comparison_always
11612   enum {
11613     AlwaysConstant,
11614     AlwaysTrue,
11615     AlwaysFalse,
11616     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11617   };
11618 
11619   // C++2a [depr.array.comp]:
11620   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11621   //   operands of array type are deprecated.
11622   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11623       RHSStripped->getType()->isArrayType()) {
11624     S.Diag(Loc, diag::warn_depr_array_comparison)
11625         << LHS->getSourceRange() << RHS->getSourceRange()
11626         << LHSStripped->getType() << RHSStripped->getType();
11627     // Carry on to produce the tautological comparison warning, if this
11628     // expression is potentially-evaluated, we can resolve the array to a
11629     // non-weak declaration, and so on.
11630   }
11631 
11632   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11633     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11634       unsigned Result;
11635       switch (Opc) {
11636       case BO_EQ:
11637       case BO_LE:
11638       case BO_GE:
11639         Result = AlwaysTrue;
11640         break;
11641       case BO_NE:
11642       case BO_LT:
11643       case BO_GT:
11644         Result = AlwaysFalse;
11645         break;
11646       case BO_Cmp:
11647         Result = AlwaysEqual;
11648         break;
11649       default:
11650         Result = AlwaysConstant;
11651         break;
11652       }
11653       S.DiagRuntimeBehavior(Loc, nullptr,
11654                             S.PDiag(diag::warn_comparison_always)
11655                                 << 0 /*self-comparison*/
11656                                 << Result);
11657     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11658       // What is it always going to evaluate to?
11659       unsigned Result;
11660       switch (Opc) {
11661       case BO_EQ: // e.g. array1 == array2
11662         Result = AlwaysFalse;
11663         break;
11664       case BO_NE: // e.g. array1 != array2
11665         Result = AlwaysTrue;
11666         break;
11667       default: // e.g. array1 <= array2
11668         // The best we can say is 'a constant'
11669         Result = AlwaysConstant;
11670         break;
11671       }
11672       S.DiagRuntimeBehavior(Loc, nullptr,
11673                             S.PDiag(diag::warn_comparison_always)
11674                                 << 1 /*array comparison*/
11675                                 << Result);
11676     }
11677   }
11678 
11679   if (isa<CastExpr>(LHSStripped))
11680     LHSStripped = LHSStripped->IgnoreParenCasts();
11681   if (isa<CastExpr>(RHSStripped))
11682     RHSStripped = RHSStripped->IgnoreParenCasts();
11683 
11684   // Warn about comparisons against a string constant (unless the other
11685   // operand is null); the user probably wants string comparison function.
11686   Expr *LiteralString = nullptr;
11687   Expr *LiteralStringStripped = nullptr;
11688   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11689       !RHSStripped->isNullPointerConstant(S.Context,
11690                                           Expr::NPC_ValueDependentIsNull)) {
11691     LiteralString = LHS;
11692     LiteralStringStripped = LHSStripped;
11693   } else if ((isa<StringLiteral>(RHSStripped) ||
11694               isa<ObjCEncodeExpr>(RHSStripped)) &&
11695              !LHSStripped->isNullPointerConstant(S.Context,
11696                                           Expr::NPC_ValueDependentIsNull)) {
11697     LiteralString = RHS;
11698     LiteralStringStripped = RHSStripped;
11699   }
11700 
11701   if (LiteralString) {
11702     S.DiagRuntimeBehavior(Loc, nullptr,
11703                           S.PDiag(diag::warn_stringcompare)
11704                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11705                               << LiteralString->getSourceRange());
11706   }
11707 }
11708 
11709 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11710   switch (CK) {
11711   default: {
11712 #ifndef NDEBUG
11713     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11714                  << "\n";
11715 #endif
11716     llvm_unreachable("unhandled cast kind");
11717   }
11718   case CK_UserDefinedConversion:
11719     return ICK_Identity;
11720   case CK_LValueToRValue:
11721     return ICK_Lvalue_To_Rvalue;
11722   case CK_ArrayToPointerDecay:
11723     return ICK_Array_To_Pointer;
11724   case CK_FunctionToPointerDecay:
11725     return ICK_Function_To_Pointer;
11726   case CK_IntegralCast:
11727     return ICK_Integral_Conversion;
11728   case CK_FloatingCast:
11729     return ICK_Floating_Conversion;
11730   case CK_IntegralToFloating:
11731   case CK_FloatingToIntegral:
11732     return ICK_Floating_Integral;
11733   case CK_IntegralComplexCast:
11734   case CK_FloatingComplexCast:
11735   case CK_FloatingComplexToIntegralComplex:
11736   case CK_IntegralComplexToFloatingComplex:
11737     return ICK_Complex_Conversion;
11738   case CK_FloatingComplexToReal:
11739   case CK_FloatingRealToComplex:
11740   case CK_IntegralComplexToReal:
11741   case CK_IntegralRealToComplex:
11742     return ICK_Complex_Real;
11743   }
11744 }
11745 
11746 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11747                                              QualType FromType,
11748                                              SourceLocation Loc) {
11749   // Check for a narrowing implicit conversion.
11750   StandardConversionSequence SCS;
11751   SCS.setAsIdentityConversion();
11752   SCS.setToType(0, FromType);
11753   SCS.setToType(1, ToType);
11754   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11755     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11756 
11757   APValue PreNarrowingValue;
11758   QualType PreNarrowingType;
11759   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11760                                PreNarrowingType,
11761                                /*IgnoreFloatToIntegralConversion*/ true)) {
11762   case NK_Dependent_Narrowing:
11763     // Implicit conversion to a narrower type, but the expression is
11764     // value-dependent so we can't tell whether it's actually narrowing.
11765   case NK_Not_Narrowing:
11766     return false;
11767 
11768   case NK_Constant_Narrowing:
11769     // Implicit conversion to a narrower type, and the value is not a constant
11770     // expression.
11771     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11772         << /*Constant*/ 1
11773         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11774     return true;
11775 
11776   case NK_Variable_Narrowing:
11777     // Implicit conversion to a narrower type, and the value is not a constant
11778     // expression.
11779   case NK_Type_Narrowing:
11780     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11781         << /*Constant*/ 0 << FromType << ToType;
11782     // TODO: It's not a constant expression, but what if the user intended it
11783     // to be? Can we produce notes to help them figure out why it isn't?
11784     return true;
11785   }
11786   llvm_unreachable("unhandled case in switch");
11787 }
11788 
11789 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11790                                                          ExprResult &LHS,
11791                                                          ExprResult &RHS,
11792                                                          SourceLocation Loc) {
11793   QualType LHSType = LHS.get()->getType();
11794   QualType RHSType = RHS.get()->getType();
11795   // Dig out the original argument type and expression before implicit casts
11796   // were applied. These are the types/expressions we need to check the
11797   // [expr.spaceship] requirements against.
11798   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11799   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11800   QualType LHSStrippedType = LHSStripped.get()->getType();
11801   QualType RHSStrippedType = RHSStripped.get()->getType();
11802 
11803   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11804   // other is not, the program is ill-formed.
11805   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11806     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11807     return QualType();
11808   }
11809 
11810   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11811   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11812                     RHSStrippedType->isEnumeralType();
11813   if (NumEnumArgs == 1) {
11814     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11815     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11816     if (OtherTy->hasFloatingRepresentation()) {
11817       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11818       return QualType();
11819     }
11820   }
11821   if (NumEnumArgs == 2) {
11822     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11823     // type E, the operator yields the result of converting the operands
11824     // to the underlying type of E and applying <=> to the converted operands.
11825     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11826       S.InvalidOperands(Loc, LHS, RHS);
11827       return QualType();
11828     }
11829     QualType IntType =
11830         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11831     assert(IntType->isArithmeticType());
11832 
11833     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11834     // promote the boolean type, and all other promotable integer types, to
11835     // avoid this.
11836     if (IntType->isPromotableIntegerType())
11837       IntType = S.Context.getPromotedIntegerType(IntType);
11838 
11839     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11840     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11841     LHSType = RHSType = IntType;
11842   }
11843 
11844   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11845   // usual arithmetic conversions are applied to the operands.
11846   QualType Type =
11847       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11848   if (LHS.isInvalid() || RHS.isInvalid())
11849     return QualType();
11850   if (Type.isNull())
11851     return S.InvalidOperands(Loc, LHS, RHS);
11852 
11853   Optional<ComparisonCategoryType> CCT =
11854       getComparisonCategoryForBuiltinCmp(Type);
11855   if (!CCT)
11856     return S.InvalidOperands(Loc, LHS, RHS);
11857 
11858   bool HasNarrowing = checkThreeWayNarrowingConversion(
11859       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11860   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11861                                                    RHS.get()->getBeginLoc());
11862   if (HasNarrowing)
11863     return QualType();
11864 
11865   assert(!Type.isNull() && "composite type for <=> has not been set");
11866 
11867   return S.CheckComparisonCategoryType(
11868       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11869 }
11870 
11871 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11872                                                  ExprResult &RHS,
11873                                                  SourceLocation Loc,
11874                                                  BinaryOperatorKind Opc) {
11875   if (Opc == BO_Cmp)
11876     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11877 
11878   // C99 6.5.8p3 / C99 6.5.9p4
11879   QualType Type =
11880       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11881   if (LHS.isInvalid() || RHS.isInvalid())
11882     return QualType();
11883   if (Type.isNull())
11884     return S.InvalidOperands(Loc, LHS, RHS);
11885   assert(Type->isArithmeticType() || Type->isEnumeralType());
11886 
11887   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11888     return S.InvalidOperands(Loc, LHS, RHS);
11889 
11890   // Check for comparisons of floating point operands using != and ==.
11891   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11892     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11893 
11894   // The result of comparisons is 'bool' in C++, 'int' in C.
11895   return S.Context.getLogicalOperationType();
11896 }
11897 
11898 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11899   if (!NullE.get()->getType()->isAnyPointerType())
11900     return;
11901   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11902   if (!E.get()->getType()->isAnyPointerType() &&
11903       E.get()->isNullPointerConstant(Context,
11904                                      Expr::NPC_ValueDependentIsNotNull) ==
11905         Expr::NPCK_ZeroExpression) {
11906     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11907       if (CL->getValue() == 0)
11908         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11909             << NullValue
11910             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11911                                             NullValue ? "NULL" : "(void *)0");
11912     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11913         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11914         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11915         if (T == Context.CharTy)
11916           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11917               << NullValue
11918               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11919                                               NullValue ? "NULL" : "(void *)0");
11920       }
11921   }
11922 }
11923 
11924 // C99 6.5.8, C++ [expr.rel]
11925 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11926                                     SourceLocation Loc,
11927                                     BinaryOperatorKind Opc) {
11928   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11929   bool IsThreeWay = Opc == BO_Cmp;
11930   bool IsOrdered = IsRelational || IsThreeWay;
11931   auto IsAnyPointerType = [](ExprResult E) {
11932     QualType Ty = E.get()->getType();
11933     return Ty->isPointerType() || Ty->isMemberPointerType();
11934   };
11935 
11936   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11937   // type, array-to-pointer, ..., conversions are performed on both operands to
11938   // bring them to their composite type.
11939   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11940   // any type-related checks.
11941   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11942     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11943     if (LHS.isInvalid())
11944       return QualType();
11945     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11946     if (RHS.isInvalid())
11947       return QualType();
11948   } else {
11949     LHS = DefaultLvalueConversion(LHS.get());
11950     if (LHS.isInvalid())
11951       return QualType();
11952     RHS = DefaultLvalueConversion(RHS.get());
11953     if (RHS.isInvalid())
11954       return QualType();
11955   }
11956 
11957   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11958   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11959     CheckPtrComparisonWithNullChar(LHS, RHS);
11960     CheckPtrComparisonWithNullChar(RHS, LHS);
11961   }
11962 
11963   // Handle vector comparisons separately.
11964   if (LHS.get()->getType()->isVectorType() ||
11965       RHS.get()->getType()->isVectorType())
11966     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11967 
11968   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11969   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11970 
11971   QualType LHSType = LHS.get()->getType();
11972   QualType RHSType = RHS.get()->getType();
11973   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11974       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11975     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11976 
11977   const Expr::NullPointerConstantKind LHSNullKind =
11978       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11979   const Expr::NullPointerConstantKind RHSNullKind =
11980       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11981   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11982   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11983 
11984   auto computeResultTy = [&]() {
11985     if (Opc != BO_Cmp)
11986       return Context.getLogicalOperationType();
11987     assert(getLangOpts().CPlusPlus);
11988     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11989 
11990     QualType CompositeTy = LHS.get()->getType();
11991     assert(!CompositeTy->isReferenceType());
11992 
11993     Optional<ComparisonCategoryType> CCT =
11994         getComparisonCategoryForBuiltinCmp(CompositeTy);
11995     if (!CCT)
11996       return InvalidOperands(Loc, LHS, RHS);
11997 
11998     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11999       // P0946R0: Comparisons between a null pointer constant and an object
12000       // pointer result in std::strong_equality, which is ill-formed under
12001       // P1959R0.
12002       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12003           << (LHSIsNull ? LHS.get()->getSourceRange()
12004                         : RHS.get()->getSourceRange());
12005       return QualType();
12006     }
12007 
12008     return CheckComparisonCategoryType(
12009         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12010   };
12011 
12012   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12013     bool IsEquality = Opc == BO_EQ;
12014     if (RHSIsNull)
12015       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12016                                    RHS.get()->getSourceRange());
12017     else
12018       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12019                                    LHS.get()->getSourceRange());
12020   }
12021 
12022   if (IsOrdered && LHSType->isFunctionPointerType() &&
12023       RHSType->isFunctionPointerType()) {
12024     // Valid unless a relational comparison of function pointers
12025     bool IsError = Opc == BO_Cmp;
12026     auto DiagID =
12027         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12028         : getLangOpts().CPlusPlus
12029             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12030             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12031     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12032                       << RHS.get()->getSourceRange();
12033     if (IsError)
12034       return QualType();
12035   }
12036 
12037   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12038       (RHSType->isIntegerType() && !RHSIsNull)) {
12039     // Skip normal pointer conversion checks in this case; we have better
12040     // diagnostics for this below.
12041   } else if (getLangOpts().CPlusPlus) {
12042     // Equality comparison of a function pointer to a void pointer is invalid,
12043     // but we allow it as an extension.
12044     // FIXME: If we really want to allow this, should it be part of composite
12045     // pointer type computation so it works in conditionals too?
12046     if (!IsOrdered &&
12047         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12048          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12049       // This is a gcc extension compatibility comparison.
12050       // In a SFINAE context, we treat this as a hard error to maintain
12051       // conformance with the C++ standard.
12052       diagnoseFunctionPointerToVoidComparison(
12053           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12054 
12055       if (isSFINAEContext())
12056         return QualType();
12057 
12058       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12059       return computeResultTy();
12060     }
12061 
12062     // C++ [expr.eq]p2:
12063     //   If at least one operand is a pointer [...] bring them to their
12064     //   composite pointer type.
12065     // C++ [expr.spaceship]p6
12066     //  If at least one of the operands is of pointer type, [...] bring them
12067     //  to their composite pointer type.
12068     // C++ [expr.rel]p2:
12069     //   If both operands are pointers, [...] bring them to their composite
12070     //   pointer type.
12071     // For <=>, the only valid non-pointer types are arrays and functions, and
12072     // we already decayed those, so this is really the same as the relational
12073     // comparison rule.
12074     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12075             (IsOrdered ? 2 : 1) &&
12076         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12077                                          RHSType->isObjCObjectPointerType()))) {
12078       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12079         return QualType();
12080       return computeResultTy();
12081     }
12082   } else if (LHSType->isPointerType() &&
12083              RHSType->isPointerType()) { // C99 6.5.8p2
12084     // All of the following pointer-related warnings are GCC extensions, except
12085     // when handling null pointer constants.
12086     QualType LCanPointeeTy =
12087       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12088     QualType RCanPointeeTy =
12089       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12090 
12091     // C99 6.5.9p2 and C99 6.5.8p2
12092     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12093                                    RCanPointeeTy.getUnqualifiedType())) {
12094       if (IsRelational) {
12095         // Pointers both need to point to complete or incomplete types
12096         if ((LCanPointeeTy->isIncompleteType() !=
12097              RCanPointeeTy->isIncompleteType()) &&
12098             !getLangOpts().C11) {
12099           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12100               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12101               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12102               << RCanPointeeTy->isIncompleteType();
12103         }
12104       }
12105     } else if (!IsRelational &&
12106                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12107       // Valid unless comparison between non-null pointer and function pointer
12108       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12109           && !LHSIsNull && !RHSIsNull)
12110         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12111                                                 /*isError*/false);
12112     } else {
12113       // Invalid
12114       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12115     }
12116     if (LCanPointeeTy != RCanPointeeTy) {
12117       // Treat NULL constant as a special case in OpenCL.
12118       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12119         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12120           Diag(Loc,
12121                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12122               << LHSType << RHSType << 0 /* comparison */
12123               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12124         }
12125       }
12126       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12127       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12128       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12129                                                : CK_BitCast;
12130       if (LHSIsNull && !RHSIsNull)
12131         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12132       else
12133         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12134     }
12135     return computeResultTy();
12136   }
12137 
12138   if (getLangOpts().CPlusPlus) {
12139     // C++ [expr.eq]p4:
12140     //   Two operands of type std::nullptr_t or one operand of type
12141     //   std::nullptr_t and the other a null pointer constant compare equal.
12142     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12143       if (LHSType->isNullPtrType()) {
12144         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12145         return computeResultTy();
12146       }
12147       if (RHSType->isNullPtrType()) {
12148         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12149         return computeResultTy();
12150       }
12151     }
12152 
12153     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12154     // These aren't covered by the composite pointer type rules.
12155     if (!IsOrdered && RHSType->isNullPtrType() &&
12156         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12157       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12158       return computeResultTy();
12159     }
12160     if (!IsOrdered && LHSType->isNullPtrType() &&
12161         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12162       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12163       return computeResultTy();
12164     }
12165 
12166     if (IsRelational &&
12167         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12168          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12169       // HACK: Relational comparison of nullptr_t against a pointer type is
12170       // invalid per DR583, but we allow it within std::less<> and friends,
12171       // since otherwise common uses of it break.
12172       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12173       // friends to have std::nullptr_t overload candidates.
12174       DeclContext *DC = CurContext;
12175       if (isa<FunctionDecl>(DC))
12176         DC = DC->getParent();
12177       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12178         if (CTSD->isInStdNamespace() &&
12179             llvm::StringSwitch<bool>(CTSD->getName())
12180                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12181                 .Default(false)) {
12182           if (RHSType->isNullPtrType())
12183             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12184           else
12185             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12186           return computeResultTy();
12187         }
12188       }
12189     }
12190 
12191     // C++ [expr.eq]p2:
12192     //   If at least one operand is a pointer to member, [...] bring them to
12193     //   their composite pointer type.
12194     if (!IsOrdered &&
12195         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12196       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12197         return QualType();
12198       else
12199         return computeResultTy();
12200     }
12201   }
12202 
12203   // Handle block pointer types.
12204   if (!IsOrdered && LHSType->isBlockPointerType() &&
12205       RHSType->isBlockPointerType()) {
12206     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12207     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12208 
12209     if (!LHSIsNull && !RHSIsNull &&
12210         !Context.typesAreCompatible(lpointee, rpointee)) {
12211       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12212         << LHSType << RHSType << LHS.get()->getSourceRange()
12213         << RHS.get()->getSourceRange();
12214     }
12215     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12216     return computeResultTy();
12217   }
12218 
12219   // Allow block pointers to be compared with null pointer constants.
12220   if (!IsOrdered
12221       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12222           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12223     if (!LHSIsNull && !RHSIsNull) {
12224       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12225              ->getPointeeType()->isVoidType())
12226             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12227                 ->getPointeeType()->isVoidType())))
12228         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12229           << LHSType << RHSType << LHS.get()->getSourceRange()
12230           << RHS.get()->getSourceRange();
12231     }
12232     if (LHSIsNull && !RHSIsNull)
12233       LHS = ImpCastExprToType(LHS.get(), RHSType,
12234                               RHSType->isPointerType() ? CK_BitCast
12235                                 : CK_AnyPointerToBlockPointerCast);
12236     else
12237       RHS = ImpCastExprToType(RHS.get(), LHSType,
12238                               LHSType->isPointerType() ? CK_BitCast
12239                                 : CK_AnyPointerToBlockPointerCast);
12240     return computeResultTy();
12241   }
12242 
12243   if (LHSType->isObjCObjectPointerType() ||
12244       RHSType->isObjCObjectPointerType()) {
12245     const PointerType *LPT = LHSType->getAs<PointerType>();
12246     const PointerType *RPT = RHSType->getAs<PointerType>();
12247     if (LPT || RPT) {
12248       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12249       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12250 
12251       if (!LPtrToVoid && !RPtrToVoid &&
12252           !Context.typesAreCompatible(LHSType, RHSType)) {
12253         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12254                                           /*isError*/false);
12255       }
12256       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12257       // the RHS, but we have test coverage for this behavior.
12258       // FIXME: Consider using convertPointersToCompositeType in C++.
12259       if (LHSIsNull && !RHSIsNull) {
12260         Expr *E = LHS.get();
12261         if (getLangOpts().ObjCAutoRefCount)
12262           CheckObjCConversion(SourceRange(), RHSType, E,
12263                               CCK_ImplicitConversion);
12264         LHS = ImpCastExprToType(E, RHSType,
12265                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12266       }
12267       else {
12268         Expr *E = RHS.get();
12269         if (getLangOpts().ObjCAutoRefCount)
12270           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12271                               /*Diagnose=*/true,
12272                               /*DiagnoseCFAudited=*/false, Opc);
12273         RHS = ImpCastExprToType(E, LHSType,
12274                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12275       }
12276       return computeResultTy();
12277     }
12278     if (LHSType->isObjCObjectPointerType() &&
12279         RHSType->isObjCObjectPointerType()) {
12280       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12281         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12282                                           /*isError*/false);
12283       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12284         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12285 
12286       if (LHSIsNull && !RHSIsNull)
12287         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12288       else
12289         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12290       return computeResultTy();
12291     }
12292 
12293     if (!IsOrdered && LHSType->isBlockPointerType() &&
12294         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12295       LHS = ImpCastExprToType(LHS.get(), RHSType,
12296                               CK_BlockPointerToObjCPointerCast);
12297       return computeResultTy();
12298     } else if (!IsOrdered &&
12299                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12300                RHSType->isBlockPointerType()) {
12301       RHS = ImpCastExprToType(RHS.get(), LHSType,
12302                               CK_BlockPointerToObjCPointerCast);
12303       return computeResultTy();
12304     }
12305   }
12306   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12307       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12308     unsigned DiagID = 0;
12309     bool isError = false;
12310     if (LangOpts.DebuggerSupport) {
12311       // Under a debugger, allow the comparison of pointers to integers,
12312       // since users tend to want to compare addresses.
12313     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12314                (RHSIsNull && RHSType->isIntegerType())) {
12315       if (IsOrdered) {
12316         isError = getLangOpts().CPlusPlus;
12317         DiagID =
12318           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12319                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12320       }
12321     } else if (getLangOpts().CPlusPlus) {
12322       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12323       isError = true;
12324     } else if (IsOrdered)
12325       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12326     else
12327       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12328 
12329     if (DiagID) {
12330       Diag(Loc, DiagID)
12331         << LHSType << RHSType << LHS.get()->getSourceRange()
12332         << RHS.get()->getSourceRange();
12333       if (isError)
12334         return QualType();
12335     }
12336 
12337     if (LHSType->isIntegerType())
12338       LHS = ImpCastExprToType(LHS.get(), RHSType,
12339                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12340     else
12341       RHS = ImpCastExprToType(RHS.get(), LHSType,
12342                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12343     return computeResultTy();
12344   }
12345 
12346   // Handle block pointers.
12347   if (!IsOrdered && RHSIsNull
12348       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12349     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12350     return computeResultTy();
12351   }
12352   if (!IsOrdered && LHSIsNull
12353       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12354     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12355     return computeResultTy();
12356   }
12357 
12358   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12359     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12360       return computeResultTy();
12361     }
12362 
12363     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12364       return computeResultTy();
12365     }
12366 
12367     if (LHSIsNull && RHSType->isQueueT()) {
12368       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12369       return computeResultTy();
12370     }
12371 
12372     if (LHSType->isQueueT() && RHSIsNull) {
12373       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12374       return computeResultTy();
12375     }
12376   }
12377 
12378   return InvalidOperands(Loc, LHS, RHS);
12379 }
12380 
12381 // Return a signed ext_vector_type that is of identical size and number of
12382 // elements. For floating point vectors, return an integer type of identical
12383 // size and number of elements. In the non ext_vector_type case, search from
12384 // the largest type to the smallest type to avoid cases where long long == long,
12385 // where long gets picked over long long.
12386 QualType Sema::GetSignedVectorType(QualType V) {
12387   const VectorType *VTy = V->castAs<VectorType>();
12388   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12389 
12390   if (isa<ExtVectorType>(VTy)) {
12391     if (TypeSize == Context.getTypeSize(Context.CharTy))
12392       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12393     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12394       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12395     if (TypeSize == Context.getTypeSize(Context.IntTy))
12396       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12397     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12398       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12399     if (TypeSize == Context.getTypeSize(Context.LongTy))
12400       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12401     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12402            "Unhandled vector element size in vector compare");
12403     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12404   }
12405 
12406   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12407     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12408                                  VectorType::GenericVector);
12409   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12410     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12411                                  VectorType::GenericVector);
12412   if (TypeSize == Context.getTypeSize(Context.LongTy))
12413     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12414                                  VectorType::GenericVector);
12415   if (TypeSize == Context.getTypeSize(Context.IntTy))
12416     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12417                                  VectorType::GenericVector);
12418   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12419     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12420                                  VectorType::GenericVector);
12421   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12422          "Unhandled vector element size in vector compare");
12423   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12424                                VectorType::GenericVector);
12425 }
12426 
12427 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12428 /// operates on extended vector types.  Instead of producing an IntTy result,
12429 /// like a scalar comparison, a vector comparison produces a vector of integer
12430 /// types.
12431 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12432                                           SourceLocation Loc,
12433                                           BinaryOperatorKind Opc) {
12434   if (Opc == BO_Cmp) {
12435     Diag(Loc, diag::err_three_way_vector_comparison);
12436     return QualType();
12437   }
12438 
12439   // Check to make sure we're operating on vectors of the same type and width,
12440   // Allowing one side to be a scalar of element type.
12441   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12442                               /*AllowBothBool*/true,
12443                               /*AllowBoolConversions*/getLangOpts().ZVector);
12444   if (vType.isNull())
12445     return vType;
12446 
12447   QualType LHSType = LHS.get()->getType();
12448 
12449   // Determine the return type of a vector compare. By default clang will return
12450   // a scalar for all vector compares except vector bool and vector pixel.
12451   // With the gcc compiler we will always return a vector type and with the xl
12452   // compiler we will always return a scalar type. This switch allows choosing
12453   // which behavior is prefered.
12454   if (getLangOpts().AltiVec) {
12455     switch (getLangOpts().getAltivecSrcCompat()) {
12456     case LangOptions::AltivecSrcCompatKind::Mixed:
12457       // If AltiVec, the comparison results in a numeric type, i.e.
12458       // bool for C++, int for C
12459       if (vType->castAs<VectorType>()->getVectorKind() ==
12460           VectorType::AltiVecVector)
12461         return Context.getLogicalOperationType();
12462       else
12463         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12464       break;
12465     case LangOptions::AltivecSrcCompatKind::GCC:
12466       // For GCC we always return the vector type.
12467       break;
12468     case LangOptions::AltivecSrcCompatKind::XL:
12469       return Context.getLogicalOperationType();
12470       break;
12471     }
12472   }
12473 
12474   // For non-floating point types, check for self-comparisons of the form
12475   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12476   // often indicate logic errors in the program.
12477   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12478 
12479   // Check for comparisons of floating point operands using != and ==.
12480   if (BinaryOperator::isEqualityOp(Opc) &&
12481       LHSType->hasFloatingRepresentation()) {
12482     assert(RHS.get()->getType()->hasFloatingRepresentation());
12483     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12484   }
12485 
12486   // Return a signed type for the vector.
12487   return GetSignedVectorType(vType);
12488 }
12489 
12490 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12491                                     const ExprResult &XorRHS,
12492                                     const SourceLocation Loc) {
12493   // Do not diagnose macros.
12494   if (Loc.isMacroID())
12495     return;
12496 
12497   // Do not diagnose if both LHS and RHS are macros.
12498   if (XorLHS.get()->getExprLoc().isMacroID() &&
12499       XorRHS.get()->getExprLoc().isMacroID())
12500     return;
12501 
12502   bool Negative = false;
12503   bool ExplicitPlus = false;
12504   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12505   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12506 
12507   if (!LHSInt)
12508     return;
12509   if (!RHSInt) {
12510     // Check negative literals.
12511     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12512       UnaryOperatorKind Opc = UO->getOpcode();
12513       if (Opc != UO_Minus && Opc != UO_Plus)
12514         return;
12515       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12516       if (!RHSInt)
12517         return;
12518       Negative = (Opc == UO_Minus);
12519       ExplicitPlus = !Negative;
12520     } else {
12521       return;
12522     }
12523   }
12524 
12525   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12526   llvm::APInt RightSideValue = RHSInt->getValue();
12527   if (LeftSideValue != 2 && LeftSideValue != 10)
12528     return;
12529 
12530   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12531     return;
12532 
12533   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12534       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12535   llvm::StringRef ExprStr =
12536       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12537 
12538   CharSourceRange XorRange =
12539       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12540   llvm::StringRef XorStr =
12541       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12542   // Do not diagnose if xor keyword/macro is used.
12543   if (XorStr == "xor")
12544     return;
12545 
12546   std::string LHSStr = std::string(Lexer::getSourceText(
12547       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12548       S.getSourceManager(), S.getLangOpts()));
12549   std::string RHSStr = std::string(Lexer::getSourceText(
12550       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12551       S.getSourceManager(), S.getLangOpts()));
12552 
12553   if (Negative) {
12554     RightSideValue = -RightSideValue;
12555     RHSStr = "-" + RHSStr;
12556   } else if (ExplicitPlus) {
12557     RHSStr = "+" + RHSStr;
12558   }
12559 
12560   StringRef LHSStrRef = LHSStr;
12561   StringRef RHSStrRef = RHSStr;
12562   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12563   // literals.
12564   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12565       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12566       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12567       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12568       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12569       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12570       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12571     return;
12572 
12573   bool SuggestXor =
12574       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12575   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12576   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12577   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12578     std::string SuggestedExpr = "1 << " + RHSStr;
12579     bool Overflow = false;
12580     llvm::APInt One = (LeftSideValue - 1);
12581     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12582     if (Overflow) {
12583       if (RightSideIntValue < 64)
12584         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12585             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12586             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12587       else if (RightSideIntValue == 64)
12588         S.Diag(Loc, diag::warn_xor_used_as_pow)
12589             << ExprStr << toString(XorValue, 10, true);
12590       else
12591         return;
12592     } else {
12593       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12594           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12595           << toString(PowValue, 10, true)
12596           << FixItHint::CreateReplacement(
12597                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12598     }
12599 
12600     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12601         << ("0x2 ^ " + RHSStr) << SuggestXor;
12602   } else if (LeftSideValue == 10) {
12603     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12604     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12605         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12606         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12607     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12608         << ("0xA ^ " + RHSStr) << SuggestXor;
12609   }
12610 }
12611 
12612 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12613                                           SourceLocation Loc) {
12614   // Ensure that either both operands are of the same vector type, or
12615   // one operand is of a vector type and the other is of its element type.
12616   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12617                                        /*AllowBothBool*/true,
12618                                        /*AllowBoolConversions*/false);
12619   if (vType.isNull())
12620     return InvalidOperands(Loc, LHS, RHS);
12621   if (getLangOpts().OpenCL &&
12622       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12623       vType->hasFloatingRepresentation())
12624     return InvalidOperands(Loc, LHS, RHS);
12625   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12626   //        usage of the logical operators && and || with vectors in C. This
12627   //        check could be notionally dropped.
12628   if (!getLangOpts().CPlusPlus &&
12629       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12630     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12631 
12632   return GetSignedVectorType(LHS.get()->getType());
12633 }
12634 
12635 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12636                                               SourceLocation Loc,
12637                                               bool IsCompAssign) {
12638   if (!IsCompAssign) {
12639     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12640     if (LHS.isInvalid())
12641       return QualType();
12642   }
12643   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12644   if (RHS.isInvalid())
12645     return QualType();
12646 
12647   // For conversion purposes, we ignore any qualifiers.
12648   // For example, "const float" and "float" are equivalent.
12649   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12650   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12651 
12652   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12653   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12654   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12655 
12656   if (Context.hasSameType(LHSType, RHSType))
12657     return LHSType;
12658 
12659   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12660   // case we have to return InvalidOperands.
12661   ExprResult OriginalLHS = LHS;
12662   ExprResult OriginalRHS = RHS;
12663   if (LHSMatType && !RHSMatType) {
12664     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12665     if (!RHS.isInvalid())
12666       return LHSType;
12667 
12668     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12669   }
12670 
12671   if (!LHSMatType && RHSMatType) {
12672     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12673     if (!LHS.isInvalid())
12674       return RHSType;
12675     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12676   }
12677 
12678   return InvalidOperands(Loc, LHS, RHS);
12679 }
12680 
12681 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12682                                            SourceLocation Loc,
12683                                            bool IsCompAssign) {
12684   if (!IsCompAssign) {
12685     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12686     if (LHS.isInvalid())
12687       return QualType();
12688   }
12689   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12690   if (RHS.isInvalid())
12691     return QualType();
12692 
12693   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12694   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12695   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12696 
12697   if (LHSMatType && RHSMatType) {
12698     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12699       return InvalidOperands(Loc, LHS, RHS);
12700 
12701     if (!Context.hasSameType(LHSMatType->getElementType(),
12702                              RHSMatType->getElementType()))
12703       return InvalidOperands(Loc, LHS, RHS);
12704 
12705     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12706                                          LHSMatType->getNumRows(),
12707                                          RHSMatType->getNumColumns());
12708   }
12709   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12710 }
12711 
12712 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12713                                            SourceLocation Loc,
12714                                            BinaryOperatorKind Opc) {
12715   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12716 
12717   bool IsCompAssign =
12718       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12719 
12720   if (LHS.get()->getType()->isVectorType() ||
12721       RHS.get()->getType()->isVectorType()) {
12722     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12723         RHS.get()->getType()->hasIntegerRepresentation())
12724       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12725                         /*AllowBothBool*/true,
12726                         /*AllowBoolConversions*/getLangOpts().ZVector);
12727     return InvalidOperands(Loc, LHS, RHS);
12728   }
12729 
12730   if (Opc == BO_And)
12731     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12732 
12733   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12734       RHS.get()->getType()->hasFloatingRepresentation())
12735     return InvalidOperands(Loc, LHS, RHS);
12736 
12737   ExprResult LHSResult = LHS, RHSResult = RHS;
12738   QualType compType = UsualArithmeticConversions(
12739       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12740   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12741     return QualType();
12742   LHS = LHSResult.get();
12743   RHS = RHSResult.get();
12744 
12745   if (Opc == BO_Xor)
12746     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12747 
12748   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12749     return compType;
12750   return InvalidOperands(Loc, LHS, RHS);
12751 }
12752 
12753 // C99 6.5.[13,14]
12754 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12755                                            SourceLocation Loc,
12756                                            BinaryOperatorKind Opc) {
12757   // Check vector operands differently.
12758   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12759     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12760 
12761   bool EnumConstantInBoolContext = false;
12762   for (const ExprResult &HS : {LHS, RHS}) {
12763     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12764       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12765       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12766         EnumConstantInBoolContext = true;
12767     }
12768   }
12769 
12770   if (EnumConstantInBoolContext)
12771     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12772 
12773   // Diagnose cases where the user write a logical and/or but probably meant a
12774   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12775   // is a constant.
12776   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12777       !LHS.get()->getType()->isBooleanType() &&
12778       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12779       // Don't warn in macros or template instantiations.
12780       !Loc.isMacroID() && !inTemplateInstantiation()) {
12781     // If the RHS can be constant folded, and if it constant folds to something
12782     // that isn't 0 or 1 (which indicate a potential logical operation that
12783     // happened to fold to true/false) then warn.
12784     // Parens on the RHS are ignored.
12785     Expr::EvalResult EVResult;
12786     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12787       llvm::APSInt Result = EVResult.Val.getInt();
12788       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12789            !RHS.get()->getExprLoc().isMacroID()) ||
12790           (Result != 0 && Result != 1)) {
12791         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12792           << RHS.get()->getSourceRange()
12793           << (Opc == BO_LAnd ? "&&" : "||");
12794         // Suggest replacing the logical operator with the bitwise version
12795         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12796             << (Opc == BO_LAnd ? "&" : "|")
12797             << FixItHint::CreateReplacement(SourceRange(
12798                                                  Loc, getLocForEndOfToken(Loc)),
12799                                             Opc == BO_LAnd ? "&" : "|");
12800         if (Opc == BO_LAnd)
12801           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12802           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12803               << FixItHint::CreateRemoval(
12804                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12805                                  RHS.get()->getEndLoc()));
12806       }
12807     }
12808   }
12809 
12810   if (!Context.getLangOpts().CPlusPlus) {
12811     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12812     // not operate on the built-in scalar and vector float types.
12813     if (Context.getLangOpts().OpenCL &&
12814         Context.getLangOpts().OpenCLVersion < 120) {
12815       if (LHS.get()->getType()->isFloatingType() ||
12816           RHS.get()->getType()->isFloatingType())
12817         return InvalidOperands(Loc, LHS, RHS);
12818     }
12819 
12820     LHS = UsualUnaryConversions(LHS.get());
12821     if (LHS.isInvalid())
12822       return QualType();
12823 
12824     RHS = UsualUnaryConversions(RHS.get());
12825     if (RHS.isInvalid())
12826       return QualType();
12827 
12828     if (!LHS.get()->getType()->isScalarType() ||
12829         !RHS.get()->getType()->isScalarType())
12830       return InvalidOperands(Loc, LHS, RHS);
12831 
12832     return Context.IntTy;
12833   }
12834 
12835   // The following is safe because we only use this method for
12836   // non-overloadable operands.
12837 
12838   // C++ [expr.log.and]p1
12839   // C++ [expr.log.or]p1
12840   // The operands are both contextually converted to type bool.
12841   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12842   if (LHSRes.isInvalid())
12843     return InvalidOperands(Loc, LHS, RHS);
12844   LHS = LHSRes;
12845 
12846   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12847   if (RHSRes.isInvalid())
12848     return InvalidOperands(Loc, LHS, RHS);
12849   RHS = RHSRes;
12850 
12851   // C++ [expr.log.and]p2
12852   // C++ [expr.log.or]p2
12853   // The result is a bool.
12854   return Context.BoolTy;
12855 }
12856 
12857 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12858   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12859   if (!ME) return false;
12860   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12861   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12862       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12863   if (!Base) return false;
12864   return Base->getMethodDecl() != nullptr;
12865 }
12866 
12867 /// Is the given expression (which must be 'const') a reference to a
12868 /// variable which was originally non-const, but which has become
12869 /// 'const' due to being captured within a block?
12870 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12871 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12872   assert(E->isLValue() && E->getType().isConstQualified());
12873   E = E->IgnoreParens();
12874 
12875   // Must be a reference to a declaration from an enclosing scope.
12876   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12877   if (!DRE) return NCCK_None;
12878   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12879 
12880   // The declaration must be a variable which is not declared 'const'.
12881   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12882   if (!var) return NCCK_None;
12883   if (var->getType().isConstQualified()) return NCCK_None;
12884   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12885 
12886   // Decide whether the first capture was for a block or a lambda.
12887   DeclContext *DC = S.CurContext, *Prev = nullptr;
12888   // Decide whether the first capture was for a block or a lambda.
12889   while (DC) {
12890     // For init-capture, it is possible that the variable belongs to the
12891     // template pattern of the current context.
12892     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12893       if (var->isInitCapture() &&
12894           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12895         break;
12896     if (DC == var->getDeclContext())
12897       break;
12898     Prev = DC;
12899     DC = DC->getParent();
12900   }
12901   // Unless we have an init-capture, we've gone one step too far.
12902   if (!var->isInitCapture())
12903     DC = Prev;
12904   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12905 }
12906 
12907 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12908   Ty = Ty.getNonReferenceType();
12909   if (IsDereference && Ty->isPointerType())
12910     Ty = Ty->getPointeeType();
12911   return !Ty.isConstQualified();
12912 }
12913 
12914 // Update err_typecheck_assign_const and note_typecheck_assign_const
12915 // when this enum is changed.
12916 enum {
12917   ConstFunction,
12918   ConstVariable,
12919   ConstMember,
12920   ConstMethod,
12921   NestedConstMember,
12922   ConstUnknown,  // Keep as last element
12923 };
12924 
12925 /// Emit the "read-only variable not assignable" error and print notes to give
12926 /// more information about why the variable is not assignable, such as pointing
12927 /// to the declaration of a const variable, showing that a method is const, or
12928 /// that the function is returning a const reference.
12929 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12930                                     SourceLocation Loc) {
12931   SourceRange ExprRange = E->getSourceRange();
12932 
12933   // Only emit one error on the first const found.  All other consts will emit
12934   // a note to the error.
12935   bool DiagnosticEmitted = false;
12936 
12937   // Track if the current expression is the result of a dereference, and if the
12938   // next checked expression is the result of a dereference.
12939   bool IsDereference = false;
12940   bool NextIsDereference = false;
12941 
12942   // Loop to process MemberExpr chains.
12943   while (true) {
12944     IsDereference = NextIsDereference;
12945 
12946     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12947     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12948       NextIsDereference = ME->isArrow();
12949       const ValueDecl *VD = ME->getMemberDecl();
12950       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12951         // Mutable fields can be modified even if the class is const.
12952         if (Field->isMutable()) {
12953           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12954           break;
12955         }
12956 
12957         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12958           if (!DiagnosticEmitted) {
12959             S.Diag(Loc, diag::err_typecheck_assign_const)
12960                 << ExprRange << ConstMember << false /*static*/ << Field
12961                 << Field->getType();
12962             DiagnosticEmitted = true;
12963           }
12964           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12965               << ConstMember << false /*static*/ << Field << Field->getType()
12966               << Field->getSourceRange();
12967         }
12968         E = ME->getBase();
12969         continue;
12970       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12971         if (VDecl->getType().isConstQualified()) {
12972           if (!DiagnosticEmitted) {
12973             S.Diag(Loc, diag::err_typecheck_assign_const)
12974                 << ExprRange << ConstMember << true /*static*/ << VDecl
12975                 << VDecl->getType();
12976             DiagnosticEmitted = true;
12977           }
12978           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12979               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12980               << VDecl->getSourceRange();
12981         }
12982         // Static fields do not inherit constness from parents.
12983         break;
12984       }
12985       break; // End MemberExpr
12986     } else if (const ArraySubscriptExpr *ASE =
12987                    dyn_cast<ArraySubscriptExpr>(E)) {
12988       E = ASE->getBase()->IgnoreParenImpCasts();
12989       continue;
12990     } else if (const ExtVectorElementExpr *EVE =
12991                    dyn_cast<ExtVectorElementExpr>(E)) {
12992       E = EVE->getBase()->IgnoreParenImpCasts();
12993       continue;
12994     }
12995     break;
12996   }
12997 
12998   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12999     // Function calls
13000     const FunctionDecl *FD = CE->getDirectCallee();
13001     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13002       if (!DiagnosticEmitted) {
13003         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13004                                                       << ConstFunction << FD;
13005         DiagnosticEmitted = true;
13006       }
13007       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13008              diag::note_typecheck_assign_const)
13009           << ConstFunction << FD << FD->getReturnType()
13010           << FD->getReturnTypeSourceRange();
13011     }
13012   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13013     // Point to variable declaration.
13014     if (const ValueDecl *VD = DRE->getDecl()) {
13015       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13016         if (!DiagnosticEmitted) {
13017           S.Diag(Loc, diag::err_typecheck_assign_const)
13018               << ExprRange << ConstVariable << VD << VD->getType();
13019           DiagnosticEmitted = true;
13020         }
13021         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13022             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13023       }
13024     }
13025   } else if (isa<CXXThisExpr>(E)) {
13026     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13027       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13028         if (MD->isConst()) {
13029           if (!DiagnosticEmitted) {
13030             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13031                                                           << ConstMethod << MD;
13032             DiagnosticEmitted = true;
13033           }
13034           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13035               << ConstMethod << MD << MD->getSourceRange();
13036         }
13037       }
13038     }
13039   }
13040 
13041   if (DiagnosticEmitted)
13042     return;
13043 
13044   // Can't determine a more specific message, so display the generic error.
13045   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13046 }
13047 
13048 enum OriginalExprKind {
13049   OEK_Variable,
13050   OEK_Member,
13051   OEK_LValue
13052 };
13053 
13054 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13055                                          const RecordType *Ty,
13056                                          SourceLocation Loc, SourceRange Range,
13057                                          OriginalExprKind OEK,
13058                                          bool &DiagnosticEmitted) {
13059   std::vector<const RecordType *> RecordTypeList;
13060   RecordTypeList.push_back(Ty);
13061   unsigned NextToCheckIndex = 0;
13062   // We walk the record hierarchy breadth-first to ensure that we print
13063   // diagnostics in field nesting order.
13064   while (RecordTypeList.size() > NextToCheckIndex) {
13065     bool IsNested = NextToCheckIndex > 0;
13066     for (const FieldDecl *Field :
13067          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13068       // First, check every field for constness.
13069       QualType FieldTy = Field->getType();
13070       if (FieldTy.isConstQualified()) {
13071         if (!DiagnosticEmitted) {
13072           S.Diag(Loc, diag::err_typecheck_assign_const)
13073               << Range << NestedConstMember << OEK << VD
13074               << IsNested << Field;
13075           DiagnosticEmitted = true;
13076         }
13077         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13078             << NestedConstMember << IsNested << Field
13079             << FieldTy << Field->getSourceRange();
13080       }
13081 
13082       // Then we append it to the list to check next in order.
13083       FieldTy = FieldTy.getCanonicalType();
13084       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13085         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13086           RecordTypeList.push_back(FieldRecTy);
13087       }
13088     }
13089     ++NextToCheckIndex;
13090   }
13091 }
13092 
13093 /// Emit an error for the case where a record we are trying to assign to has a
13094 /// const-qualified field somewhere in its hierarchy.
13095 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13096                                          SourceLocation Loc) {
13097   QualType Ty = E->getType();
13098   assert(Ty->isRecordType() && "lvalue was not record?");
13099   SourceRange Range = E->getSourceRange();
13100   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13101   bool DiagEmitted = false;
13102 
13103   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13104     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13105             Range, OEK_Member, DiagEmitted);
13106   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13107     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13108             Range, OEK_Variable, DiagEmitted);
13109   else
13110     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13111             Range, OEK_LValue, DiagEmitted);
13112   if (!DiagEmitted)
13113     DiagnoseConstAssignment(S, E, Loc);
13114 }
13115 
13116 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13117 /// emit an error and return true.  If so, return false.
13118 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13119   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13120 
13121   S.CheckShadowingDeclModification(E, Loc);
13122 
13123   SourceLocation OrigLoc = Loc;
13124   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13125                                                               &Loc);
13126   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13127     IsLV = Expr::MLV_InvalidMessageExpression;
13128   if (IsLV == Expr::MLV_Valid)
13129     return false;
13130 
13131   unsigned DiagID = 0;
13132   bool NeedType = false;
13133   switch (IsLV) { // C99 6.5.16p2
13134   case Expr::MLV_ConstQualified:
13135     // Use a specialized diagnostic when we're assigning to an object
13136     // from an enclosing function or block.
13137     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13138       if (NCCK == NCCK_Block)
13139         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13140       else
13141         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13142       break;
13143     }
13144 
13145     // In ARC, use some specialized diagnostics for occasions where we
13146     // infer 'const'.  These are always pseudo-strong variables.
13147     if (S.getLangOpts().ObjCAutoRefCount) {
13148       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13149       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13150         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13151 
13152         // Use the normal diagnostic if it's pseudo-__strong but the
13153         // user actually wrote 'const'.
13154         if (var->isARCPseudoStrong() &&
13155             (!var->getTypeSourceInfo() ||
13156              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13157           // There are three pseudo-strong cases:
13158           //  - self
13159           ObjCMethodDecl *method = S.getCurMethodDecl();
13160           if (method && var == method->getSelfDecl()) {
13161             DiagID = method->isClassMethod()
13162               ? diag::err_typecheck_arc_assign_self_class_method
13163               : diag::err_typecheck_arc_assign_self;
13164 
13165           //  - Objective-C externally_retained attribute.
13166           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13167                      isa<ParmVarDecl>(var)) {
13168             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13169 
13170           //  - fast enumeration variables
13171           } else {
13172             DiagID = diag::err_typecheck_arr_assign_enumeration;
13173           }
13174 
13175           SourceRange Assign;
13176           if (Loc != OrigLoc)
13177             Assign = SourceRange(OrigLoc, OrigLoc);
13178           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13179           // We need to preserve the AST regardless, so migration tool
13180           // can do its job.
13181           return false;
13182         }
13183       }
13184     }
13185 
13186     // If none of the special cases above are triggered, then this is a
13187     // simple const assignment.
13188     if (DiagID == 0) {
13189       DiagnoseConstAssignment(S, E, Loc);
13190       return true;
13191     }
13192 
13193     break;
13194   case Expr::MLV_ConstAddrSpace:
13195     DiagnoseConstAssignment(S, E, Loc);
13196     return true;
13197   case Expr::MLV_ConstQualifiedField:
13198     DiagnoseRecursiveConstFields(S, E, Loc);
13199     return true;
13200   case Expr::MLV_ArrayType:
13201   case Expr::MLV_ArrayTemporary:
13202     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13203     NeedType = true;
13204     break;
13205   case Expr::MLV_NotObjectType:
13206     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13207     NeedType = true;
13208     break;
13209   case Expr::MLV_LValueCast:
13210     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13211     break;
13212   case Expr::MLV_Valid:
13213     llvm_unreachable("did not take early return for MLV_Valid");
13214   case Expr::MLV_InvalidExpression:
13215   case Expr::MLV_MemberFunction:
13216   case Expr::MLV_ClassTemporary:
13217     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13218     break;
13219   case Expr::MLV_IncompleteType:
13220   case Expr::MLV_IncompleteVoidType:
13221     return S.RequireCompleteType(Loc, E->getType(),
13222              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13223   case Expr::MLV_DuplicateVectorComponents:
13224     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13225     break;
13226   case Expr::MLV_NoSetterProperty:
13227     llvm_unreachable("readonly properties should be processed differently");
13228   case Expr::MLV_InvalidMessageExpression:
13229     DiagID = diag::err_readonly_message_assignment;
13230     break;
13231   case Expr::MLV_SubObjCPropertySetting:
13232     DiagID = diag::err_no_subobject_property_setting;
13233     break;
13234   }
13235 
13236   SourceRange Assign;
13237   if (Loc != OrigLoc)
13238     Assign = SourceRange(OrigLoc, OrigLoc);
13239   if (NeedType)
13240     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13241   else
13242     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13243   return true;
13244 }
13245 
13246 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13247                                          SourceLocation Loc,
13248                                          Sema &Sema) {
13249   if (Sema.inTemplateInstantiation())
13250     return;
13251   if (Sema.isUnevaluatedContext())
13252     return;
13253   if (Loc.isInvalid() || Loc.isMacroID())
13254     return;
13255   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13256     return;
13257 
13258   // C / C++ fields
13259   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13260   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13261   if (ML && MR) {
13262     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13263       return;
13264     const ValueDecl *LHSDecl =
13265         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13266     const ValueDecl *RHSDecl =
13267         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13268     if (LHSDecl != RHSDecl)
13269       return;
13270     if (LHSDecl->getType().isVolatileQualified())
13271       return;
13272     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13273       if (RefTy->getPointeeType().isVolatileQualified())
13274         return;
13275 
13276     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13277   }
13278 
13279   // Objective-C instance variables
13280   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13281   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13282   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13283     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13284     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13285     if (RL && RR && RL->getDecl() == RR->getDecl())
13286       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13287   }
13288 }
13289 
13290 // C99 6.5.16.1
13291 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13292                                        SourceLocation Loc,
13293                                        QualType CompoundType) {
13294   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13295 
13296   // Verify that LHS is a modifiable lvalue, and emit error if not.
13297   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13298     return QualType();
13299 
13300   QualType LHSType = LHSExpr->getType();
13301   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13302                                              CompoundType;
13303   // OpenCL v1.2 s6.1.1.1 p2:
13304   // The half data type can only be used to declare a pointer to a buffer that
13305   // contains half values
13306   if (getLangOpts().OpenCL &&
13307       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13308       LHSType->isHalfType()) {
13309     Diag(Loc, diag::err_opencl_half_load_store) << 1
13310         << LHSType.getUnqualifiedType();
13311     return QualType();
13312   }
13313 
13314   AssignConvertType ConvTy;
13315   if (CompoundType.isNull()) {
13316     Expr *RHSCheck = RHS.get();
13317 
13318     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13319 
13320     QualType LHSTy(LHSType);
13321     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13322     if (RHS.isInvalid())
13323       return QualType();
13324     // Special case of NSObject attributes on c-style pointer types.
13325     if (ConvTy == IncompatiblePointer &&
13326         ((Context.isObjCNSObjectType(LHSType) &&
13327           RHSType->isObjCObjectPointerType()) ||
13328          (Context.isObjCNSObjectType(RHSType) &&
13329           LHSType->isObjCObjectPointerType())))
13330       ConvTy = Compatible;
13331 
13332     if (ConvTy == Compatible &&
13333         LHSType->isObjCObjectType())
13334         Diag(Loc, diag::err_objc_object_assignment)
13335           << LHSType;
13336 
13337     // If the RHS is a unary plus or minus, check to see if they = and + are
13338     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13339     // instead of "x += 4".
13340     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13341       RHSCheck = ICE->getSubExpr();
13342     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13343       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13344           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13345           // Only if the two operators are exactly adjacent.
13346           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13347           // And there is a space or other character before the subexpr of the
13348           // unary +/-.  We don't want to warn on "x=-1".
13349           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13350           UO->getSubExpr()->getBeginLoc().isFileID()) {
13351         Diag(Loc, diag::warn_not_compound_assign)
13352           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13353           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13354       }
13355     }
13356 
13357     if (ConvTy == Compatible) {
13358       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13359         // Warn about retain cycles where a block captures the LHS, but
13360         // not if the LHS is a simple variable into which the block is
13361         // being stored...unless that variable can be captured by reference!
13362         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13363         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13364         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13365           checkRetainCycles(LHSExpr, RHS.get());
13366       }
13367 
13368       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13369           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13370         // It is safe to assign a weak reference into a strong variable.
13371         // Although this code can still have problems:
13372         //   id x = self.weakProp;
13373         //   id y = self.weakProp;
13374         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13375         // paths through the function. This should be revisited if
13376         // -Wrepeated-use-of-weak is made flow-sensitive.
13377         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13378         // variable, which will be valid for the current autorelease scope.
13379         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13380                              RHS.get()->getBeginLoc()))
13381           getCurFunction()->markSafeWeakUse(RHS.get());
13382 
13383       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13384         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13385       }
13386     }
13387   } else {
13388     // Compound assignment "x += y"
13389     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13390   }
13391 
13392   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13393                                RHS.get(), AA_Assigning))
13394     return QualType();
13395 
13396   CheckForNullPointerDereference(*this, LHSExpr);
13397 
13398   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13399     if (CompoundType.isNull()) {
13400       // C++2a [expr.ass]p5:
13401       //   A simple-assignment whose left operand is of a volatile-qualified
13402       //   type is deprecated unless the assignment is either a discarded-value
13403       //   expression or an unevaluated operand
13404       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13405     } else {
13406       // C++2a [expr.ass]p6:
13407       //   [Compound-assignment] expressions are deprecated if E1 has
13408       //   volatile-qualified type
13409       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13410     }
13411   }
13412 
13413   // C99 6.5.16p3: The type of an assignment expression is the type of the
13414   // left operand unless the left operand has qualified type, in which case
13415   // it is the unqualified version of the type of the left operand.
13416   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13417   // is converted to the type of the assignment expression (above).
13418   // C++ 5.17p1: the type of the assignment expression is that of its left
13419   // operand.
13420   return (getLangOpts().CPlusPlus
13421           ? LHSType : LHSType.getUnqualifiedType());
13422 }
13423 
13424 // Only ignore explicit casts to void.
13425 static bool IgnoreCommaOperand(const Expr *E) {
13426   E = E->IgnoreParens();
13427 
13428   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13429     if (CE->getCastKind() == CK_ToVoid) {
13430       return true;
13431     }
13432 
13433     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13434     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13435         CE->getSubExpr()->getType()->isDependentType()) {
13436       return true;
13437     }
13438   }
13439 
13440   return false;
13441 }
13442 
13443 // Look for instances where it is likely the comma operator is confused with
13444 // another operator.  There is an explicit list of acceptable expressions for
13445 // the left hand side of the comma operator, otherwise emit a warning.
13446 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13447   // No warnings in macros
13448   if (Loc.isMacroID())
13449     return;
13450 
13451   // Don't warn in template instantiations.
13452   if (inTemplateInstantiation())
13453     return;
13454 
13455   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13456   // instead, skip more than needed, then call back into here with the
13457   // CommaVisitor in SemaStmt.cpp.
13458   // The listed locations are the initialization and increment portions
13459   // of a for loop.  The additional checks are on the condition of
13460   // if statements, do/while loops, and for loops.
13461   // Differences in scope flags for C89 mode requires the extra logic.
13462   const unsigned ForIncrementFlags =
13463       getLangOpts().C99 || getLangOpts().CPlusPlus
13464           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13465           : Scope::ContinueScope | Scope::BreakScope;
13466   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13467   const unsigned ScopeFlags = getCurScope()->getFlags();
13468   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13469       (ScopeFlags & ForInitFlags) == ForInitFlags)
13470     return;
13471 
13472   // If there are multiple comma operators used together, get the RHS of the
13473   // of the comma operator as the LHS.
13474   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13475     if (BO->getOpcode() != BO_Comma)
13476       break;
13477     LHS = BO->getRHS();
13478   }
13479 
13480   // Only allow some expressions on LHS to not warn.
13481   if (IgnoreCommaOperand(LHS))
13482     return;
13483 
13484   Diag(Loc, diag::warn_comma_operator);
13485   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13486       << LHS->getSourceRange()
13487       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13488                                     LangOpts.CPlusPlus ? "static_cast<void>("
13489                                                        : "(void)(")
13490       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13491                                     ")");
13492 }
13493 
13494 // C99 6.5.17
13495 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13496                                    SourceLocation Loc) {
13497   LHS = S.CheckPlaceholderExpr(LHS.get());
13498   RHS = S.CheckPlaceholderExpr(RHS.get());
13499   if (LHS.isInvalid() || RHS.isInvalid())
13500     return QualType();
13501 
13502   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13503   // operands, but not unary promotions.
13504   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13505 
13506   // So we treat the LHS as a ignored value, and in C++ we allow the
13507   // containing site to determine what should be done with the RHS.
13508   LHS = S.IgnoredValueConversions(LHS.get());
13509   if (LHS.isInvalid())
13510     return QualType();
13511 
13512   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13513 
13514   if (!S.getLangOpts().CPlusPlus) {
13515     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13516     if (RHS.isInvalid())
13517       return QualType();
13518     if (!RHS.get()->getType()->isVoidType())
13519       S.RequireCompleteType(Loc, RHS.get()->getType(),
13520                             diag::err_incomplete_type);
13521   }
13522 
13523   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13524     S.DiagnoseCommaOperator(LHS.get(), Loc);
13525 
13526   return RHS.get()->getType();
13527 }
13528 
13529 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13530 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13531 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13532                                                ExprValueKind &VK,
13533                                                ExprObjectKind &OK,
13534                                                SourceLocation OpLoc,
13535                                                bool IsInc, bool IsPrefix) {
13536   if (Op->isTypeDependent())
13537     return S.Context.DependentTy;
13538 
13539   QualType ResType = Op->getType();
13540   // Atomic types can be used for increment / decrement where the non-atomic
13541   // versions can, so ignore the _Atomic() specifier for the purpose of
13542   // checking.
13543   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13544     ResType = ResAtomicType->getValueType();
13545 
13546   assert(!ResType.isNull() && "no type for increment/decrement expression");
13547 
13548   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13549     // Decrement of bool is not allowed.
13550     if (!IsInc) {
13551       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13552       return QualType();
13553     }
13554     // Increment of bool sets it to true, but is deprecated.
13555     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13556                                               : diag::warn_increment_bool)
13557       << Op->getSourceRange();
13558   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13559     // Error on enum increments and decrements in C++ mode
13560     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13561     return QualType();
13562   } else if (ResType->isRealType()) {
13563     // OK!
13564   } else if (ResType->isPointerType()) {
13565     // C99 6.5.2.4p2, 6.5.6p2
13566     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13567       return QualType();
13568   } else if (ResType->isObjCObjectPointerType()) {
13569     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13570     // Otherwise, we just need a complete type.
13571     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13572         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13573       return QualType();
13574   } else if (ResType->isAnyComplexType()) {
13575     // C99 does not support ++/-- on complex types, we allow as an extension.
13576     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13577       << ResType << Op->getSourceRange();
13578   } else if (ResType->isPlaceholderType()) {
13579     ExprResult PR = S.CheckPlaceholderExpr(Op);
13580     if (PR.isInvalid()) return QualType();
13581     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13582                                           IsInc, IsPrefix);
13583   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13584     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13585   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13586              (ResType->castAs<VectorType>()->getVectorKind() !=
13587               VectorType::AltiVecBool)) {
13588     // The z vector extensions allow ++ and -- for non-bool vectors.
13589   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13590             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13591     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13592   } else {
13593     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13594       << ResType << int(IsInc) << Op->getSourceRange();
13595     return QualType();
13596   }
13597   // At this point, we know we have a real, complex or pointer type.
13598   // Now make sure the operand is a modifiable lvalue.
13599   if (CheckForModifiableLvalue(Op, OpLoc, S))
13600     return QualType();
13601   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13602     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13603     //   An operand with volatile-qualified type is deprecated
13604     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13605         << IsInc << ResType;
13606   }
13607   // In C++, a prefix increment is the same type as the operand. Otherwise
13608   // (in C or with postfix), the increment is the unqualified type of the
13609   // operand.
13610   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13611     VK = VK_LValue;
13612     OK = Op->getObjectKind();
13613     return ResType;
13614   } else {
13615     VK = VK_PRValue;
13616     return ResType.getUnqualifiedType();
13617   }
13618 }
13619 
13620 
13621 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13622 /// This routine allows us to typecheck complex/recursive expressions
13623 /// where the declaration is needed for type checking. We only need to
13624 /// handle cases when the expression references a function designator
13625 /// or is an lvalue. Here are some examples:
13626 ///  - &(x) => x
13627 ///  - &*****f => f for f a function designator.
13628 ///  - &s.xx => s
13629 ///  - &s.zz[1].yy -> s, if zz is an array
13630 ///  - *(x + 1) -> x, if x is an array
13631 ///  - &"123"[2] -> 0
13632 ///  - & __real__ x -> x
13633 ///
13634 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13635 /// members.
13636 static ValueDecl *getPrimaryDecl(Expr *E) {
13637   switch (E->getStmtClass()) {
13638   case Stmt::DeclRefExprClass:
13639     return cast<DeclRefExpr>(E)->getDecl();
13640   case Stmt::MemberExprClass:
13641     // If this is an arrow operator, the address is an offset from
13642     // the base's value, so the object the base refers to is
13643     // irrelevant.
13644     if (cast<MemberExpr>(E)->isArrow())
13645       return nullptr;
13646     // Otherwise, the expression refers to a part of the base
13647     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13648   case Stmt::ArraySubscriptExprClass: {
13649     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13650     // promotion of register arrays earlier.
13651     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13652     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13653       if (ICE->getSubExpr()->getType()->isArrayType())
13654         return getPrimaryDecl(ICE->getSubExpr());
13655     }
13656     return nullptr;
13657   }
13658   case Stmt::UnaryOperatorClass: {
13659     UnaryOperator *UO = cast<UnaryOperator>(E);
13660 
13661     switch(UO->getOpcode()) {
13662     case UO_Real:
13663     case UO_Imag:
13664     case UO_Extension:
13665       return getPrimaryDecl(UO->getSubExpr());
13666     default:
13667       return nullptr;
13668     }
13669   }
13670   case Stmt::ParenExprClass:
13671     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13672   case Stmt::ImplicitCastExprClass:
13673     // If the result of an implicit cast is an l-value, we care about
13674     // the sub-expression; otherwise, the result here doesn't matter.
13675     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13676   case Stmt::CXXUuidofExprClass:
13677     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13678   default:
13679     return nullptr;
13680   }
13681 }
13682 
13683 namespace {
13684 enum {
13685   AO_Bit_Field = 0,
13686   AO_Vector_Element = 1,
13687   AO_Property_Expansion = 2,
13688   AO_Register_Variable = 3,
13689   AO_Matrix_Element = 4,
13690   AO_No_Error = 5
13691 };
13692 }
13693 /// Diagnose invalid operand for address of operations.
13694 ///
13695 /// \param Type The type of operand which cannot have its address taken.
13696 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13697                                          Expr *E, unsigned Type) {
13698   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13699 }
13700 
13701 /// CheckAddressOfOperand - The operand of & must be either a function
13702 /// designator or an lvalue designating an object. If it is an lvalue, the
13703 /// object cannot be declared with storage class register or be a bit field.
13704 /// Note: The usual conversions are *not* applied to the operand of the &
13705 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13706 /// In C++, the operand might be an overloaded function name, in which case
13707 /// we allow the '&' but retain the overloaded-function type.
13708 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13709   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13710     if (PTy->getKind() == BuiltinType::Overload) {
13711       Expr *E = OrigOp.get()->IgnoreParens();
13712       if (!isa<OverloadExpr>(E)) {
13713         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13714         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13715           << OrigOp.get()->getSourceRange();
13716         return QualType();
13717       }
13718 
13719       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13720       if (isa<UnresolvedMemberExpr>(Ovl))
13721         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13722           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13723             << OrigOp.get()->getSourceRange();
13724           return QualType();
13725         }
13726 
13727       return Context.OverloadTy;
13728     }
13729 
13730     if (PTy->getKind() == BuiltinType::UnknownAny)
13731       return Context.UnknownAnyTy;
13732 
13733     if (PTy->getKind() == BuiltinType::BoundMember) {
13734       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13735         << OrigOp.get()->getSourceRange();
13736       return QualType();
13737     }
13738 
13739     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13740     if (OrigOp.isInvalid()) return QualType();
13741   }
13742 
13743   if (OrigOp.get()->isTypeDependent())
13744     return Context.DependentTy;
13745 
13746   assert(!OrigOp.get()->hasPlaceholderType());
13747 
13748   // Make sure to ignore parentheses in subsequent checks
13749   Expr *op = OrigOp.get()->IgnoreParens();
13750 
13751   // In OpenCL captures for blocks called as lambda functions
13752   // are located in the private address space. Blocks used in
13753   // enqueue_kernel can be located in a different address space
13754   // depending on a vendor implementation. Thus preventing
13755   // taking an address of the capture to avoid invalid AS casts.
13756   if (LangOpts.OpenCL) {
13757     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13758     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13759       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13760       return QualType();
13761     }
13762   }
13763 
13764   if (getLangOpts().C99) {
13765     // Implement C99-only parts of addressof rules.
13766     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13767       if (uOp->getOpcode() == UO_Deref)
13768         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13769         // (assuming the deref expression is valid).
13770         return uOp->getSubExpr()->getType();
13771     }
13772     // Technically, there should be a check for array subscript
13773     // expressions here, but the result of one is always an lvalue anyway.
13774   }
13775   ValueDecl *dcl = getPrimaryDecl(op);
13776 
13777   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13778     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13779                                            op->getBeginLoc()))
13780       return QualType();
13781 
13782   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13783   unsigned AddressOfError = AO_No_Error;
13784 
13785   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13786     bool sfinae = (bool)isSFINAEContext();
13787     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13788                                   : diag::ext_typecheck_addrof_temporary)
13789       << op->getType() << op->getSourceRange();
13790     if (sfinae)
13791       return QualType();
13792     // Materialize the temporary as an lvalue so that we can take its address.
13793     OrigOp = op =
13794         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13795   } else if (isa<ObjCSelectorExpr>(op)) {
13796     return Context.getPointerType(op->getType());
13797   } else if (lval == Expr::LV_MemberFunction) {
13798     // If it's an instance method, make a member pointer.
13799     // The expression must have exactly the form &A::foo.
13800 
13801     // If the underlying expression isn't a decl ref, give up.
13802     if (!isa<DeclRefExpr>(op)) {
13803       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13804         << OrigOp.get()->getSourceRange();
13805       return QualType();
13806     }
13807     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13808     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13809 
13810     // The id-expression was parenthesized.
13811     if (OrigOp.get() != DRE) {
13812       Diag(OpLoc, diag::err_parens_pointer_member_function)
13813         << OrigOp.get()->getSourceRange();
13814 
13815     // The method was named without a qualifier.
13816     } else if (!DRE->getQualifier()) {
13817       if (MD->getParent()->getName().empty())
13818         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13819           << op->getSourceRange();
13820       else {
13821         SmallString<32> Str;
13822         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13823         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13824           << op->getSourceRange()
13825           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13826       }
13827     }
13828 
13829     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13830     if (isa<CXXDestructorDecl>(MD))
13831       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13832 
13833     QualType MPTy = Context.getMemberPointerType(
13834         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13835     // Under the MS ABI, lock down the inheritance model now.
13836     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13837       (void)isCompleteType(OpLoc, MPTy);
13838     return MPTy;
13839   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13840     // C99 6.5.3.2p1
13841     // The operand must be either an l-value or a function designator
13842     if (!op->getType()->isFunctionType()) {
13843       // Use a special diagnostic for loads from property references.
13844       if (isa<PseudoObjectExpr>(op)) {
13845         AddressOfError = AO_Property_Expansion;
13846       } else {
13847         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13848           << op->getType() << op->getSourceRange();
13849         return QualType();
13850       }
13851     }
13852   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13853     // The operand cannot be a bit-field
13854     AddressOfError = AO_Bit_Field;
13855   } else if (op->getObjectKind() == OK_VectorComponent) {
13856     // The operand cannot be an element of a vector
13857     AddressOfError = AO_Vector_Element;
13858   } else if (op->getObjectKind() == OK_MatrixComponent) {
13859     // The operand cannot be an element of a matrix.
13860     AddressOfError = AO_Matrix_Element;
13861   } else if (dcl) { // C99 6.5.3.2p1
13862     // We have an lvalue with a decl. Make sure the decl is not declared
13863     // with the register storage-class specifier.
13864     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13865       // in C++ it is not error to take address of a register
13866       // variable (c++03 7.1.1P3)
13867       if (vd->getStorageClass() == SC_Register &&
13868           !getLangOpts().CPlusPlus) {
13869         AddressOfError = AO_Register_Variable;
13870       }
13871     } else if (isa<MSPropertyDecl>(dcl)) {
13872       AddressOfError = AO_Property_Expansion;
13873     } else if (isa<FunctionTemplateDecl>(dcl)) {
13874       return Context.OverloadTy;
13875     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13876       // Okay: we can take the address of a field.
13877       // Could be a pointer to member, though, if there is an explicit
13878       // scope qualifier for the class.
13879       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13880         DeclContext *Ctx = dcl->getDeclContext();
13881         if (Ctx && Ctx->isRecord()) {
13882           if (dcl->getType()->isReferenceType()) {
13883             Diag(OpLoc,
13884                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13885               << dcl->getDeclName() << dcl->getType();
13886             return QualType();
13887           }
13888 
13889           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13890             Ctx = Ctx->getParent();
13891 
13892           QualType MPTy = Context.getMemberPointerType(
13893               op->getType(),
13894               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13895           // Under the MS ABI, lock down the inheritance model now.
13896           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13897             (void)isCompleteType(OpLoc, MPTy);
13898           return MPTy;
13899         }
13900       }
13901     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13902                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13903       llvm_unreachable("Unknown/unexpected decl type");
13904   }
13905 
13906   if (AddressOfError != AO_No_Error) {
13907     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13908     return QualType();
13909   }
13910 
13911   if (lval == Expr::LV_IncompleteVoidType) {
13912     // Taking the address of a void variable is technically illegal, but we
13913     // allow it in cases which are otherwise valid.
13914     // Example: "extern void x; void* y = &x;".
13915     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13916   }
13917 
13918   // If the operand has type "type", the result has type "pointer to type".
13919   if (op->getType()->isObjCObjectType())
13920     return Context.getObjCObjectPointerType(op->getType());
13921 
13922   CheckAddressOfPackedMember(op);
13923 
13924   return Context.getPointerType(op->getType());
13925 }
13926 
13927 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13928   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13929   if (!DRE)
13930     return;
13931   const Decl *D = DRE->getDecl();
13932   if (!D)
13933     return;
13934   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13935   if (!Param)
13936     return;
13937   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13938     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13939       return;
13940   if (FunctionScopeInfo *FD = S.getCurFunction())
13941     if (!FD->ModifiedNonNullParams.count(Param))
13942       FD->ModifiedNonNullParams.insert(Param);
13943 }
13944 
13945 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13946 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13947                                         SourceLocation OpLoc) {
13948   if (Op->isTypeDependent())
13949     return S.Context.DependentTy;
13950 
13951   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13952   if (ConvResult.isInvalid())
13953     return QualType();
13954   Op = ConvResult.get();
13955   QualType OpTy = Op->getType();
13956   QualType Result;
13957 
13958   if (isa<CXXReinterpretCastExpr>(Op)) {
13959     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13960     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13961                                      Op->getSourceRange());
13962   }
13963 
13964   if (const PointerType *PT = OpTy->getAs<PointerType>())
13965   {
13966     Result = PT->getPointeeType();
13967   }
13968   else if (const ObjCObjectPointerType *OPT =
13969              OpTy->getAs<ObjCObjectPointerType>())
13970     Result = OPT->getPointeeType();
13971   else {
13972     ExprResult PR = S.CheckPlaceholderExpr(Op);
13973     if (PR.isInvalid()) return QualType();
13974     if (PR.get() != Op)
13975       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13976   }
13977 
13978   if (Result.isNull()) {
13979     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13980       << OpTy << Op->getSourceRange();
13981     return QualType();
13982   }
13983 
13984   // Note that per both C89 and C99, indirection is always legal, even if Result
13985   // is an incomplete type or void.  It would be possible to warn about
13986   // dereferencing a void pointer, but it's completely well-defined, and such a
13987   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13988   // for pointers to 'void' but is fine for any other pointer type:
13989   //
13990   // C++ [expr.unary.op]p1:
13991   //   [...] the expression to which [the unary * operator] is applied shall
13992   //   be a pointer to an object type, or a pointer to a function type
13993   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13994     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13995       << OpTy << Op->getSourceRange();
13996 
13997   // Dereferences are usually l-values...
13998   VK = VK_LValue;
13999 
14000   // ...except that certain expressions are never l-values in C.
14001   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14002     VK = VK_PRValue;
14003 
14004   return Result;
14005 }
14006 
14007 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14008   BinaryOperatorKind Opc;
14009   switch (Kind) {
14010   default: llvm_unreachable("Unknown binop!");
14011   case tok::periodstar:           Opc = BO_PtrMemD; break;
14012   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14013   case tok::star:                 Opc = BO_Mul; break;
14014   case tok::slash:                Opc = BO_Div; break;
14015   case tok::percent:              Opc = BO_Rem; break;
14016   case tok::plus:                 Opc = BO_Add; break;
14017   case tok::minus:                Opc = BO_Sub; break;
14018   case tok::lessless:             Opc = BO_Shl; break;
14019   case tok::greatergreater:       Opc = BO_Shr; break;
14020   case tok::lessequal:            Opc = BO_LE; break;
14021   case tok::less:                 Opc = BO_LT; break;
14022   case tok::greaterequal:         Opc = BO_GE; break;
14023   case tok::greater:              Opc = BO_GT; break;
14024   case tok::exclaimequal:         Opc = BO_NE; break;
14025   case tok::equalequal:           Opc = BO_EQ; break;
14026   case tok::spaceship:            Opc = BO_Cmp; break;
14027   case tok::amp:                  Opc = BO_And; break;
14028   case tok::caret:                Opc = BO_Xor; break;
14029   case tok::pipe:                 Opc = BO_Or; break;
14030   case tok::ampamp:               Opc = BO_LAnd; break;
14031   case tok::pipepipe:             Opc = BO_LOr; break;
14032   case tok::equal:                Opc = BO_Assign; break;
14033   case tok::starequal:            Opc = BO_MulAssign; break;
14034   case tok::slashequal:           Opc = BO_DivAssign; break;
14035   case tok::percentequal:         Opc = BO_RemAssign; break;
14036   case tok::plusequal:            Opc = BO_AddAssign; break;
14037   case tok::minusequal:           Opc = BO_SubAssign; break;
14038   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14039   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14040   case tok::ampequal:             Opc = BO_AndAssign; break;
14041   case tok::caretequal:           Opc = BO_XorAssign; break;
14042   case tok::pipeequal:            Opc = BO_OrAssign; break;
14043   case tok::comma:                Opc = BO_Comma; break;
14044   }
14045   return Opc;
14046 }
14047 
14048 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14049   tok::TokenKind Kind) {
14050   UnaryOperatorKind Opc;
14051   switch (Kind) {
14052   default: llvm_unreachable("Unknown unary op!");
14053   case tok::plusplus:     Opc = UO_PreInc; break;
14054   case tok::minusminus:   Opc = UO_PreDec; break;
14055   case tok::amp:          Opc = UO_AddrOf; break;
14056   case tok::star:         Opc = UO_Deref; break;
14057   case tok::plus:         Opc = UO_Plus; break;
14058   case tok::minus:        Opc = UO_Minus; break;
14059   case tok::tilde:        Opc = UO_Not; break;
14060   case tok::exclaim:      Opc = UO_LNot; break;
14061   case tok::kw___real:    Opc = UO_Real; break;
14062   case tok::kw___imag:    Opc = UO_Imag; break;
14063   case tok::kw___extension__: Opc = UO_Extension; break;
14064   }
14065   return Opc;
14066 }
14067 
14068 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14069 /// This warning suppressed in the event of macro expansions.
14070 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14071                                    SourceLocation OpLoc, bool IsBuiltin) {
14072   if (S.inTemplateInstantiation())
14073     return;
14074   if (S.isUnevaluatedContext())
14075     return;
14076   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14077     return;
14078   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14079   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14080   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14081   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14082   if (!LHSDeclRef || !RHSDeclRef ||
14083       LHSDeclRef->getLocation().isMacroID() ||
14084       RHSDeclRef->getLocation().isMacroID())
14085     return;
14086   const ValueDecl *LHSDecl =
14087     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14088   const ValueDecl *RHSDecl =
14089     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14090   if (LHSDecl != RHSDecl)
14091     return;
14092   if (LHSDecl->getType().isVolatileQualified())
14093     return;
14094   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14095     if (RefTy->getPointeeType().isVolatileQualified())
14096       return;
14097 
14098   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14099                           : diag::warn_self_assignment_overloaded)
14100       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14101       << RHSExpr->getSourceRange();
14102 }
14103 
14104 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14105 /// is usually indicative of introspection within the Objective-C pointer.
14106 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14107                                           SourceLocation OpLoc) {
14108   if (!S.getLangOpts().ObjC)
14109     return;
14110 
14111   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14112   const Expr *LHS = L.get();
14113   const Expr *RHS = R.get();
14114 
14115   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14116     ObjCPointerExpr = LHS;
14117     OtherExpr = RHS;
14118   }
14119   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14120     ObjCPointerExpr = RHS;
14121     OtherExpr = LHS;
14122   }
14123 
14124   // This warning is deliberately made very specific to reduce false
14125   // positives with logic that uses '&' for hashing.  This logic mainly
14126   // looks for code trying to introspect into tagged pointers, which
14127   // code should generally never do.
14128   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14129     unsigned Diag = diag::warn_objc_pointer_masking;
14130     // Determine if we are introspecting the result of performSelectorXXX.
14131     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14132     // Special case messages to -performSelector and friends, which
14133     // can return non-pointer values boxed in a pointer value.
14134     // Some clients may wish to silence warnings in this subcase.
14135     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14136       Selector S = ME->getSelector();
14137       StringRef SelArg0 = S.getNameForSlot(0);
14138       if (SelArg0.startswith("performSelector"))
14139         Diag = diag::warn_objc_pointer_masking_performSelector;
14140     }
14141 
14142     S.Diag(OpLoc, Diag)
14143       << ObjCPointerExpr->getSourceRange();
14144   }
14145 }
14146 
14147 static NamedDecl *getDeclFromExpr(Expr *E) {
14148   if (!E)
14149     return nullptr;
14150   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14151     return DRE->getDecl();
14152   if (auto *ME = dyn_cast<MemberExpr>(E))
14153     return ME->getMemberDecl();
14154   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14155     return IRE->getDecl();
14156   return nullptr;
14157 }
14158 
14159 // This helper function promotes a binary operator's operands (which are of a
14160 // half vector type) to a vector of floats and then truncates the result to
14161 // a vector of either half or short.
14162 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14163                                       BinaryOperatorKind Opc, QualType ResultTy,
14164                                       ExprValueKind VK, ExprObjectKind OK,
14165                                       bool IsCompAssign, SourceLocation OpLoc,
14166                                       FPOptionsOverride FPFeatures) {
14167   auto &Context = S.getASTContext();
14168   assert((isVector(ResultTy, Context.HalfTy) ||
14169           isVector(ResultTy, Context.ShortTy)) &&
14170          "Result must be a vector of half or short");
14171   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14172          isVector(RHS.get()->getType(), Context.HalfTy) &&
14173          "both operands expected to be a half vector");
14174 
14175   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14176   QualType BinOpResTy = RHS.get()->getType();
14177 
14178   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14179   // change BinOpResTy to a vector of ints.
14180   if (isVector(ResultTy, Context.ShortTy))
14181     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14182 
14183   if (IsCompAssign)
14184     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14185                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14186                                           BinOpResTy, BinOpResTy);
14187 
14188   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14189   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14190                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14191   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14192 }
14193 
14194 static std::pair<ExprResult, ExprResult>
14195 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14196                            Expr *RHSExpr) {
14197   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14198   if (!S.Context.isDependenceAllowed()) {
14199     // C cannot handle TypoExpr nodes on either side of a binop because it
14200     // doesn't handle dependent types properly, so make sure any TypoExprs have
14201     // been dealt with before checking the operands.
14202     LHS = S.CorrectDelayedTyposInExpr(LHS);
14203     RHS = S.CorrectDelayedTyposInExpr(
14204         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14205         [Opc, LHS](Expr *E) {
14206           if (Opc != BO_Assign)
14207             return ExprResult(E);
14208           // Avoid correcting the RHS to the same Expr as the LHS.
14209           Decl *D = getDeclFromExpr(E);
14210           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14211         });
14212   }
14213   return std::make_pair(LHS, RHS);
14214 }
14215 
14216 /// Returns true if conversion between vectors of halfs and vectors of floats
14217 /// is needed.
14218 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14219                                      Expr *E0, Expr *E1 = nullptr) {
14220   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14221       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14222     return false;
14223 
14224   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14225     QualType Ty = E->IgnoreImplicit()->getType();
14226 
14227     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14228     // to vectors of floats. Although the element type of the vectors is __fp16,
14229     // the vectors shouldn't be treated as storage-only types. See the
14230     // discussion here: https://reviews.llvm.org/rG825235c140e7
14231     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14232       if (VT->getVectorKind() == VectorType::NeonVector)
14233         return false;
14234       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14235     }
14236     return false;
14237   };
14238 
14239   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14240 }
14241 
14242 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14243 /// operator @p Opc at location @c TokLoc. This routine only supports
14244 /// built-in operations; ActOnBinOp handles overloaded operators.
14245 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14246                                     BinaryOperatorKind Opc,
14247                                     Expr *LHSExpr, Expr *RHSExpr) {
14248   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14249     // The syntax only allows initializer lists on the RHS of assignment,
14250     // so we don't need to worry about accepting invalid code for
14251     // non-assignment operators.
14252     // C++11 5.17p9:
14253     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14254     //   of x = {} is x = T().
14255     InitializationKind Kind = InitializationKind::CreateDirectList(
14256         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14257     InitializedEntity Entity =
14258         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14259     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14260     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14261     if (Init.isInvalid())
14262       return Init;
14263     RHSExpr = Init.get();
14264   }
14265 
14266   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14267   QualType ResultTy;     // Result type of the binary operator.
14268   // The following two variables are used for compound assignment operators
14269   QualType CompLHSTy;    // Type of LHS after promotions for computation
14270   QualType CompResultTy; // Type of computation result
14271   ExprValueKind VK = VK_PRValue;
14272   ExprObjectKind OK = OK_Ordinary;
14273   bool ConvertHalfVec = false;
14274 
14275   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14276   if (!LHS.isUsable() || !RHS.isUsable())
14277     return ExprError();
14278 
14279   if (getLangOpts().OpenCL) {
14280     QualType LHSTy = LHSExpr->getType();
14281     QualType RHSTy = RHSExpr->getType();
14282     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14283     // the ATOMIC_VAR_INIT macro.
14284     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14285       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14286       if (BO_Assign == Opc)
14287         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14288       else
14289         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14290       return ExprError();
14291     }
14292 
14293     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14294     // only with a builtin functions and therefore should be disallowed here.
14295     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14296         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14297         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14298         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14299       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14300       return ExprError();
14301     }
14302   }
14303 
14304   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14305   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14306 
14307   switch (Opc) {
14308   case BO_Assign:
14309     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14310     if (getLangOpts().CPlusPlus &&
14311         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14312       VK = LHS.get()->getValueKind();
14313       OK = LHS.get()->getObjectKind();
14314     }
14315     if (!ResultTy.isNull()) {
14316       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14317       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14318 
14319       // Avoid copying a block to the heap if the block is assigned to a local
14320       // auto variable that is declared in the same scope as the block. This
14321       // optimization is unsafe if the local variable is declared in an outer
14322       // scope. For example:
14323       //
14324       // BlockTy b;
14325       // {
14326       //   b = ^{...};
14327       // }
14328       // // It is unsafe to invoke the block here if it wasn't copied to the
14329       // // heap.
14330       // b();
14331 
14332       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14333         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14334           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14335             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14336               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14337 
14338       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14339         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14340                               NTCUC_Assignment, NTCUK_Copy);
14341     }
14342     RecordModifiableNonNullParam(*this, LHS.get());
14343     break;
14344   case BO_PtrMemD:
14345   case BO_PtrMemI:
14346     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14347                                             Opc == BO_PtrMemI);
14348     break;
14349   case BO_Mul:
14350   case BO_Div:
14351     ConvertHalfVec = true;
14352     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14353                                            Opc == BO_Div);
14354     break;
14355   case BO_Rem:
14356     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14357     break;
14358   case BO_Add:
14359     ConvertHalfVec = true;
14360     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14361     break;
14362   case BO_Sub:
14363     ConvertHalfVec = true;
14364     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14365     break;
14366   case BO_Shl:
14367   case BO_Shr:
14368     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14369     break;
14370   case BO_LE:
14371   case BO_LT:
14372   case BO_GE:
14373   case BO_GT:
14374     ConvertHalfVec = true;
14375     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14376     break;
14377   case BO_EQ:
14378   case BO_NE:
14379     ConvertHalfVec = true;
14380     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14381     break;
14382   case BO_Cmp:
14383     ConvertHalfVec = true;
14384     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14385     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14386     break;
14387   case BO_And:
14388     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14389     LLVM_FALLTHROUGH;
14390   case BO_Xor:
14391   case BO_Or:
14392     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14393     break;
14394   case BO_LAnd:
14395   case BO_LOr:
14396     ConvertHalfVec = true;
14397     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14398     break;
14399   case BO_MulAssign:
14400   case BO_DivAssign:
14401     ConvertHalfVec = true;
14402     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14403                                                Opc == BO_DivAssign);
14404     CompLHSTy = CompResultTy;
14405     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14406       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14407     break;
14408   case BO_RemAssign:
14409     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14410     CompLHSTy = CompResultTy;
14411     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14412       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14413     break;
14414   case BO_AddAssign:
14415     ConvertHalfVec = true;
14416     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14417     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14418       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14419     break;
14420   case BO_SubAssign:
14421     ConvertHalfVec = true;
14422     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14423     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14424       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14425     break;
14426   case BO_ShlAssign:
14427   case BO_ShrAssign:
14428     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14429     CompLHSTy = CompResultTy;
14430     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14431       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14432     break;
14433   case BO_AndAssign:
14434   case BO_OrAssign: // fallthrough
14435     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14436     LLVM_FALLTHROUGH;
14437   case BO_XorAssign:
14438     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14439     CompLHSTy = CompResultTy;
14440     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14441       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14442     break;
14443   case BO_Comma:
14444     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14445     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14446       VK = RHS.get()->getValueKind();
14447       OK = RHS.get()->getObjectKind();
14448     }
14449     break;
14450   }
14451   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14452     return ExprError();
14453 
14454   // Some of the binary operations require promoting operands of half vector to
14455   // float vectors and truncating the result back to half vector. For now, we do
14456   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14457   // arm64).
14458   assert(
14459       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14460                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14461       "both sides are half vectors or neither sides are");
14462   ConvertHalfVec =
14463       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14464 
14465   // Check for array bounds violations for both sides of the BinaryOperator
14466   CheckArrayAccess(LHS.get());
14467   CheckArrayAccess(RHS.get());
14468 
14469   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14470     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14471                                                  &Context.Idents.get("object_setClass"),
14472                                                  SourceLocation(), LookupOrdinaryName);
14473     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14474       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14475       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14476           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14477                                         "object_setClass(")
14478           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14479                                           ",")
14480           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14481     }
14482     else
14483       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14484   }
14485   else if (const ObjCIvarRefExpr *OIRE =
14486            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14487     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14488 
14489   // Opc is not a compound assignment if CompResultTy is null.
14490   if (CompResultTy.isNull()) {
14491     if (ConvertHalfVec)
14492       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14493                                  OpLoc, CurFPFeatureOverrides());
14494     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14495                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14496   }
14497 
14498   // Handle compound assignments.
14499   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14500       OK_ObjCProperty) {
14501     VK = VK_LValue;
14502     OK = LHS.get()->getObjectKind();
14503   }
14504 
14505   // The LHS is not converted to the result type for fixed-point compound
14506   // assignment as the common type is computed on demand. Reset the CompLHSTy
14507   // to the LHS type we would have gotten after unary conversions.
14508   if (CompResultTy->isFixedPointType())
14509     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14510 
14511   if (ConvertHalfVec)
14512     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14513                                OpLoc, CurFPFeatureOverrides());
14514 
14515   return CompoundAssignOperator::Create(
14516       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14517       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14518 }
14519 
14520 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14521 /// operators are mixed in a way that suggests that the programmer forgot that
14522 /// comparison operators have higher precedence. The most typical example of
14523 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14524 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14525                                       SourceLocation OpLoc, Expr *LHSExpr,
14526                                       Expr *RHSExpr) {
14527   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14528   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14529 
14530   // Check that one of the sides is a comparison operator and the other isn't.
14531   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14532   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14533   if (isLeftComp == isRightComp)
14534     return;
14535 
14536   // Bitwise operations are sometimes used as eager logical ops.
14537   // Don't diagnose this.
14538   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14539   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14540   if (isLeftBitwise || isRightBitwise)
14541     return;
14542 
14543   SourceRange DiagRange = isLeftComp
14544                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14545                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14546   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14547   SourceRange ParensRange =
14548       isLeftComp
14549           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14550           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14551 
14552   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14553     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14554   SuggestParentheses(Self, OpLoc,
14555     Self.PDiag(diag::note_precedence_silence) << OpStr,
14556     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14557   SuggestParentheses(Self, OpLoc,
14558     Self.PDiag(diag::note_precedence_bitwise_first)
14559       << BinaryOperator::getOpcodeStr(Opc),
14560     ParensRange);
14561 }
14562 
14563 /// It accepts a '&&' expr that is inside a '||' one.
14564 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14565 /// in parentheses.
14566 static void
14567 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14568                                        BinaryOperator *Bop) {
14569   assert(Bop->getOpcode() == BO_LAnd);
14570   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14571       << Bop->getSourceRange() << OpLoc;
14572   SuggestParentheses(Self, Bop->getOperatorLoc(),
14573     Self.PDiag(diag::note_precedence_silence)
14574       << Bop->getOpcodeStr(),
14575     Bop->getSourceRange());
14576 }
14577 
14578 /// Returns true if the given expression can be evaluated as a constant
14579 /// 'true'.
14580 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14581   bool Res;
14582   return !E->isValueDependent() &&
14583          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14584 }
14585 
14586 /// Returns true if the given expression can be evaluated as a constant
14587 /// 'false'.
14588 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14589   bool Res;
14590   return !E->isValueDependent() &&
14591          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14592 }
14593 
14594 /// Look for '&&' in the left hand of a '||' expr.
14595 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14596                                              Expr *LHSExpr, Expr *RHSExpr) {
14597   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14598     if (Bop->getOpcode() == BO_LAnd) {
14599       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14600       if (EvaluatesAsFalse(S, RHSExpr))
14601         return;
14602       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14603       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14604         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14605     } else if (Bop->getOpcode() == BO_LOr) {
14606       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14607         // If it's "a || b && 1 || c" we didn't warn earlier for
14608         // "a || b && 1", but warn now.
14609         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14610           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14611       }
14612     }
14613   }
14614 }
14615 
14616 /// Look for '&&' in the right hand of a '||' expr.
14617 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14618                                              Expr *LHSExpr, Expr *RHSExpr) {
14619   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14620     if (Bop->getOpcode() == BO_LAnd) {
14621       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14622       if (EvaluatesAsFalse(S, LHSExpr))
14623         return;
14624       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14625       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14626         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14627     }
14628   }
14629 }
14630 
14631 /// Look for bitwise op in the left or right hand of a bitwise op with
14632 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14633 /// the '&' expression in parentheses.
14634 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14635                                          SourceLocation OpLoc, Expr *SubExpr) {
14636   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14637     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14638       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14639         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14640         << Bop->getSourceRange() << OpLoc;
14641       SuggestParentheses(S, Bop->getOperatorLoc(),
14642         S.PDiag(diag::note_precedence_silence)
14643           << Bop->getOpcodeStr(),
14644         Bop->getSourceRange());
14645     }
14646   }
14647 }
14648 
14649 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14650                                     Expr *SubExpr, StringRef Shift) {
14651   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14652     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14653       StringRef Op = Bop->getOpcodeStr();
14654       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14655           << Bop->getSourceRange() << OpLoc << Shift << Op;
14656       SuggestParentheses(S, Bop->getOperatorLoc(),
14657           S.PDiag(diag::note_precedence_silence) << Op,
14658           Bop->getSourceRange());
14659     }
14660   }
14661 }
14662 
14663 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14664                                  Expr *LHSExpr, Expr *RHSExpr) {
14665   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14666   if (!OCE)
14667     return;
14668 
14669   FunctionDecl *FD = OCE->getDirectCallee();
14670   if (!FD || !FD->isOverloadedOperator())
14671     return;
14672 
14673   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14674   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14675     return;
14676 
14677   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14678       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14679       << (Kind == OO_LessLess);
14680   SuggestParentheses(S, OCE->getOperatorLoc(),
14681                      S.PDiag(diag::note_precedence_silence)
14682                          << (Kind == OO_LessLess ? "<<" : ">>"),
14683                      OCE->getSourceRange());
14684   SuggestParentheses(
14685       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14686       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14687 }
14688 
14689 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14690 /// precedence.
14691 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14692                                     SourceLocation OpLoc, Expr *LHSExpr,
14693                                     Expr *RHSExpr){
14694   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14695   if (BinaryOperator::isBitwiseOp(Opc))
14696     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14697 
14698   // Diagnose "arg1 & arg2 | arg3"
14699   if ((Opc == BO_Or || Opc == BO_Xor) &&
14700       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14701     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14702     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14703   }
14704 
14705   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14706   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14707   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14708     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14709     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14710   }
14711 
14712   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14713       || Opc == BO_Shr) {
14714     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14715     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14716     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14717   }
14718 
14719   // Warn on overloaded shift operators and comparisons, such as:
14720   // cout << 5 == 4;
14721   if (BinaryOperator::isComparisonOp(Opc))
14722     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14723 }
14724 
14725 // Binary Operators.  'Tok' is the token for the operator.
14726 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14727                             tok::TokenKind Kind,
14728                             Expr *LHSExpr, Expr *RHSExpr) {
14729   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14730   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14731   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14732 
14733   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14734   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14735 
14736   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14737 }
14738 
14739 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14740                        UnresolvedSetImpl &Functions) {
14741   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14742   if (OverOp != OO_None && OverOp != OO_Equal)
14743     LookupOverloadedOperatorName(OverOp, S, Functions);
14744 
14745   // In C++20 onwards, we may have a second operator to look up.
14746   if (getLangOpts().CPlusPlus20) {
14747     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14748       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14749   }
14750 }
14751 
14752 /// Build an overloaded binary operator expression in the given scope.
14753 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14754                                        BinaryOperatorKind Opc,
14755                                        Expr *LHS, Expr *RHS) {
14756   switch (Opc) {
14757   case BO_Assign:
14758   case BO_DivAssign:
14759   case BO_RemAssign:
14760   case BO_SubAssign:
14761   case BO_AndAssign:
14762   case BO_OrAssign:
14763   case BO_XorAssign:
14764     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14765     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14766     break;
14767   default:
14768     break;
14769   }
14770 
14771   // Find all of the overloaded operators visible from this point.
14772   UnresolvedSet<16> Functions;
14773   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14774 
14775   // Build the (potentially-overloaded, potentially-dependent)
14776   // binary operation.
14777   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14778 }
14779 
14780 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14781                             BinaryOperatorKind Opc,
14782                             Expr *LHSExpr, Expr *RHSExpr) {
14783   ExprResult LHS, RHS;
14784   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14785   if (!LHS.isUsable() || !RHS.isUsable())
14786     return ExprError();
14787   LHSExpr = LHS.get();
14788   RHSExpr = RHS.get();
14789 
14790   // We want to end up calling one of checkPseudoObjectAssignment
14791   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14792   // both expressions are overloadable or either is type-dependent),
14793   // or CreateBuiltinBinOp (in any other case).  We also want to get
14794   // any placeholder types out of the way.
14795 
14796   // Handle pseudo-objects in the LHS.
14797   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14798     // Assignments with a pseudo-object l-value need special analysis.
14799     if (pty->getKind() == BuiltinType::PseudoObject &&
14800         BinaryOperator::isAssignmentOp(Opc))
14801       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14802 
14803     // Don't resolve overloads if the other type is overloadable.
14804     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14805       // We can't actually test that if we still have a placeholder,
14806       // though.  Fortunately, none of the exceptions we see in that
14807       // code below are valid when the LHS is an overload set.  Note
14808       // that an overload set can be dependently-typed, but it never
14809       // instantiates to having an overloadable type.
14810       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14811       if (resolvedRHS.isInvalid()) return ExprError();
14812       RHSExpr = resolvedRHS.get();
14813 
14814       if (RHSExpr->isTypeDependent() ||
14815           RHSExpr->getType()->isOverloadableType())
14816         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14817     }
14818 
14819     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14820     // template, diagnose the missing 'template' keyword instead of diagnosing
14821     // an invalid use of a bound member function.
14822     //
14823     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14824     // to C++1z [over.over]/1.4, but we already checked for that case above.
14825     if (Opc == BO_LT && inTemplateInstantiation() &&
14826         (pty->getKind() == BuiltinType::BoundMember ||
14827          pty->getKind() == BuiltinType::Overload)) {
14828       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14829       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14830           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14831             return isa<FunctionTemplateDecl>(ND);
14832           })) {
14833         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14834                                 : OE->getNameLoc(),
14835              diag::err_template_kw_missing)
14836           << OE->getName().getAsString() << "";
14837         return ExprError();
14838       }
14839     }
14840 
14841     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14842     if (LHS.isInvalid()) return ExprError();
14843     LHSExpr = LHS.get();
14844   }
14845 
14846   // Handle pseudo-objects in the RHS.
14847   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14848     // An overload in the RHS can potentially be resolved by the type
14849     // being assigned to.
14850     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14851       if (getLangOpts().CPlusPlus &&
14852           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14853            LHSExpr->getType()->isOverloadableType()))
14854         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14855 
14856       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14857     }
14858 
14859     // Don't resolve overloads if the other type is overloadable.
14860     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14861         LHSExpr->getType()->isOverloadableType())
14862       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14863 
14864     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14865     if (!resolvedRHS.isUsable()) return ExprError();
14866     RHSExpr = resolvedRHS.get();
14867   }
14868 
14869   if (getLangOpts().CPlusPlus) {
14870     // If either expression is type-dependent, always build an
14871     // overloaded op.
14872     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14873       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14874 
14875     // Otherwise, build an overloaded op if either expression has an
14876     // overloadable type.
14877     if (LHSExpr->getType()->isOverloadableType() ||
14878         RHSExpr->getType()->isOverloadableType())
14879       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14880   }
14881 
14882   if (getLangOpts().RecoveryAST &&
14883       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14884     assert(!getLangOpts().CPlusPlus);
14885     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14886            "Should only occur in error-recovery path.");
14887     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14888       // C [6.15.16] p3:
14889       // An assignment expression has the value of the left operand after the
14890       // assignment, but is not an lvalue.
14891       return CompoundAssignOperator::Create(
14892           Context, LHSExpr, RHSExpr, Opc,
14893           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14894           OpLoc, CurFPFeatureOverrides());
14895     QualType ResultType;
14896     switch (Opc) {
14897     case BO_Assign:
14898       ResultType = LHSExpr->getType().getUnqualifiedType();
14899       break;
14900     case BO_LT:
14901     case BO_GT:
14902     case BO_LE:
14903     case BO_GE:
14904     case BO_EQ:
14905     case BO_NE:
14906     case BO_LAnd:
14907     case BO_LOr:
14908       // These operators have a fixed result type regardless of operands.
14909       ResultType = Context.IntTy;
14910       break;
14911     case BO_Comma:
14912       ResultType = RHSExpr->getType();
14913       break;
14914     default:
14915       ResultType = Context.DependentTy;
14916       break;
14917     }
14918     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14919                                   VK_PRValue, OK_Ordinary, OpLoc,
14920                                   CurFPFeatureOverrides());
14921   }
14922 
14923   // Build a built-in binary operation.
14924   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14925 }
14926 
14927 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14928   if (T.isNull() || T->isDependentType())
14929     return false;
14930 
14931   if (!T->isPromotableIntegerType())
14932     return true;
14933 
14934   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14935 }
14936 
14937 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14938                                       UnaryOperatorKind Opc,
14939                                       Expr *InputExpr) {
14940   ExprResult Input = InputExpr;
14941   ExprValueKind VK = VK_PRValue;
14942   ExprObjectKind OK = OK_Ordinary;
14943   QualType resultType;
14944   bool CanOverflow = false;
14945 
14946   bool ConvertHalfVec = false;
14947   if (getLangOpts().OpenCL) {
14948     QualType Ty = InputExpr->getType();
14949     // The only legal unary operation for atomics is '&'.
14950     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14951     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14952     // only with a builtin functions and therefore should be disallowed here.
14953         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14954         || Ty->isBlockPointerType())) {
14955       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14956                        << InputExpr->getType()
14957                        << Input.get()->getSourceRange());
14958     }
14959   }
14960 
14961   switch (Opc) {
14962   case UO_PreInc:
14963   case UO_PreDec:
14964   case UO_PostInc:
14965   case UO_PostDec:
14966     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14967                                                 OpLoc,
14968                                                 Opc == UO_PreInc ||
14969                                                 Opc == UO_PostInc,
14970                                                 Opc == UO_PreInc ||
14971                                                 Opc == UO_PreDec);
14972     CanOverflow = isOverflowingIntegerType(Context, resultType);
14973     break;
14974   case UO_AddrOf:
14975     resultType = CheckAddressOfOperand(Input, OpLoc);
14976     CheckAddressOfNoDeref(InputExpr);
14977     RecordModifiableNonNullParam(*this, InputExpr);
14978     break;
14979   case UO_Deref: {
14980     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14981     if (Input.isInvalid()) return ExprError();
14982     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14983     break;
14984   }
14985   case UO_Plus:
14986   case UO_Minus:
14987     CanOverflow = Opc == UO_Minus &&
14988                   isOverflowingIntegerType(Context, Input.get()->getType());
14989     Input = UsualUnaryConversions(Input.get());
14990     if (Input.isInvalid()) return ExprError();
14991     // Unary plus and minus require promoting an operand of half vector to a
14992     // float vector and truncating the result back to a half vector. For now, we
14993     // do this only when HalfArgsAndReturns is set (that is, when the target is
14994     // arm or arm64).
14995     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14996 
14997     // If the operand is a half vector, promote it to a float vector.
14998     if (ConvertHalfVec)
14999       Input = convertVector(Input.get(), Context.FloatTy, *this);
15000     resultType = Input.get()->getType();
15001     if (resultType->isDependentType())
15002       break;
15003     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15004       break;
15005     else if (resultType->isVectorType() &&
15006              // The z vector extensions don't allow + or - with bool vectors.
15007              (!Context.getLangOpts().ZVector ||
15008               resultType->castAs<VectorType>()->getVectorKind() !=
15009               VectorType::AltiVecBool))
15010       break;
15011     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15012              Opc == UO_Plus &&
15013              resultType->isPointerType())
15014       break;
15015 
15016     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15017       << resultType << Input.get()->getSourceRange());
15018 
15019   case UO_Not: // bitwise complement
15020     Input = UsualUnaryConversions(Input.get());
15021     if (Input.isInvalid())
15022       return ExprError();
15023     resultType = Input.get()->getType();
15024     if (resultType->isDependentType())
15025       break;
15026     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15027     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15028       // C99 does not support '~' for complex conjugation.
15029       Diag(OpLoc, diag::ext_integer_complement_complex)
15030           << resultType << Input.get()->getSourceRange();
15031     else if (resultType->hasIntegerRepresentation())
15032       break;
15033     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15034       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15035       // on vector float types.
15036       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15037       if (!T->isIntegerType())
15038         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15039                           << resultType << Input.get()->getSourceRange());
15040     } else {
15041       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15042                        << resultType << Input.get()->getSourceRange());
15043     }
15044     break;
15045 
15046   case UO_LNot: // logical negation
15047     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15048     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15049     if (Input.isInvalid()) return ExprError();
15050     resultType = Input.get()->getType();
15051 
15052     // Though we still have to promote half FP to float...
15053     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15054       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15055       resultType = Context.FloatTy;
15056     }
15057 
15058     if (resultType->isDependentType())
15059       break;
15060     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15061       // C99 6.5.3.3p1: ok, fallthrough;
15062       if (Context.getLangOpts().CPlusPlus) {
15063         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15064         // operand contextually converted to bool.
15065         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15066                                   ScalarTypeToBooleanCastKind(resultType));
15067       } else if (Context.getLangOpts().OpenCL &&
15068                  Context.getLangOpts().OpenCLVersion < 120) {
15069         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15070         // operate on scalar float types.
15071         if (!resultType->isIntegerType() && !resultType->isPointerType())
15072           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15073                            << resultType << Input.get()->getSourceRange());
15074       }
15075     } else if (resultType->isExtVectorType()) {
15076       if (Context.getLangOpts().OpenCL &&
15077           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15078         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15079         // operate on vector float types.
15080         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15081         if (!T->isIntegerType())
15082           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15083                            << resultType << Input.get()->getSourceRange());
15084       }
15085       // Vector logical not returns the signed variant of the operand type.
15086       resultType = GetSignedVectorType(resultType);
15087       break;
15088     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15089       const VectorType *VTy = resultType->castAs<VectorType>();
15090       if (VTy->getVectorKind() != VectorType::GenericVector)
15091         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15092                          << resultType << Input.get()->getSourceRange());
15093 
15094       // Vector logical not returns the signed variant of the operand type.
15095       resultType = GetSignedVectorType(resultType);
15096       break;
15097     } else {
15098       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15099         << resultType << Input.get()->getSourceRange());
15100     }
15101 
15102     // LNot always has type int. C99 6.5.3.3p5.
15103     // In C++, it's bool. C++ 5.3.1p8
15104     resultType = Context.getLogicalOperationType();
15105     break;
15106   case UO_Real:
15107   case UO_Imag:
15108     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15109     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15110     // complex l-values to ordinary l-values and all other values to r-values.
15111     if (Input.isInvalid()) return ExprError();
15112     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15113       if (Input.get()->isGLValue() &&
15114           Input.get()->getObjectKind() == OK_Ordinary)
15115         VK = Input.get()->getValueKind();
15116     } else if (!getLangOpts().CPlusPlus) {
15117       // In C, a volatile scalar is read by __imag. In C++, it is not.
15118       Input = DefaultLvalueConversion(Input.get());
15119     }
15120     break;
15121   case UO_Extension:
15122     resultType = Input.get()->getType();
15123     VK = Input.get()->getValueKind();
15124     OK = Input.get()->getObjectKind();
15125     break;
15126   case UO_Coawait:
15127     // It's unnecessary to represent the pass-through operator co_await in the
15128     // AST; just return the input expression instead.
15129     assert(!Input.get()->getType()->isDependentType() &&
15130                    "the co_await expression must be non-dependant before "
15131                    "building operator co_await");
15132     return Input;
15133   }
15134   if (resultType.isNull() || Input.isInvalid())
15135     return ExprError();
15136 
15137   // Check for array bounds violations in the operand of the UnaryOperator,
15138   // except for the '*' and '&' operators that have to be handled specially
15139   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15140   // that are explicitly defined as valid by the standard).
15141   if (Opc != UO_AddrOf && Opc != UO_Deref)
15142     CheckArrayAccess(Input.get());
15143 
15144   auto *UO =
15145       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15146                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15147 
15148   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15149       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15150       !isUnevaluatedContext())
15151     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15152 
15153   // Convert the result back to a half vector.
15154   if (ConvertHalfVec)
15155     return convertVector(UO, Context.HalfTy, *this);
15156   return UO;
15157 }
15158 
15159 /// Determine whether the given expression is a qualified member
15160 /// access expression, of a form that could be turned into a pointer to member
15161 /// with the address-of operator.
15162 bool Sema::isQualifiedMemberAccess(Expr *E) {
15163   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15164     if (!DRE->getQualifier())
15165       return false;
15166 
15167     ValueDecl *VD = DRE->getDecl();
15168     if (!VD->isCXXClassMember())
15169       return false;
15170 
15171     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15172       return true;
15173     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15174       return Method->isInstance();
15175 
15176     return false;
15177   }
15178 
15179   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15180     if (!ULE->getQualifier())
15181       return false;
15182 
15183     for (NamedDecl *D : ULE->decls()) {
15184       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15185         if (Method->isInstance())
15186           return true;
15187       } else {
15188         // Overload set does not contain methods.
15189         break;
15190       }
15191     }
15192 
15193     return false;
15194   }
15195 
15196   return false;
15197 }
15198 
15199 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15200                               UnaryOperatorKind Opc, Expr *Input) {
15201   // First things first: handle placeholders so that the
15202   // overloaded-operator check considers the right type.
15203   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15204     // Increment and decrement of pseudo-object references.
15205     if (pty->getKind() == BuiltinType::PseudoObject &&
15206         UnaryOperator::isIncrementDecrementOp(Opc))
15207       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15208 
15209     // extension is always a builtin operator.
15210     if (Opc == UO_Extension)
15211       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15212 
15213     // & gets special logic for several kinds of placeholder.
15214     // The builtin code knows what to do.
15215     if (Opc == UO_AddrOf &&
15216         (pty->getKind() == BuiltinType::Overload ||
15217          pty->getKind() == BuiltinType::UnknownAny ||
15218          pty->getKind() == BuiltinType::BoundMember))
15219       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15220 
15221     // Anything else needs to be handled now.
15222     ExprResult Result = CheckPlaceholderExpr(Input);
15223     if (Result.isInvalid()) return ExprError();
15224     Input = Result.get();
15225   }
15226 
15227   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15228       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15229       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15230     // Find all of the overloaded operators visible from this point.
15231     UnresolvedSet<16> Functions;
15232     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15233     if (S && OverOp != OO_None)
15234       LookupOverloadedOperatorName(OverOp, S, Functions);
15235 
15236     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15237   }
15238 
15239   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15240 }
15241 
15242 // Unary Operators.  'Tok' is the token for the operator.
15243 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15244                               tok::TokenKind Op, Expr *Input) {
15245   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15246 }
15247 
15248 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15249 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15250                                 LabelDecl *TheDecl) {
15251   TheDecl->markUsed(Context);
15252   // Create the AST node.  The address of a label always has type 'void*'.
15253   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15254                                      Context.getPointerType(Context.VoidTy));
15255 }
15256 
15257 void Sema::ActOnStartStmtExpr() {
15258   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15259 }
15260 
15261 void Sema::ActOnStmtExprError() {
15262   // Note that function is also called by TreeTransform when leaving a
15263   // StmtExpr scope without rebuilding anything.
15264 
15265   DiscardCleanupsInEvaluationContext();
15266   PopExpressionEvaluationContext();
15267 }
15268 
15269 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15270                                SourceLocation RPLoc) {
15271   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15272 }
15273 
15274 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15275                                SourceLocation RPLoc, unsigned TemplateDepth) {
15276   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15277   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15278 
15279   if (hasAnyUnrecoverableErrorsInThisFunction())
15280     DiscardCleanupsInEvaluationContext();
15281   assert(!Cleanup.exprNeedsCleanups() &&
15282          "cleanups within StmtExpr not correctly bound!");
15283   PopExpressionEvaluationContext();
15284 
15285   // FIXME: there are a variety of strange constraints to enforce here, for
15286   // example, it is not possible to goto into a stmt expression apparently.
15287   // More semantic analysis is needed.
15288 
15289   // If there are sub-stmts in the compound stmt, take the type of the last one
15290   // as the type of the stmtexpr.
15291   QualType Ty = Context.VoidTy;
15292   bool StmtExprMayBindToTemp = false;
15293   if (!Compound->body_empty()) {
15294     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15295     if (const auto *LastStmt =
15296             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15297       if (const Expr *Value = LastStmt->getExprStmt()) {
15298         StmtExprMayBindToTemp = true;
15299         Ty = Value->getType();
15300       }
15301     }
15302   }
15303 
15304   // FIXME: Check that expression type is complete/non-abstract; statement
15305   // expressions are not lvalues.
15306   Expr *ResStmtExpr =
15307       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15308   if (StmtExprMayBindToTemp)
15309     return MaybeBindToTemporary(ResStmtExpr);
15310   return ResStmtExpr;
15311 }
15312 
15313 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15314   if (ER.isInvalid())
15315     return ExprError();
15316 
15317   // Do function/array conversion on the last expression, but not
15318   // lvalue-to-rvalue.  However, initialize an unqualified type.
15319   ER = DefaultFunctionArrayConversion(ER.get());
15320   if (ER.isInvalid())
15321     return ExprError();
15322   Expr *E = ER.get();
15323 
15324   if (E->isTypeDependent())
15325     return E;
15326 
15327   // In ARC, if the final expression ends in a consume, splice
15328   // the consume out and bind it later.  In the alternate case
15329   // (when dealing with a retainable type), the result
15330   // initialization will create a produce.  In both cases the
15331   // result will be +1, and we'll need to balance that out with
15332   // a bind.
15333   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15334   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15335     return Cast->getSubExpr();
15336 
15337   // FIXME: Provide a better location for the initialization.
15338   return PerformCopyInitialization(
15339       InitializedEntity::InitializeStmtExprResult(
15340           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15341       SourceLocation(), E);
15342 }
15343 
15344 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15345                                       TypeSourceInfo *TInfo,
15346                                       ArrayRef<OffsetOfComponent> Components,
15347                                       SourceLocation RParenLoc) {
15348   QualType ArgTy = TInfo->getType();
15349   bool Dependent = ArgTy->isDependentType();
15350   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15351 
15352   // We must have at least one component that refers to the type, and the first
15353   // one is known to be a field designator.  Verify that the ArgTy represents
15354   // a struct/union/class.
15355   if (!Dependent && !ArgTy->isRecordType())
15356     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15357                        << ArgTy << TypeRange);
15358 
15359   // Type must be complete per C99 7.17p3 because a declaring a variable
15360   // with an incomplete type would be ill-formed.
15361   if (!Dependent
15362       && RequireCompleteType(BuiltinLoc, ArgTy,
15363                              diag::err_offsetof_incomplete_type, TypeRange))
15364     return ExprError();
15365 
15366   bool DidWarnAboutNonPOD = false;
15367   QualType CurrentType = ArgTy;
15368   SmallVector<OffsetOfNode, 4> Comps;
15369   SmallVector<Expr*, 4> Exprs;
15370   for (const OffsetOfComponent &OC : Components) {
15371     if (OC.isBrackets) {
15372       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15373       if (!CurrentType->isDependentType()) {
15374         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15375         if(!AT)
15376           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15377                            << CurrentType);
15378         CurrentType = AT->getElementType();
15379       } else
15380         CurrentType = Context.DependentTy;
15381 
15382       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15383       if (IdxRval.isInvalid())
15384         return ExprError();
15385       Expr *Idx = IdxRval.get();
15386 
15387       // The expression must be an integral expression.
15388       // FIXME: An integral constant expression?
15389       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15390           !Idx->getType()->isIntegerType())
15391         return ExprError(
15392             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15393             << Idx->getSourceRange());
15394 
15395       // Record this array index.
15396       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15397       Exprs.push_back(Idx);
15398       continue;
15399     }
15400 
15401     // Offset of a field.
15402     if (CurrentType->isDependentType()) {
15403       // We have the offset of a field, but we can't look into the dependent
15404       // type. Just record the identifier of the field.
15405       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15406       CurrentType = Context.DependentTy;
15407       continue;
15408     }
15409 
15410     // We need to have a complete type to look into.
15411     if (RequireCompleteType(OC.LocStart, CurrentType,
15412                             diag::err_offsetof_incomplete_type))
15413       return ExprError();
15414 
15415     // Look for the designated field.
15416     const RecordType *RC = CurrentType->getAs<RecordType>();
15417     if (!RC)
15418       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15419                        << CurrentType);
15420     RecordDecl *RD = RC->getDecl();
15421 
15422     // C++ [lib.support.types]p5:
15423     //   The macro offsetof accepts a restricted set of type arguments in this
15424     //   International Standard. type shall be a POD structure or a POD union
15425     //   (clause 9).
15426     // C++11 [support.types]p4:
15427     //   If type is not a standard-layout class (Clause 9), the results are
15428     //   undefined.
15429     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15430       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15431       unsigned DiagID =
15432         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15433                             : diag::ext_offsetof_non_pod_type;
15434 
15435       if (!IsSafe && !DidWarnAboutNonPOD &&
15436           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15437                               PDiag(DiagID)
15438                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15439                               << CurrentType))
15440         DidWarnAboutNonPOD = true;
15441     }
15442 
15443     // Look for the field.
15444     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15445     LookupQualifiedName(R, RD);
15446     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15447     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15448     if (!MemberDecl) {
15449       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15450         MemberDecl = IndirectMemberDecl->getAnonField();
15451     }
15452 
15453     if (!MemberDecl)
15454       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15455                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15456                                                               OC.LocEnd));
15457 
15458     // C99 7.17p3:
15459     //   (If the specified member is a bit-field, the behavior is undefined.)
15460     //
15461     // We diagnose this as an error.
15462     if (MemberDecl->isBitField()) {
15463       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15464         << MemberDecl->getDeclName()
15465         << SourceRange(BuiltinLoc, RParenLoc);
15466       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15467       return ExprError();
15468     }
15469 
15470     RecordDecl *Parent = MemberDecl->getParent();
15471     if (IndirectMemberDecl)
15472       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15473 
15474     // If the member was found in a base class, introduce OffsetOfNodes for
15475     // the base class indirections.
15476     CXXBasePaths Paths;
15477     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15478                       Paths)) {
15479       if (Paths.getDetectedVirtual()) {
15480         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15481           << MemberDecl->getDeclName()
15482           << SourceRange(BuiltinLoc, RParenLoc);
15483         return ExprError();
15484       }
15485 
15486       CXXBasePath &Path = Paths.front();
15487       for (const CXXBasePathElement &B : Path)
15488         Comps.push_back(OffsetOfNode(B.Base));
15489     }
15490 
15491     if (IndirectMemberDecl) {
15492       for (auto *FI : IndirectMemberDecl->chain()) {
15493         assert(isa<FieldDecl>(FI));
15494         Comps.push_back(OffsetOfNode(OC.LocStart,
15495                                      cast<FieldDecl>(FI), OC.LocEnd));
15496       }
15497     } else
15498       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15499 
15500     CurrentType = MemberDecl->getType().getNonReferenceType();
15501   }
15502 
15503   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15504                               Comps, Exprs, RParenLoc);
15505 }
15506 
15507 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15508                                       SourceLocation BuiltinLoc,
15509                                       SourceLocation TypeLoc,
15510                                       ParsedType ParsedArgTy,
15511                                       ArrayRef<OffsetOfComponent> Components,
15512                                       SourceLocation RParenLoc) {
15513 
15514   TypeSourceInfo *ArgTInfo;
15515   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15516   if (ArgTy.isNull())
15517     return ExprError();
15518 
15519   if (!ArgTInfo)
15520     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15521 
15522   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15523 }
15524 
15525 
15526 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15527                                  Expr *CondExpr,
15528                                  Expr *LHSExpr, Expr *RHSExpr,
15529                                  SourceLocation RPLoc) {
15530   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15531 
15532   ExprValueKind VK = VK_PRValue;
15533   ExprObjectKind OK = OK_Ordinary;
15534   QualType resType;
15535   bool CondIsTrue = false;
15536   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15537     resType = Context.DependentTy;
15538   } else {
15539     // The conditional expression is required to be a constant expression.
15540     llvm::APSInt condEval(32);
15541     ExprResult CondICE = VerifyIntegerConstantExpression(
15542         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15543     if (CondICE.isInvalid())
15544       return ExprError();
15545     CondExpr = CondICE.get();
15546     CondIsTrue = condEval.getZExtValue();
15547 
15548     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15549     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15550 
15551     resType = ActiveExpr->getType();
15552     VK = ActiveExpr->getValueKind();
15553     OK = ActiveExpr->getObjectKind();
15554   }
15555 
15556   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15557                                   resType, VK, OK, RPLoc, CondIsTrue);
15558 }
15559 
15560 //===----------------------------------------------------------------------===//
15561 // Clang Extensions.
15562 //===----------------------------------------------------------------------===//
15563 
15564 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15565 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15566   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15567 
15568   if (LangOpts.CPlusPlus) {
15569     MangleNumberingContext *MCtx;
15570     Decl *ManglingContextDecl;
15571     std::tie(MCtx, ManglingContextDecl) =
15572         getCurrentMangleNumberContext(Block->getDeclContext());
15573     if (MCtx) {
15574       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15575       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15576     }
15577   }
15578 
15579   PushBlockScope(CurScope, Block);
15580   CurContext->addDecl(Block);
15581   if (CurScope)
15582     PushDeclContext(CurScope, Block);
15583   else
15584     CurContext = Block;
15585 
15586   getCurBlock()->HasImplicitReturnType = true;
15587 
15588   // Enter a new evaluation context to insulate the block from any
15589   // cleanups from the enclosing full-expression.
15590   PushExpressionEvaluationContext(
15591       ExpressionEvaluationContext::PotentiallyEvaluated);
15592 }
15593 
15594 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15595                                Scope *CurScope) {
15596   assert(ParamInfo.getIdentifier() == nullptr &&
15597          "block-id should have no identifier!");
15598   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15599   BlockScopeInfo *CurBlock = getCurBlock();
15600 
15601   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15602   QualType T = Sig->getType();
15603 
15604   // FIXME: We should allow unexpanded parameter packs here, but that would,
15605   // in turn, make the block expression contain unexpanded parameter packs.
15606   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15607     // Drop the parameters.
15608     FunctionProtoType::ExtProtoInfo EPI;
15609     EPI.HasTrailingReturn = false;
15610     EPI.TypeQuals.addConst();
15611     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15612     Sig = Context.getTrivialTypeSourceInfo(T);
15613   }
15614 
15615   // GetTypeForDeclarator always produces a function type for a block
15616   // literal signature.  Furthermore, it is always a FunctionProtoType
15617   // unless the function was written with a typedef.
15618   assert(T->isFunctionType() &&
15619          "GetTypeForDeclarator made a non-function block signature");
15620 
15621   // Look for an explicit signature in that function type.
15622   FunctionProtoTypeLoc ExplicitSignature;
15623 
15624   if ((ExplicitSignature = Sig->getTypeLoc()
15625                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15626 
15627     // Check whether that explicit signature was synthesized by
15628     // GetTypeForDeclarator.  If so, don't save that as part of the
15629     // written signature.
15630     if (ExplicitSignature.getLocalRangeBegin() ==
15631         ExplicitSignature.getLocalRangeEnd()) {
15632       // This would be much cheaper if we stored TypeLocs instead of
15633       // TypeSourceInfos.
15634       TypeLoc Result = ExplicitSignature.getReturnLoc();
15635       unsigned Size = Result.getFullDataSize();
15636       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15637       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15638 
15639       ExplicitSignature = FunctionProtoTypeLoc();
15640     }
15641   }
15642 
15643   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15644   CurBlock->FunctionType = T;
15645 
15646   const auto *Fn = T->castAs<FunctionType>();
15647   QualType RetTy = Fn->getReturnType();
15648   bool isVariadic =
15649       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15650 
15651   CurBlock->TheDecl->setIsVariadic(isVariadic);
15652 
15653   // Context.DependentTy is used as a placeholder for a missing block
15654   // return type.  TODO:  what should we do with declarators like:
15655   //   ^ * { ... }
15656   // If the answer is "apply template argument deduction"....
15657   if (RetTy != Context.DependentTy) {
15658     CurBlock->ReturnType = RetTy;
15659     CurBlock->TheDecl->setBlockMissingReturnType(false);
15660     CurBlock->HasImplicitReturnType = false;
15661   }
15662 
15663   // Push block parameters from the declarator if we had them.
15664   SmallVector<ParmVarDecl*, 8> Params;
15665   if (ExplicitSignature) {
15666     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15667       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15668       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15669           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15670         // Diagnose this as an extension in C17 and earlier.
15671         if (!getLangOpts().C2x)
15672           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15673       }
15674       Params.push_back(Param);
15675     }
15676 
15677   // Fake up parameter variables if we have a typedef, like
15678   //   ^ fntype { ... }
15679   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15680     for (const auto &I : Fn->param_types()) {
15681       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15682           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15683       Params.push_back(Param);
15684     }
15685   }
15686 
15687   // Set the parameters on the block decl.
15688   if (!Params.empty()) {
15689     CurBlock->TheDecl->setParams(Params);
15690     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15691                              /*CheckParameterNames=*/false);
15692   }
15693 
15694   // Finally we can process decl attributes.
15695   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15696 
15697   // Put the parameter variables in scope.
15698   for (auto AI : CurBlock->TheDecl->parameters()) {
15699     AI->setOwningFunction(CurBlock->TheDecl);
15700 
15701     // If this has an identifier, add it to the scope stack.
15702     if (AI->getIdentifier()) {
15703       CheckShadow(CurBlock->TheScope, AI);
15704 
15705       PushOnScopeChains(AI, CurBlock->TheScope);
15706     }
15707   }
15708 }
15709 
15710 /// ActOnBlockError - If there is an error parsing a block, this callback
15711 /// is invoked to pop the information about the block from the action impl.
15712 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15713   // Leave the expression-evaluation context.
15714   DiscardCleanupsInEvaluationContext();
15715   PopExpressionEvaluationContext();
15716 
15717   // Pop off CurBlock, handle nested blocks.
15718   PopDeclContext();
15719   PopFunctionScopeInfo();
15720 }
15721 
15722 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15723 /// literal was successfully completed.  ^(int x){...}
15724 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15725                                     Stmt *Body, Scope *CurScope) {
15726   // If blocks are disabled, emit an error.
15727   if (!LangOpts.Blocks)
15728     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15729 
15730   // Leave the expression-evaluation context.
15731   if (hasAnyUnrecoverableErrorsInThisFunction())
15732     DiscardCleanupsInEvaluationContext();
15733   assert(!Cleanup.exprNeedsCleanups() &&
15734          "cleanups within block not correctly bound!");
15735   PopExpressionEvaluationContext();
15736 
15737   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15738   BlockDecl *BD = BSI->TheDecl;
15739 
15740   if (BSI->HasImplicitReturnType)
15741     deduceClosureReturnType(*BSI);
15742 
15743   QualType RetTy = Context.VoidTy;
15744   if (!BSI->ReturnType.isNull())
15745     RetTy = BSI->ReturnType;
15746 
15747   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15748   QualType BlockTy;
15749 
15750   // If the user wrote a function type in some form, try to use that.
15751   if (!BSI->FunctionType.isNull()) {
15752     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15753 
15754     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15755     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15756 
15757     // Turn protoless block types into nullary block types.
15758     if (isa<FunctionNoProtoType>(FTy)) {
15759       FunctionProtoType::ExtProtoInfo EPI;
15760       EPI.ExtInfo = Ext;
15761       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15762 
15763     // Otherwise, if we don't need to change anything about the function type,
15764     // preserve its sugar structure.
15765     } else if (FTy->getReturnType() == RetTy &&
15766                (!NoReturn || FTy->getNoReturnAttr())) {
15767       BlockTy = BSI->FunctionType;
15768 
15769     // Otherwise, make the minimal modifications to the function type.
15770     } else {
15771       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15772       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15773       EPI.TypeQuals = Qualifiers();
15774       EPI.ExtInfo = Ext;
15775       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15776     }
15777 
15778   // If we don't have a function type, just build one from nothing.
15779   } else {
15780     FunctionProtoType::ExtProtoInfo EPI;
15781     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15782     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15783   }
15784 
15785   DiagnoseUnusedParameters(BD->parameters());
15786   BlockTy = Context.getBlockPointerType(BlockTy);
15787 
15788   // If needed, diagnose invalid gotos and switches in the block.
15789   if (getCurFunction()->NeedsScopeChecking() &&
15790       !PP.isCodeCompletionEnabled())
15791     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15792 
15793   BD->setBody(cast<CompoundStmt>(Body));
15794 
15795   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15796     DiagnoseUnguardedAvailabilityViolations(BD);
15797 
15798   // Try to apply the named return value optimization. We have to check again
15799   // if we can do this, though, because blocks keep return statements around
15800   // to deduce an implicit return type.
15801   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15802       !BD->isDependentContext())
15803     computeNRVO(Body, BSI);
15804 
15805   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15806       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15807     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15808                           NTCUK_Destruct|NTCUK_Copy);
15809 
15810   PopDeclContext();
15811 
15812   // Set the captured variables on the block.
15813   SmallVector<BlockDecl::Capture, 4> Captures;
15814   for (Capture &Cap : BSI->Captures) {
15815     if (Cap.isInvalid() || Cap.isThisCapture())
15816       continue;
15817 
15818     VarDecl *Var = Cap.getVariable();
15819     Expr *CopyExpr = nullptr;
15820     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15821       if (const RecordType *Record =
15822               Cap.getCaptureType()->getAs<RecordType>()) {
15823         // The capture logic needs the destructor, so make sure we mark it.
15824         // Usually this is unnecessary because most local variables have
15825         // their destructors marked at declaration time, but parameters are
15826         // an exception because it's technically only the call site that
15827         // actually requires the destructor.
15828         if (isa<ParmVarDecl>(Var))
15829           FinalizeVarWithDestructor(Var, Record);
15830 
15831         // Enter a separate potentially-evaluated context while building block
15832         // initializers to isolate their cleanups from those of the block
15833         // itself.
15834         // FIXME: Is this appropriate even when the block itself occurs in an
15835         // unevaluated operand?
15836         EnterExpressionEvaluationContext EvalContext(
15837             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15838 
15839         SourceLocation Loc = Cap.getLocation();
15840 
15841         ExprResult Result = BuildDeclarationNameExpr(
15842             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15843 
15844         // According to the blocks spec, the capture of a variable from
15845         // the stack requires a const copy constructor.  This is not true
15846         // of the copy/move done to move a __block variable to the heap.
15847         if (!Result.isInvalid() &&
15848             !Result.get()->getType().isConstQualified()) {
15849           Result = ImpCastExprToType(Result.get(),
15850                                      Result.get()->getType().withConst(),
15851                                      CK_NoOp, VK_LValue);
15852         }
15853 
15854         if (!Result.isInvalid()) {
15855           Result = PerformCopyInitialization(
15856               InitializedEntity::InitializeBlock(Var->getLocation(),
15857                                                  Cap.getCaptureType()),
15858               Loc, Result.get());
15859         }
15860 
15861         // Build a full-expression copy expression if initialization
15862         // succeeded and used a non-trivial constructor.  Recover from
15863         // errors by pretending that the copy isn't necessary.
15864         if (!Result.isInvalid() &&
15865             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15866                 ->isTrivial()) {
15867           Result = MaybeCreateExprWithCleanups(Result);
15868           CopyExpr = Result.get();
15869         }
15870       }
15871     }
15872 
15873     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15874                               CopyExpr);
15875     Captures.push_back(NewCap);
15876   }
15877   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15878 
15879   // Pop the block scope now but keep it alive to the end of this function.
15880   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15881   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15882 
15883   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15884 
15885   // If the block isn't obviously global, i.e. it captures anything at
15886   // all, then we need to do a few things in the surrounding context:
15887   if (Result->getBlockDecl()->hasCaptures()) {
15888     // First, this expression has a new cleanup object.
15889     ExprCleanupObjects.push_back(Result->getBlockDecl());
15890     Cleanup.setExprNeedsCleanups(true);
15891 
15892     // It also gets a branch-protected scope if any of the captured
15893     // variables needs destruction.
15894     for (const auto &CI : Result->getBlockDecl()->captures()) {
15895       const VarDecl *var = CI.getVariable();
15896       if (var->getType().isDestructedType() != QualType::DK_none) {
15897         setFunctionHasBranchProtectedScope();
15898         break;
15899       }
15900     }
15901   }
15902 
15903   if (getCurFunction())
15904     getCurFunction()->addBlock(BD);
15905 
15906   return Result;
15907 }
15908 
15909 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15910                             SourceLocation RPLoc) {
15911   TypeSourceInfo *TInfo;
15912   GetTypeFromParser(Ty, &TInfo);
15913   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15914 }
15915 
15916 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15917                                 Expr *E, TypeSourceInfo *TInfo,
15918                                 SourceLocation RPLoc) {
15919   Expr *OrigExpr = E;
15920   bool IsMS = false;
15921 
15922   // CUDA device code does not support varargs.
15923   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15924     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15925       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15926       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15927         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15928     }
15929   }
15930 
15931   // NVPTX does not support va_arg expression.
15932   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15933       Context.getTargetInfo().getTriple().isNVPTX())
15934     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15935 
15936   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15937   // as Microsoft ABI on an actual Microsoft platform, where
15938   // __builtin_ms_va_list and __builtin_va_list are the same.)
15939   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15940       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15941     QualType MSVaListType = Context.getBuiltinMSVaListType();
15942     if (Context.hasSameType(MSVaListType, E->getType())) {
15943       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15944         return ExprError();
15945       IsMS = true;
15946     }
15947   }
15948 
15949   // Get the va_list type
15950   QualType VaListType = Context.getBuiltinVaListType();
15951   if (!IsMS) {
15952     if (VaListType->isArrayType()) {
15953       // Deal with implicit array decay; for example, on x86-64,
15954       // va_list is an array, but it's supposed to decay to
15955       // a pointer for va_arg.
15956       VaListType = Context.getArrayDecayedType(VaListType);
15957       // Make sure the input expression also decays appropriately.
15958       ExprResult Result = UsualUnaryConversions(E);
15959       if (Result.isInvalid())
15960         return ExprError();
15961       E = Result.get();
15962     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15963       // If va_list is a record type and we are compiling in C++ mode,
15964       // check the argument using reference binding.
15965       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15966           Context, Context.getLValueReferenceType(VaListType), false);
15967       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15968       if (Init.isInvalid())
15969         return ExprError();
15970       E = Init.getAs<Expr>();
15971     } else {
15972       // Otherwise, the va_list argument must be an l-value because
15973       // it is modified by va_arg.
15974       if (!E->isTypeDependent() &&
15975           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15976         return ExprError();
15977     }
15978   }
15979 
15980   if (!IsMS && !E->isTypeDependent() &&
15981       !Context.hasSameType(VaListType, E->getType()))
15982     return ExprError(
15983         Diag(E->getBeginLoc(),
15984              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15985         << OrigExpr->getType() << E->getSourceRange());
15986 
15987   if (!TInfo->getType()->isDependentType()) {
15988     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15989                             diag::err_second_parameter_to_va_arg_incomplete,
15990                             TInfo->getTypeLoc()))
15991       return ExprError();
15992 
15993     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15994                                TInfo->getType(),
15995                                diag::err_second_parameter_to_va_arg_abstract,
15996                                TInfo->getTypeLoc()))
15997       return ExprError();
15998 
15999     if (!TInfo->getType().isPODType(Context)) {
16000       Diag(TInfo->getTypeLoc().getBeginLoc(),
16001            TInfo->getType()->isObjCLifetimeType()
16002              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16003              : diag::warn_second_parameter_to_va_arg_not_pod)
16004         << TInfo->getType()
16005         << TInfo->getTypeLoc().getSourceRange();
16006     }
16007 
16008     // Check for va_arg where arguments of the given type will be promoted
16009     // (i.e. this va_arg is guaranteed to have undefined behavior).
16010     QualType PromoteType;
16011     if (TInfo->getType()->isPromotableIntegerType()) {
16012       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16013       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16014       // and C2x 7.16.1.1p2 says, in part:
16015       //   If type is not compatible with the type of the actual next argument
16016       //   (as promoted according to the default argument promotions), the
16017       //   behavior is undefined, except for the following cases:
16018       //     - both types are pointers to qualified or unqualified versions of
16019       //       compatible types;
16020       //     - one type is a signed integer type, the other type is the
16021       //       corresponding unsigned integer type, and the value is
16022       //       representable in both types;
16023       //     - one type is pointer to qualified or unqualified void and the
16024       //       other is a pointer to a qualified or unqualified character type.
16025       // Given that type compatibility is the primary requirement (ignoring
16026       // qualifications), you would think we could call typesAreCompatible()
16027       // directly to test this. However, in C++, that checks for *same type*,
16028       // which causes false positives when passing an enumeration type to
16029       // va_arg. Instead, get the underlying type of the enumeration and pass
16030       // that.
16031       QualType UnderlyingType = TInfo->getType();
16032       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16033         UnderlyingType = ET->getDecl()->getIntegerType();
16034       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16035                                      /*CompareUnqualified*/ true))
16036         PromoteType = QualType();
16037 
16038       // If the types are still not compatible, we need to test whether the
16039       // promoted type and the underlying type are the same except for
16040       // signedness. Ask the AST for the correctly corresponding type and see
16041       // if that's compatible.
16042       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16043           PromoteType->isUnsignedIntegerType() !=
16044               UnderlyingType->isUnsignedIntegerType()) {
16045         UnderlyingType =
16046             UnderlyingType->isUnsignedIntegerType()
16047                 ? Context.getCorrespondingSignedType(UnderlyingType)
16048                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16049         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16050                                        /*CompareUnqualified*/ true))
16051           PromoteType = QualType();
16052       }
16053     }
16054     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16055       PromoteType = Context.DoubleTy;
16056     if (!PromoteType.isNull())
16057       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16058                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16059                           << TInfo->getType()
16060                           << PromoteType
16061                           << TInfo->getTypeLoc().getSourceRange());
16062   }
16063 
16064   QualType T = TInfo->getType().getNonLValueExprType(Context);
16065   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16066 }
16067 
16068 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16069   // The type of __null will be int or long, depending on the size of
16070   // pointers on the target.
16071   QualType Ty;
16072   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16073   if (pw == Context.getTargetInfo().getIntWidth())
16074     Ty = Context.IntTy;
16075   else if (pw == Context.getTargetInfo().getLongWidth())
16076     Ty = Context.LongTy;
16077   else if (pw == Context.getTargetInfo().getLongLongWidth())
16078     Ty = Context.LongLongTy;
16079   else {
16080     llvm_unreachable("I don't know size of pointer!");
16081   }
16082 
16083   return new (Context) GNUNullExpr(Ty, TokenLoc);
16084 }
16085 
16086 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16087                                     SourceLocation BuiltinLoc,
16088                                     SourceLocation RPLoc) {
16089   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
16090 }
16091 
16092 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16093                                     SourceLocation BuiltinLoc,
16094                                     SourceLocation RPLoc,
16095                                     DeclContext *ParentContext) {
16096   return new (Context)
16097       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
16098 }
16099 
16100 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16101                                         bool Diagnose) {
16102   if (!getLangOpts().ObjC)
16103     return false;
16104 
16105   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16106   if (!PT)
16107     return false;
16108   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16109 
16110   // Ignore any parens, implicit casts (should only be
16111   // array-to-pointer decays), and not-so-opaque values.  The last is
16112   // important for making this trigger for property assignments.
16113   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16114   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16115     if (OV->getSourceExpr())
16116       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16117 
16118   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16119     if (!PT->isObjCIdType() &&
16120         !(ID && ID->getIdentifier()->isStr("NSString")))
16121       return false;
16122     if (!SL->isAscii())
16123       return false;
16124 
16125     if (Diagnose) {
16126       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16127           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16128       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16129     }
16130     return true;
16131   }
16132 
16133   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16134       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16135       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16136       !SrcExpr->isNullPointerConstant(
16137           getASTContext(), Expr::NPC_NeverValueDependent)) {
16138     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16139       return false;
16140     if (Diagnose) {
16141       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16142           << /*number*/1
16143           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16144       Expr *NumLit =
16145           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16146       if (NumLit)
16147         Exp = NumLit;
16148     }
16149     return true;
16150   }
16151 
16152   return false;
16153 }
16154 
16155 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16156                                               const Expr *SrcExpr) {
16157   if (!DstType->isFunctionPointerType() ||
16158       !SrcExpr->getType()->isFunctionType())
16159     return false;
16160 
16161   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16162   if (!DRE)
16163     return false;
16164 
16165   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16166   if (!FD)
16167     return false;
16168 
16169   return !S.checkAddressOfFunctionIsAvailable(FD,
16170                                               /*Complain=*/true,
16171                                               SrcExpr->getBeginLoc());
16172 }
16173 
16174 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16175                                     SourceLocation Loc,
16176                                     QualType DstType, QualType SrcType,
16177                                     Expr *SrcExpr, AssignmentAction Action,
16178                                     bool *Complained) {
16179   if (Complained)
16180     *Complained = false;
16181 
16182   // Decode the result (notice that AST's are still created for extensions).
16183   bool CheckInferredResultType = false;
16184   bool isInvalid = false;
16185   unsigned DiagKind = 0;
16186   ConversionFixItGenerator ConvHints;
16187   bool MayHaveConvFixit = false;
16188   bool MayHaveFunctionDiff = false;
16189   const ObjCInterfaceDecl *IFace = nullptr;
16190   const ObjCProtocolDecl *PDecl = nullptr;
16191 
16192   switch (ConvTy) {
16193   case Compatible:
16194       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16195       return false;
16196 
16197   case PointerToInt:
16198     if (getLangOpts().CPlusPlus) {
16199       DiagKind = diag::err_typecheck_convert_pointer_int;
16200       isInvalid = true;
16201     } else {
16202       DiagKind = diag::ext_typecheck_convert_pointer_int;
16203     }
16204     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16205     MayHaveConvFixit = true;
16206     break;
16207   case IntToPointer:
16208     if (getLangOpts().CPlusPlus) {
16209       DiagKind = diag::err_typecheck_convert_int_pointer;
16210       isInvalid = true;
16211     } else {
16212       DiagKind = diag::ext_typecheck_convert_int_pointer;
16213     }
16214     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16215     MayHaveConvFixit = true;
16216     break;
16217   case IncompatibleFunctionPointer:
16218     if (getLangOpts().CPlusPlus) {
16219       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16220       isInvalid = true;
16221     } else {
16222       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16223     }
16224     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16225     MayHaveConvFixit = true;
16226     break;
16227   case IncompatiblePointer:
16228     if (Action == AA_Passing_CFAudited) {
16229       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16230     } else if (getLangOpts().CPlusPlus) {
16231       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16232       isInvalid = true;
16233     } else {
16234       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16235     }
16236     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16237       SrcType->isObjCObjectPointerType();
16238     if (!CheckInferredResultType) {
16239       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16240     } else if (CheckInferredResultType) {
16241       SrcType = SrcType.getUnqualifiedType();
16242       DstType = DstType.getUnqualifiedType();
16243     }
16244     MayHaveConvFixit = true;
16245     break;
16246   case IncompatiblePointerSign:
16247     if (getLangOpts().CPlusPlus) {
16248       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16249       isInvalid = true;
16250     } else {
16251       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16252     }
16253     break;
16254   case FunctionVoidPointer:
16255     if (getLangOpts().CPlusPlus) {
16256       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16257       isInvalid = true;
16258     } else {
16259       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16260     }
16261     break;
16262   case IncompatiblePointerDiscardsQualifiers: {
16263     // Perform array-to-pointer decay if necessary.
16264     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16265 
16266     isInvalid = true;
16267 
16268     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16269     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16270     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16271       DiagKind = diag::err_typecheck_incompatible_address_space;
16272       break;
16273 
16274     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16275       DiagKind = diag::err_typecheck_incompatible_ownership;
16276       break;
16277     }
16278 
16279     llvm_unreachable("unknown error case for discarding qualifiers!");
16280     // fallthrough
16281   }
16282   case CompatiblePointerDiscardsQualifiers:
16283     // If the qualifiers lost were because we were applying the
16284     // (deprecated) C++ conversion from a string literal to a char*
16285     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16286     // Ideally, this check would be performed in
16287     // checkPointerTypesForAssignment. However, that would require a
16288     // bit of refactoring (so that the second argument is an
16289     // expression, rather than a type), which should be done as part
16290     // of a larger effort to fix checkPointerTypesForAssignment for
16291     // C++ semantics.
16292     if (getLangOpts().CPlusPlus &&
16293         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16294       return false;
16295     if (getLangOpts().CPlusPlus) {
16296       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16297       isInvalid = true;
16298     } else {
16299       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16300     }
16301 
16302     break;
16303   case IncompatibleNestedPointerQualifiers:
16304     if (getLangOpts().CPlusPlus) {
16305       isInvalid = true;
16306       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16307     } else {
16308       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16309     }
16310     break;
16311   case IncompatibleNestedPointerAddressSpaceMismatch:
16312     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16313     isInvalid = true;
16314     break;
16315   case IntToBlockPointer:
16316     DiagKind = diag::err_int_to_block_pointer;
16317     isInvalid = true;
16318     break;
16319   case IncompatibleBlockPointer:
16320     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16321     isInvalid = true;
16322     break;
16323   case IncompatibleObjCQualifiedId: {
16324     if (SrcType->isObjCQualifiedIdType()) {
16325       const ObjCObjectPointerType *srcOPT =
16326                 SrcType->castAs<ObjCObjectPointerType>();
16327       for (auto *srcProto : srcOPT->quals()) {
16328         PDecl = srcProto;
16329         break;
16330       }
16331       if (const ObjCInterfaceType *IFaceT =
16332             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16333         IFace = IFaceT->getDecl();
16334     }
16335     else if (DstType->isObjCQualifiedIdType()) {
16336       const ObjCObjectPointerType *dstOPT =
16337         DstType->castAs<ObjCObjectPointerType>();
16338       for (auto *dstProto : dstOPT->quals()) {
16339         PDecl = dstProto;
16340         break;
16341       }
16342       if (const ObjCInterfaceType *IFaceT =
16343             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16344         IFace = IFaceT->getDecl();
16345     }
16346     if (getLangOpts().CPlusPlus) {
16347       DiagKind = diag::err_incompatible_qualified_id;
16348       isInvalid = true;
16349     } else {
16350       DiagKind = diag::warn_incompatible_qualified_id;
16351     }
16352     break;
16353   }
16354   case IncompatibleVectors:
16355     if (getLangOpts().CPlusPlus) {
16356       DiagKind = diag::err_incompatible_vectors;
16357       isInvalid = true;
16358     } else {
16359       DiagKind = diag::warn_incompatible_vectors;
16360     }
16361     break;
16362   case IncompatibleObjCWeakRef:
16363     DiagKind = diag::err_arc_weak_unavailable_assign;
16364     isInvalid = true;
16365     break;
16366   case Incompatible:
16367     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16368       if (Complained)
16369         *Complained = true;
16370       return true;
16371     }
16372 
16373     DiagKind = diag::err_typecheck_convert_incompatible;
16374     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16375     MayHaveConvFixit = true;
16376     isInvalid = true;
16377     MayHaveFunctionDiff = true;
16378     break;
16379   }
16380 
16381   QualType FirstType, SecondType;
16382   switch (Action) {
16383   case AA_Assigning:
16384   case AA_Initializing:
16385     // The destination type comes first.
16386     FirstType = DstType;
16387     SecondType = SrcType;
16388     break;
16389 
16390   case AA_Returning:
16391   case AA_Passing:
16392   case AA_Passing_CFAudited:
16393   case AA_Converting:
16394   case AA_Sending:
16395   case AA_Casting:
16396     // The source type comes first.
16397     FirstType = SrcType;
16398     SecondType = DstType;
16399     break;
16400   }
16401 
16402   PartialDiagnostic FDiag = PDiag(DiagKind);
16403   if (Action == AA_Passing_CFAudited)
16404     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16405   else
16406     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16407 
16408   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16409       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16410     auto isPlainChar = [](const clang::Type *Type) {
16411       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16412              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16413     };
16414     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16415               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16416   }
16417 
16418   // If we can fix the conversion, suggest the FixIts.
16419   if (!ConvHints.isNull()) {
16420     for (FixItHint &H : ConvHints.Hints)
16421       FDiag << H;
16422   }
16423 
16424   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16425 
16426   if (MayHaveFunctionDiff)
16427     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16428 
16429   Diag(Loc, FDiag);
16430   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16431        DiagKind == diag::err_incompatible_qualified_id) &&
16432       PDecl && IFace && !IFace->hasDefinition())
16433     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16434         << IFace << PDecl;
16435 
16436   if (SecondType == Context.OverloadTy)
16437     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16438                               FirstType, /*TakingAddress=*/true);
16439 
16440   if (CheckInferredResultType)
16441     EmitRelatedResultTypeNote(SrcExpr);
16442 
16443   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16444     EmitRelatedResultTypeNoteForReturn(DstType);
16445 
16446   if (Complained)
16447     *Complained = true;
16448   return isInvalid;
16449 }
16450 
16451 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16452                                                  llvm::APSInt *Result,
16453                                                  AllowFoldKind CanFold) {
16454   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16455   public:
16456     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16457                                              QualType T) override {
16458       return S.Diag(Loc, diag::err_ice_not_integral)
16459              << T << S.LangOpts.CPlusPlus;
16460     }
16461     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16462       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16463     }
16464   } Diagnoser;
16465 
16466   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16467 }
16468 
16469 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16470                                                  llvm::APSInt *Result,
16471                                                  unsigned DiagID,
16472                                                  AllowFoldKind CanFold) {
16473   class IDDiagnoser : public VerifyICEDiagnoser {
16474     unsigned DiagID;
16475 
16476   public:
16477     IDDiagnoser(unsigned DiagID)
16478       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16479 
16480     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16481       return S.Diag(Loc, DiagID);
16482     }
16483   } Diagnoser(DiagID);
16484 
16485   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16486 }
16487 
16488 Sema::SemaDiagnosticBuilder
16489 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16490                                              QualType T) {
16491   return diagnoseNotICE(S, Loc);
16492 }
16493 
16494 Sema::SemaDiagnosticBuilder
16495 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16496   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16497 }
16498 
16499 ExprResult
16500 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16501                                       VerifyICEDiagnoser &Diagnoser,
16502                                       AllowFoldKind CanFold) {
16503   SourceLocation DiagLoc = E->getBeginLoc();
16504 
16505   if (getLangOpts().CPlusPlus11) {
16506     // C++11 [expr.const]p5:
16507     //   If an expression of literal class type is used in a context where an
16508     //   integral constant expression is required, then that class type shall
16509     //   have a single non-explicit conversion function to an integral or
16510     //   unscoped enumeration type
16511     ExprResult Converted;
16512     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16513       VerifyICEDiagnoser &BaseDiagnoser;
16514     public:
16515       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16516           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16517                                 BaseDiagnoser.Suppress, true),
16518             BaseDiagnoser(BaseDiagnoser) {}
16519 
16520       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16521                                            QualType T) override {
16522         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16523       }
16524 
16525       SemaDiagnosticBuilder diagnoseIncomplete(
16526           Sema &S, SourceLocation Loc, QualType T) override {
16527         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16528       }
16529 
16530       SemaDiagnosticBuilder diagnoseExplicitConv(
16531           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16532         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16533       }
16534 
16535       SemaDiagnosticBuilder noteExplicitConv(
16536           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16537         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16538                  << ConvTy->isEnumeralType() << ConvTy;
16539       }
16540 
16541       SemaDiagnosticBuilder diagnoseAmbiguous(
16542           Sema &S, SourceLocation Loc, QualType T) override {
16543         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16544       }
16545 
16546       SemaDiagnosticBuilder noteAmbiguous(
16547           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16548         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16549                  << ConvTy->isEnumeralType() << ConvTy;
16550       }
16551 
16552       SemaDiagnosticBuilder diagnoseConversion(
16553           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16554         llvm_unreachable("conversion functions are permitted");
16555       }
16556     } ConvertDiagnoser(Diagnoser);
16557 
16558     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16559                                                     ConvertDiagnoser);
16560     if (Converted.isInvalid())
16561       return Converted;
16562     E = Converted.get();
16563     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16564       return ExprError();
16565   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16566     // An ICE must be of integral or unscoped enumeration type.
16567     if (!Diagnoser.Suppress)
16568       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16569           << E->getSourceRange();
16570     return ExprError();
16571   }
16572 
16573   ExprResult RValueExpr = DefaultLvalueConversion(E);
16574   if (RValueExpr.isInvalid())
16575     return ExprError();
16576 
16577   E = RValueExpr.get();
16578 
16579   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16580   // in the non-ICE case.
16581   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16582     if (Result)
16583       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16584     if (!isa<ConstantExpr>(E))
16585       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16586                  : ConstantExpr::Create(Context, E);
16587     return E;
16588   }
16589 
16590   Expr::EvalResult EvalResult;
16591   SmallVector<PartialDiagnosticAt, 8> Notes;
16592   EvalResult.Diag = &Notes;
16593 
16594   // Try to evaluate the expression, and produce diagnostics explaining why it's
16595   // not a constant expression as a side-effect.
16596   bool Folded =
16597       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16598       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16599 
16600   if (!isa<ConstantExpr>(E))
16601     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16602 
16603   // In C++11, we can rely on diagnostics being produced for any expression
16604   // which is not a constant expression. If no diagnostics were produced, then
16605   // this is a constant expression.
16606   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16607     if (Result)
16608       *Result = EvalResult.Val.getInt();
16609     return E;
16610   }
16611 
16612   // If our only note is the usual "invalid subexpression" note, just point
16613   // the caret at its location rather than producing an essentially
16614   // redundant note.
16615   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16616         diag::note_invalid_subexpr_in_const_expr) {
16617     DiagLoc = Notes[0].first;
16618     Notes.clear();
16619   }
16620 
16621   if (!Folded || !CanFold) {
16622     if (!Diagnoser.Suppress) {
16623       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16624       for (const PartialDiagnosticAt &Note : Notes)
16625         Diag(Note.first, Note.second);
16626     }
16627 
16628     return ExprError();
16629   }
16630 
16631   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16632   for (const PartialDiagnosticAt &Note : Notes)
16633     Diag(Note.first, Note.second);
16634 
16635   if (Result)
16636     *Result = EvalResult.Val.getInt();
16637   return E;
16638 }
16639 
16640 namespace {
16641   // Handle the case where we conclude a expression which we speculatively
16642   // considered to be unevaluated is actually evaluated.
16643   class TransformToPE : public TreeTransform<TransformToPE> {
16644     typedef TreeTransform<TransformToPE> BaseTransform;
16645 
16646   public:
16647     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16648 
16649     // Make sure we redo semantic analysis
16650     bool AlwaysRebuild() { return true; }
16651     bool ReplacingOriginal() { return true; }
16652 
16653     // We need to special-case DeclRefExprs referring to FieldDecls which
16654     // are not part of a member pointer formation; normal TreeTransforming
16655     // doesn't catch this case because of the way we represent them in the AST.
16656     // FIXME: This is a bit ugly; is it really the best way to handle this
16657     // case?
16658     //
16659     // Error on DeclRefExprs referring to FieldDecls.
16660     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16661       if (isa<FieldDecl>(E->getDecl()) &&
16662           !SemaRef.isUnevaluatedContext())
16663         return SemaRef.Diag(E->getLocation(),
16664                             diag::err_invalid_non_static_member_use)
16665             << E->getDecl() << E->getSourceRange();
16666 
16667       return BaseTransform::TransformDeclRefExpr(E);
16668     }
16669 
16670     // Exception: filter out member pointer formation
16671     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16672       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16673         return E;
16674 
16675       return BaseTransform::TransformUnaryOperator(E);
16676     }
16677 
16678     // The body of a lambda-expression is in a separate expression evaluation
16679     // context so never needs to be transformed.
16680     // FIXME: Ideally we wouldn't transform the closure type either, and would
16681     // just recreate the capture expressions and lambda expression.
16682     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16683       return SkipLambdaBody(E, Body);
16684     }
16685   };
16686 }
16687 
16688 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16689   assert(isUnevaluatedContext() &&
16690          "Should only transform unevaluated expressions");
16691   ExprEvalContexts.back().Context =
16692       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16693   if (isUnevaluatedContext())
16694     return E;
16695   return TransformToPE(*this).TransformExpr(E);
16696 }
16697 
16698 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
16699   assert(isUnevaluatedContext() &&
16700          "Should only transform unevaluated expressions");
16701   ExprEvalContexts.back().Context =
16702       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
16703   if (isUnevaluatedContext())
16704     return TInfo;
16705   return TransformToPE(*this).TransformType(TInfo);
16706 }
16707 
16708 void
16709 Sema::PushExpressionEvaluationContext(
16710     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16711     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16712   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16713                                 LambdaContextDecl, ExprContext);
16714 
16715   // Discarded statements and immediate contexts nested in other
16716   // discarded statements or immediate context are themselves
16717   // a discarded statement or an immediate context, respectively.
16718   ExprEvalContexts.back().InDiscardedStatement =
16719       ExprEvalContexts[ExprEvalContexts.size() - 2]
16720           .isDiscardedStatementContext();
16721   ExprEvalContexts.back().InImmediateFunctionContext =
16722       ExprEvalContexts[ExprEvalContexts.size() - 2]
16723           .isImmediateFunctionContext();
16724 
16725   Cleanup.reset();
16726   if (!MaybeODRUseExprs.empty())
16727     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16728 }
16729 
16730 void
16731 Sema::PushExpressionEvaluationContext(
16732     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16733     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16734   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16735   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16736 }
16737 
16738 namespace {
16739 
16740 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16741   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16742   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16743     if (E->getOpcode() == UO_Deref)
16744       return CheckPossibleDeref(S, E->getSubExpr());
16745   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16746     return CheckPossibleDeref(S, E->getBase());
16747   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16748     return CheckPossibleDeref(S, E->getBase());
16749   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16750     QualType Inner;
16751     QualType Ty = E->getType();
16752     if (const auto *Ptr = Ty->getAs<PointerType>())
16753       Inner = Ptr->getPointeeType();
16754     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16755       Inner = Arr->getElementType();
16756     else
16757       return nullptr;
16758 
16759     if (Inner->hasAttr(attr::NoDeref))
16760       return E;
16761   }
16762   return nullptr;
16763 }
16764 
16765 } // namespace
16766 
16767 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16768   for (const Expr *E : Rec.PossibleDerefs) {
16769     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16770     if (DeclRef) {
16771       const ValueDecl *Decl = DeclRef->getDecl();
16772       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16773           << Decl->getName() << E->getSourceRange();
16774       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16775     } else {
16776       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16777           << E->getSourceRange();
16778     }
16779   }
16780   Rec.PossibleDerefs.clear();
16781 }
16782 
16783 /// Check whether E, which is either a discarded-value expression or an
16784 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16785 /// and if so, remove it from the list of volatile-qualified assignments that
16786 /// we are going to warn are deprecated.
16787 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16788   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16789     return;
16790 
16791   // Note: ignoring parens here is not justified by the standard rules, but
16792   // ignoring parentheses seems like a more reasonable approach, and this only
16793   // drives a deprecation warning so doesn't affect conformance.
16794   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16795     if (BO->getOpcode() == BO_Assign) {
16796       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16797       llvm::erase_value(LHSs, BO->getLHS());
16798     }
16799   }
16800 }
16801 
16802 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16803   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16804       !Decl->isConsteval() || isConstantEvaluated() ||
16805       RebuildingImmediateInvocation || isImmediateFunctionContext())
16806     return E;
16807 
16808   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16809   /// It's OK if this fails; we'll also remove this in
16810   /// HandleImmediateInvocations, but catching it here allows us to avoid
16811   /// walking the AST looking for it in simple cases.
16812   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16813     if (auto *DeclRef =
16814             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16815       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16816 
16817   E = MaybeCreateExprWithCleanups(E);
16818 
16819   ConstantExpr *Res = ConstantExpr::Create(
16820       getASTContext(), E.get(),
16821       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16822                                    getASTContext()),
16823       /*IsImmediateInvocation*/ true);
16824   /// Value-dependent constant expressions should not be immediately
16825   /// evaluated until they are instantiated.
16826   if (!Res->isValueDependent())
16827     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16828   return Res;
16829 }
16830 
16831 static void EvaluateAndDiagnoseImmediateInvocation(
16832     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16833   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16834   Expr::EvalResult Eval;
16835   Eval.Diag = &Notes;
16836   ConstantExpr *CE = Candidate.getPointer();
16837   bool Result = CE->EvaluateAsConstantExpr(
16838       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16839   if (!Result || !Notes.empty()) {
16840     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16841     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16842       InnerExpr = FunctionalCast->getSubExpr();
16843     FunctionDecl *FD = nullptr;
16844     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16845       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16846     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16847       FD = Call->getConstructor();
16848     else
16849       llvm_unreachable("unhandled decl kind");
16850     assert(FD->isConsteval());
16851     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16852     for (auto &Note : Notes)
16853       SemaRef.Diag(Note.first, Note.second);
16854     return;
16855   }
16856   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16857 }
16858 
16859 static void RemoveNestedImmediateInvocation(
16860     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16861     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16862   struct ComplexRemove : TreeTransform<ComplexRemove> {
16863     using Base = TreeTransform<ComplexRemove>;
16864     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16865     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16866     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16867         CurrentII;
16868     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16869                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16870                   SmallVector<Sema::ImmediateInvocationCandidate,
16871                               4>::reverse_iterator Current)
16872         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16873     void RemoveImmediateInvocation(ConstantExpr* E) {
16874       auto It = std::find_if(CurrentII, IISet.rend(),
16875                              [E](Sema::ImmediateInvocationCandidate Elem) {
16876                                return Elem.getPointer() == E;
16877                              });
16878       assert(It != IISet.rend() &&
16879              "ConstantExpr marked IsImmediateInvocation should "
16880              "be present");
16881       It->setInt(1); // Mark as deleted
16882     }
16883     ExprResult TransformConstantExpr(ConstantExpr *E) {
16884       if (!E->isImmediateInvocation())
16885         return Base::TransformConstantExpr(E);
16886       RemoveImmediateInvocation(E);
16887       return Base::TransformExpr(E->getSubExpr());
16888     }
16889     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16890     /// we need to remove its DeclRefExpr from the DRSet.
16891     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16892       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16893       return Base::TransformCXXOperatorCallExpr(E);
16894     }
16895     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16896     /// here.
16897     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16898       if (!Init)
16899         return Init;
16900       /// ConstantExpr are the first layer of implicit node to be removed so if
16901       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16902       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16903         if (CE->isImmediateInvocation())
16904           RemoveImmediateInvocation(CE);
16905       return Base::TransformInitializer(Init, NotCopyInit);
16906     }
16907     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16908       DRSet.erase(E);
16909       return E;
16910     }
16911     bool AlwaysRebuild() { return false; }
16912     bool ReplacingOriginal() { return true; }
16913     bool AllowSkippingCXXConstructExpr() {
16914       bool Res = AllowSkippingFirstCXXConstructExpr;
16915       AllowSkippingFirstCXXConstructExpr = true;
16916       return Res;
16917     }
16918     bool AllowSkippingFirstCXXConstructExpr = true;
16919   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16920                 Rec.ImmediateInvocationCandidates, It);
16921 
16922   /// CXXConstructExpr with a single argument are getting skipped by
16923   /// TreeTransform in some situtation because they could be implicit. This
16924   /// can only occur for the top-level CXXConstructExpr because it is used
16925   /// nowhere in the expression being transformed therefore will not be rebuilt.
16926   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16927   /// skipping the first CXXConstructExpr.
16928   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16929     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16930 
16931   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16932   assert(Res.isUsable());
16933   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16934   It->getPointer()->setSubExpr(Res.get());
16935 }
16936 
16937 static void
16938 HandleImmediateInvocations(Sema &SemaRef,
16939                            Sema::ExpressionEvaluationContextRecord &Rec) {
16940   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16941        Rec.ReferenceToConsteval.size() == 0) ||
16942       SemaRef.RebuildingImmediateInvocation)
16943     return;
16944 
16945   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16946   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16947   /// need to remove ReferenceToConsteval in the immediate invocation.
16948   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16949 
16950     /// Prevent sema calls during the tree transform from adding pointers that
16951     /// are already in the sets.
16952     llvm::SaveAndRestore<bool> DisableIITracking(
16953         SemaRef.RebuildingImmediateInvocation, true);
16954 
16955     /// Prevent diagnostic during tree transfrom as they are duplicates
16956     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16957 
16958     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16959          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16960       if (!It->getInt())
16961         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16962   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16963              Rec.ReferenceToConsteval.size()) {
16964     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16965       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16966       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16967       bool VisitDeclRefExpr(DeclRefExpr *E) {
16968         DRSet.erase(E);
16969         return DRSet.size();
16970       }
16971     } Visitor(Rec.ReferenceToConsteval);
16972     Visitor.TraverseStmt(
16973         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16974   }
16975   for (auto CE : Rec.ImmediateInvocationCandidates)
16976     if (!CE.getInt())
16977       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16978   for (auto DR : Rec.ReferenceToConsteval) {
16979     auto *FD = cast<FunctionDecl>(DR->getDecl());
16980     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16981         << FD;
16982     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16983   }
16984 }
16985 
16986 void Sema::PopExpressionEvaluationContext() {
16987   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16988   unsigned NumTypos = Rec.NumTypos;
16989 
16990   if (!Rec.Lambdas.empty()) {
16991     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16992     if (!getLangOpts().CPlusPlus20 &&
16993         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16994          Rec.isUnevaluated() ||
16995          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16996       unsigned D;
16997       if (Rec.isUnevaluated()) {
16998         // C++11 [expr.prim.lambda]p2:
16999         //   A lambda-expression shall not appear in an unevaluated operand
17000         //   (Clause 5).
17001         D = diag::err_lambda_unevaluated_operand;
17002       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17003         // C++1y [expr.const]p2:
17004         //   A conditional-expression e is a core constant expression unless the
17005         //   evaluation of e, following the rules of the abstract machine, would
17006         //   evaluate [...] a lambda-expression.
17007         D = diag::err_lambda_in_constant_expression;
17008       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17009         // C++17 [expr.prim.lamda]p2:
17010         // A lambda-expression shall not appear [...] in a template-argument.
17011         D = diag::err_lambda_in_invalid_context;
17012       } else
17013         llvm_unreachable("Couldn't infer lambda error message.");
17014 
17015       for (const auto *L : Rec.Lambdas)
17016         Diag(L->getBeginLoc(), D);
17017     }
17018   }
17019 
17020   WarnOnPendingNoDerefs(Rec);
17021   HandleImmediateInvocations(*this, Rec);
17022 
17023   // Warn on any volatile-qualified simple-assignments that are not discarded-
17024   // value expressions nor unevaluated operands (those cases get removed from
17025   // this list by CheckUnusedVolatileAssignment).
17026   for (auto *BO : Rec.VolatileAssignmentLHSs)
17027     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17028         << BO->getType();
17029 
17030   // When are coming out of an unevaluated context, clear out any
17031   // temporaries that we may have created as part of the evaluation of
17032   // the expression in that context: they aren't relevant because they
17033   // will never be constructed.
17034   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17035     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17036                              ExprCleanupObjects.end());
17037     Cleanup = Rec.ParentCleanup;
17038     CleanupVarDeclMarking();
17039     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17040   // Otherwise, merge the contexts together.
17041   } else {
17042     Cleanup.mergeFrom(Rec.ParentCleanup);
17043     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17044                             Rec.SavedMaybeODRUseExprs.end());
17045   }
17046 
17047   // Pop the current expression evaluation context off the stack.
17048   ExprEvalContexts.pop_back();
17049 
17050   // The global expression evaluation context record is never popped.
17051   ExprEvalContexts.back().NumTypos += NumTypos;
17052 }
17053 
17054 void Sema::DiscardCleanupsInEvaluationContext() {
17055   ExprCleanupObjects.erase(
17056          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17057          ExprCleanupObjects.end());
17058   Cleanup.reset();
17059   MaybeODRUseExprs.clear();
17060 }
17061 
17062 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17063   ExprResult Result = CheckPlaceholderExpr(E);
17064   if (Result.isInvalid())
17065     return ExprError();
17066   E = Result.get();
17067   if (!E->getType()->isVariablyModifiedType())
17068     return E;
17069   return TransformToPotentiallyEvaluated(E);
17070 }
17071 
17072 /// Are we in a context that is potentially constant evaluated per C++20
17073 /// [expr.const]p12?
17074 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17075   /// C++2a [expr.const]p12:
17076   //   An expression or conversion is potentially constant evaluated if it is
17077   switch (SemaRef.ExprEvalContexts.back().Context) {
17078     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17079     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17080 
17081       // -- a manifestly constant-evaluated expression,
17082     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17083     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17084     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17085       // -- a potentially-evaluated expression,
17086     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17087       // -- an immediate subexpression of a braced-init-list,
17088 
17089       // -- [FIXME] an expression of the form & cast-expression that occurs
17090       //    within a templated entity
17091       // -- a subexpression of one of the above that is not a subexpression of
17092       // a nested unevaluated operand.
17093       return true;
17094 
17095     case Sema::ExpressionEvaluationContext::Unevaluated:
17096     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17097       // Expressions in this context are never evaluated.
17098       return false;
17099   }
17100   llvm_unreachable("Invalid context");
17101 }
17102 
17103 /// Return true if this function has a calling convention that requires mangling
17104 /// in the size of the parameter pack.
17105 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17106   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17107   // we don't need parameter type sizes.
17108   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17109   if (!TT.isOSWindows() || !TT.isX86())
17110     return false;
17111 
17112   // If this is C++ and this isn't an extern "C" function, parameters do not
17113   // need to be complete. In this case, C++ mangling will apply, which doesn't
17114   // use the size of the parameters.
17115   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17116     return false;
17117 
17118   // Stdcall, fastcall, and vectorcall need this special treatment.
17119   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17120   switch (CC) {
17121   case CC_X86StdCall:
17122   case CC_X86FastCall:
17123   case CC_X86VectorCall:
17124     return true;
17125   default:
17126     break;
17127   }
17128   return false;
17129 }
17130 
17131 /// Require that all of the parameter types of function be complete. Normally,
17132 /// parameter types are only required to be complete when a function is called
17133 /// or defined, but to mangle functions with certain calling conventions, the
17134 /// mangler needs to know the size of the parameter list. In this situation,
17135 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17136 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17137 /// result in a linker error. Clang doesn't implement this behavior, and instead
17138 /// attempts to error at compile time.
17139 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17140                                                   SourceLocation Loc) {
17141   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17142     FunctionDecl *FD;
17143     ParmVarDecl *Param;
17144 
17145   public:
17146     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17147         : FD(FD), Param(Param) {}
17148 
17149     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17150       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17151       StringRef CCName;
17152       switch (CC) {
17153       case CC_X86StdCall:
17154         CCName = "stdcall";
17155         break;
17156       case CC_X86FastCall:
17157         CCName = "fastcall";
17158         break;
17159       case CC_X86VectorCall:
17160         CCName = "vectorcall";
17161         break;
17162       default:
17163         llvm_unreachable("CC does not need mangling");
17164       }
17165 
17166       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17167           << Param->getDeclName() << FD->getDeclName() << CCName;
17168     }
17169   };
17170 
17171   for (ParmVarDecl *Param : FD->parameters()) {
17172     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17173     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17174   }
17175 }
17176 
17177 namespace {
17178 enum class OdrUseContext {
17179   /// Declarations in this context are not odr-used.
17180   None,
17181   /// Declarations in this context are formally odr-used, but this is a
17182   /// dependent context.
17183   Dependent,
17184   /// Declarations in this context are odr-used but not actually used (yet).
17185   FormallyOdrUsed,
17186   /// Declarations in this context are used.
17187   Used
17188 };
17189 }
17190 
17191 /// Are we within a context in which references to resolved functions or to
17192 /// variables result in odr-use?
17193 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17194   OdrUseContext Result;
17195 
17196   switch (SemaRef.ExprEvalContexts.back().Context) {
17197     case Sema::ExpressionEvaluationContext::Unevaluated:
17198     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17199     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17200       return OdrUseContext::None;
17201 
17202     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17203     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17204     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17205       Result = OdrUseContext::Used;
17206       break;
17207 
17208     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17209       Result = OdrUseContext::FormallyOdrUsed;
17210       break;
17211 
17212     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17213       // A default argument formally results in odr-use, but doesn't actually
17214       // result in a use in any real sense until it itself is used.
17215       Result = OdrUseContext::FormallyOdrUsed;
17216       break;
17217   }
17218 
17219   if (SemaRef.CurContext->isDependentContext())
17220     return OdrUseContext::Dependent;
17221 
17222   return Result;
17223 }
17224 
17225 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17226   if (!Func->isConstexpr())
17227     return false;
17228 
17229   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17230     return true;
17231   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17232   return CCD && CCD->getInheritedConstructor();
17233 }
17234 
17235 /// Mark a function referenced, and check whether it is odr-used
17236 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17237 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17238                                   bool MightBeOdrUse) {
17239   assert(Func && "No function?");
17240 
17241   Func->setReferenced();
17242 
17243   // Recursive functions aren't really used until they're used from some other
17244   // context.
17245   bool IsRecursiveCall = CurContext == Func;
17246 
17247   // C++11 [basic.def.odr]p3:
17248   //   A function whose name appears as a potentially-evaluated expression is
17249   //   odr-used if it is the unique lookup result or the selected member of a
17250   //   set of overloaded functions [...].
17251   //
17252   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17253   // can just check that here.
17254   OdrUseContext OdrUse =
17255       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17256   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17257     OdrUse = OdrUseContext::FormallyOdrUsed;
17258 
17259   // Trivial default constructors and destructors are never actually used.
17260   // FIXME: What about other special members?
17261   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17262       OdrUse == OdrUseContext::Used) {
17263     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17264       if (Constructor->isDefaultConstructor())
17265         OdrUse = OdrUseContext::FormallyOdrUsed;
17266     if (isa<CXXDestructorDecl>(Func))
17267       OdrUse = OdrUseContext::FormallyOdrUsed;
17268   }
17269 
17270   // C++20 [expr.const]p12:
17271   //   A function [...] is needed for constant evaluation if it is [...] a
17272   //   constexpr function that is named by an expression that is potentially
17273   //   constant evaluated
17274   bool NeededForConstantEvaluation =
17275       isPotentiallyConstantEvaluatedContext(*this) &&
17276       isImplicitlyDefinableConstexprFunction(Func);
17277 
17278   // Determine whether we require a function definition to exist, per
17279   // C++11 [temp.inst]p3:
17280   //   Unless a function template specialization has been explicitly
17281   //   instantiated or explicitly specialized, the function template
17282   //   specialization is implicitly instantiated when the specialization is
17283   //   referenced in a context that requires a function definition to exist.
17284   // C++20 [temp.inst]p7:
17285   //   The existence of a definition of a [...] function is considered to
17286   //   affect the semantics of the program if the [...] function is needed for
17287   //   constant evaluation by an expression
17288   // C++20 [basic.def.odr]p10:
17289   //   Every program shall contain exactly one definition of every non-inline
17290   //   function or variable that is odr-used in that program outside of a
17291   //   discarded statement
17292   // C++20 [special]p1:
17293   //   The implementation will implicitly define [defaulted special members]
17294   //   if they are odr-used or needed for constant evaluation.
17295   //
17296   // Note that we skip the implicit instantiation of templates that are only
17297   // used in unused default arguments or by recursive calls to themselves.
17298   // This is formally non-conforming, but seems reasonable in practice.
17299   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17300                                              NeededForConstantEvaluation);
17301 
17302   // C++14 [temp.expl.spec]p6:
17303   //   If a template [...] is explicitly specialized then that specialization
17304   //   shall be declared before the first use of that specialization that would
17305   //   cause an implicit instantiation to take place, in every translation unit
17306   //   in which such a use occurs
17307   if (NeedDefinition &&
17308       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17309        Func->getMemberSpecializationInfo()))
17310     checkSpecializationVisibility(Loc, Func);
17311 
17312   if (getLangOpts().CUDA)
17313     CheckCUDACall(Loc, Func);
17314 
17315   if (getLangOpts().SYCLIsDevice)
17316     checkSYCLDeviceFunction(Loc, Func);
17317 
17318   // If we need a definition, try to create one.
17319   if (NeedDefinition && !Func->getBody()) {
17320     runWithSufficientStackSpace(Loc, [&] {
17321       if (CXXConstructorDecl *Constructor =
17322               dyn_cast<CXXConstructorDecl>(Func)) {
17323         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17324         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17325           if (Constructor->isDefaultConstructor()) {
17326             if (Constructor->isTrivial() &&
17327                 !Constructor->hasAttr<DLLExportAttr>())
17328               return;
17329             DefineImplicitDefaultConstructor(Loc, Constructor);
17330           } else if (Constructor->isCopyConstructor()) {
17331             DefineImplicitCopyConstructor(Loc, Constructor);
17332           } else if (Constructor->isMoveConstructor()) {
17333             DefineImplicitMoveConstructor(Loc, Constructor);
17334           }
17335         } else if (Constructor->getInheritedConstructor()) {
17336           DefineInheritingConstructor(Loc, Constructor);
17337         }
17338       } else if (CXXDestructorDecl *Destructor =
17339                      dyn_cast<CXXDestructorDecl>(Func)) {
17340         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17341         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17342           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17343             return;
17344           DefineImplicitDestructor(Loc, Destructor);
17345         }
17346         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17347           MarkVTableUsed(Loc, Destructor->getParent());
17348       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17349         if (MethodDecl->isOverloadedOperator() &&
17350             MethodDecl->getOverloadedOperator() == OO_Equal) {
17351           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17352           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17353             if (MethodDecl->isCopyAssignmentOperator())
17354               DefineImplicitCopyAssignment(Loc, MethodDecl);
17355             else if (MethodDecl->isMoveAssignmentOperator())
17356               DefineImplicitMoveAssignment(Loc, MethodDecl);
17357           }
17358         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17359                    MethodDecl->getParent()->isLambda()) {
17360           CXXConversionDecl *Conversion =
17361               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17362           if (Conversion->isLambdaToBlockPointerConversion())
17363             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17364           else
17365             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17366         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17367           MarkVTableUsed(Loc, MethodDecl->getParent());
17368       }
17369 
17370       if (Func->isDefaulted() && !Func->isDeleted()) {
17371         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17372         if (DCK != DefaultedComparisonKind::None)
17373           DefineDefaultedComparison(Loc, Func, DCK);
17374       }
17375 
17376       // Implicit instantiation of function templates and member functions of
17377       // class templates.
17378       if (Func->isImplicitlyInstantiable()) {
17379         TemplateSpecializationKind TSK =
17380             Func->getTemplateSpecializationKindForInstantiation();
17381         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17382         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17383         if (FirstInstantiation) {
17384           PointOfInstantiation = Loc;
17385           if (auto *MSI = Func->getMemberSpecializationInfo())
17386             MSI->setPointOfInstantiation(Loc);
17387             // FIXME: Notify listener.
17388           else
17389             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17390         } else if (TSK != TSK_ImplicitInstantiation) {
17391           // Use the point of use as the point of instantiation, instead of the
17392           // point of explicit instantiation (which we track as the actual point
17393           // of instantiation). This gives better backtraces in diagnostics.
17394           PointOfInstantiation = Loc;
17395         }
17396 
17397         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17398             Func->isConstexpr()) {
17399           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17400               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17401               CodeSynthesisContexts.size())
17402             PendingLocalImplicitInstantiations.push_back(
17403                 std::make_pair(Func, PointOfInstantiation));
17404           else if (Func->isConstexpr())
17405             // Do not defer instantiations of constexpr functions, to avoid the
17406             // expression evaluator needing to call back into Sema if it sees a
17407             // call to such a function.
17408             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17409           else {
17410             Func->setInstantiationIsPending(true);
17411             PendingInstantiations.push_back(
17412                 std::make_pair(Func, PointOfInstantiation));
17413             // Notify the consumer that a function was implicitly instantiated.
17414             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17415           }
17416         }
17417       } else {
17418         // Walk redefinitions, as some of them may be instantiable.
17419         for (auto i : Func->redecls()) {
17420           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17421             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17422         }
17423       }
17424     });
17425   }
17426 
17427   // C++14 [except.spec]p17:
17428   //   An exception-specification is considered to be needed when:
17429   //   - the function is odr-used or, if it appears in an unevaluated operand,
17430   //     would be odr-used if the expression were potentially-evaluated;
17431   //
17432   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17433   // function is a pure virtual function we're calling, and in that case the
17434   // function was selected by overload resolution and we need to resolve its
17435   // exception specification for a different reason.
17436   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17437   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17438     ResolveExceptionSpec(Loc, FPT);
17439 
17440   // If this is the first "real" use, act on that.
17441   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17442     // Keep track of used but undefined functions.
17443     if (!Func->isDefined()) {
17444       if (mightHaveNonExternalLinkage(Func))
17445         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17446       else if (Func->getMostRecentDecl()->isInlined() &&
17447                !LangOpts.GNUInline &&
17448                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17449         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17450       else if (isExternalWithNoLinkageType(Func))
17451         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17452     }
17453 
17454     // Some x86 Windows calling conventions mangle the size of the parameter
17455     // pack into the name. Computing the size of the parameters requires the
17456     // parameter types to be complete. Check that now.
17457     if (funcHasParameterSizeMangling(*this, Func))
17458       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17459 
17460     // In the MS C++ ABI, the compiler emits destructor variants where they are
17461     // used. If the destructor is used here but defined elsewhere, mark the
17462     // virtual base destructors referenced. If those virtual base destructors
17463     // are inline, this will ensure they are defined when emitting the complete
17464     // destructor variant. This checking may be redundant if the destructor is
17465     // provided later in this TU.
17466     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17467       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17468         CXXRecordDecl *Parent = Dtor->getParent();
17469         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17470           CheckCompleteDestructorVariant(Loc, Dtor);
17471       }
17472     }
17473 
17474     Func->markUsed(Context);
17475   }
17476 }
17477 
17478 /// Directly mark a variable odr-used. Given a choice, prefer to use
17479 /// MarkVariableReferenced since it does additional checks and then
17480 /// calls MarkVarDeclODRUsed.
17481 /// If the variable must be captured:
17482 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17483 ///  - else capture it in the DeclContext that maps to the
17484 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17485 static void
17486 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17487                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17488   // Keep track of used but undefined variables.
17489   // FIXME: We shouldn't suppress this warning for static data members.
17490   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17491       (!Var->isExternallyVisible() || Var->isInline() ||
17492        SemaRef.isExternalWithNoLinkageType(Var)) &&
17493       !(Var->isStaticDataMember() && Var->hasInit())) {
17494     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17495     if (old.isInvalid())
17496       old = Loc;
17497   }
17498   QualType CaptureType, DeclRefType;
17499   if (SemaRef.LangOpts.OpenMP)
17500     SemaRef.tryCaptureOpenMPLambdas(Var);
17501   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17502     /*EllipsisLoc*/ SourceLocation(),
17503     /*BuildAndDiagnose*/ true,
17504     CaptureType, DeclRefType,
17505     FunctionScopeIndexToStopAt);
17506 
17507   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
17508     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17509     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17510     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17511     if (VarTarget == Sema::CVT_Host &&
17512         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17513          UserTarget == Sema::CFT_Global)) {
17514       // Diagnose ODR-use of host global variables in device functions.
17515       // Reference of device global variables in host functions is allowed
17516       // through shadow variables therefore it is not diagnosed.
17517       if (SemaRef.LangOpts.CUDAIsDevice) {
17518         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17519             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17520         SemaRef.targetDiag(Var->getLocation(),
17521                            Var->getType().isConstQualified()
17522                                ? diag::note_cuda_const_var_unpromoted
17523                                : diag::note_cuda_host_var);
17524       }
17525     } else if (VarTarget == Sema::CVT_Device &&
17526                (UserTarget == Sema::CFT_Host ||
17527                 UserTarget == Sema::CFT_HostDevice) &&
17528                !Var->hasExternalStorage()) {
17529       // Record a CUDA/HIP device side variable if it is ODR-used
17530       // by host code. This is done conservatively, when the variable is
17531       // referenced in any of the following contexts:
17532       //   - a non-function context
17533       //   - a host function
17534       //   - a host device function
17535       // This makes the ODR-use of the device side variable by host code to
17536       // be visible in the device compilation for the compiler to be able to
17537       // emit template variables instantiated by host code only and to
17538       // externalize the static device side variable ODR-used by host code.
17539       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17540     }
17541   }
17542 
17543   Var->markUsed(SemaRef.Context);
17544 }
17545 
17546 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17547                                              SourceLocation Loc,
17548                                              unsigned CapturingScopeIndex) {
17549   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17550 }
17551 
17552 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17553                                                ValueDecl *var) {
17554   DeclContext *VarDC = var->getDeclContext();
17555 
17556   //  If the parameter still belongs to the translation unit, then
17557   //  we're actually just using one parameter in the declaration of
17558   //  the next.
17559   if (isa<ParmVarDecl>(var) &&
17560       isa<TranslationUnitDecl>(VarDC))
17561     return;
17562 
17563   // For C code, don't diagnose about capture if we're not actually in code
17564   // right now; it's impossible to write a non-constant expression outside of
17565   // function context, so we'll get other (more useful) diagnostics later.
17566   //
17567   // For C++, things get a bit more nasty... it would be nice to suppress this
17568   // diagnostic for certain cases like using a local variable in an array bound
17569   // for a member of a local class, but the correct predicate is not obvious.
17570   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17571     return;
17572 
17573   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17574   unsigned ContextKind = 3; // unknown
17575   if (isa<CXXMethodDecl>(VarDC) &&
17576       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17577     ContextKind = 2;
17578   } else if (isa<FunctionDecl>(VarDC)) {
17579     ContextKind = 0;
17580   } else if (isa<BlockDecl>(VarDC)) {
17581     ContextKind = 1;
17582   }
17583 
17584   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17585     << var << ValueKind << ContextKind << VarDC;
17586   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17587       << var;
17588 
17589   // FIXME: Add additional diagnostic info about class etc. which prevents
17590   // capture.
17591 }
17592 
17593 
17594 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17595                                       bool &SubCapturesAreNested,
17596                                       QualType &CaptureType,
17597                                       QualType &DeclRefType) {
17598    // Check whether we've already captured it.
17599   if (CSI->CaptureMap.count(Var)) {
17600     // If we found a capture, any subcaptures are nested.
17601     SubCapturesAreNested = true;
17602 
17603     // Retrieve the capture type for this variable.
17604     CaptureType = CSI->getCapture(Var).getCaptureType();
17605 
17606     // Compute the type of an expression that refers to this variable.
17607     DeclRefType = CaptureType.getNonReferenceType();
17608 
17609     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17610     // are mutable in the sense that user can change their value - they are
17611     // private instances of the captured declarations.
17612     const Capture &Cap = CSI->getCapture(Var);
17613     if (Cap.isCopyCapture() &&
17614         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17615         !(isa<CapturedRegionScopeInfo>(CSI) &&
17616           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17617       DeclRefType.addConst();
17618     return true;
17619   }
17620   return false;
17621 }
17622 
17623 // Only block literals, captured statements, and lambda expressions can
17624 // capture; other scopes don't work.
17625 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17626                                  SourceLocation Loc,
17627                                  const bool Diagnose, Sema &S) {
17628   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17629     return getLambdaAwareParentOfDeclContext(DC);
17630   else if (Var->hasLocalStorage()) {
17631     if (Diagnose)
17632        diagnoseUncapturableValueReference(S, Loc, Var);
17633   }
17634   return nullptr;
17635 }
17636 
17637 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17638 // certain types of variables (unnamed, variably modified types etc.)
17639 // so check for eligibility.
17640 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17641                                  SourceLocation Loc,
17642                                  const bool Diagnose, Sema &S) {
17643 
17644   bool IsBlock = isa<BlockScopeInfo>(CSI);
17645   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17646 
17647   // Lambdas are not allowed to capture unnamed variables
17648   // (e.g. anonymous unions).
17649   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17650   // assuming that's the intent.
17651   if (IsLambda && !Var->getDeclName()) {
17652     if (Diagnose) {
17653       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17654       S.Diag(Var->getLocation(), diag::note_declared_at);
17655     }
17656     return false;
17657   }
17658 
17659   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17660   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17661     if (Diagnose) {
17662       S.Diag(Loc, diag::err_ref_vm_type);
17663       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17664     }
17665     return false;
17666   }
17667   // Prohibit structs with flexible array members too.
17668   // We cannot capture what is in the tail end of the struct.
17669   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17670     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17671       if (Diagnose) {
17672         if (IsBlock)
17673           S.Diag(Loc, diag::err_ref_flexarray_type);
17674         else
17675           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17676         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17677       }
17678       return false;
17679     }
17680   }
17681   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17682   // Lambdas and captured statements are not allowed to capture __block
17683   // variables; they don't support the expected semantics.
17684   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17685     if (Diagnose) {
17686       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17687       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17688     }
17689     return false;
17690   }
17691   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17692   if (S.getLangOpts().OpenCL && IsBlock &&
17693       Var->getType()->isBlockPointerType()) {
17694     if (Diagnose)
17695       S.Diag(Loc, diag::err_opencl_block_ref_block);
17696     return false;
17697   }
17698 
17699   return true;
17700 }
17701 
17702 // Returns true if the capture by block was successful.
17703 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17704                                  SourceLocation Loc,
17705                                  const bool BuildAndDiagnose,
17706                                  QualType &CaptureType,
17707                                  QualType &DeclRefType,
17708                                  const bool Nested,
17709                                  Sema &S, bool Invalid) {
17710   bool ByRef = false;
17711 
17712   // Blocks are not allowed to capture arrays, excepting OpenCL.
17713   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17714   // (decayed to pointers).
17715   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17716     if (BuildAndDiagnose) {
17717       S.Diag(Loc, diag::err_ref_array_type);
17718       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17719       Invalid = true;
17720     } else {
17721       return false;
17722     }
17723   }
17724 
17725   // Forbid the block-capture of autoreleasing variables.
17726   if (!Invalid &&
17727       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17728     if (BuildAndDiagnose) {
17729       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17730         << /*block*/ 0;
17731       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17732       Invalid = true;
17733     } else {
17734       return false;
17735     }
17736   }
17737 
17738   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17739   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17740     QualType PointeeTy = PT->getPointeeType();
17741 
17742     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17743         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17744         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17745       if (BuildAndDiagnose) {
17746         SourceLocation VarLoc = Var->getLocation();
17747         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17748         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17749       }
17750     }
17751   }
17752 
17753   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17754   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17755       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17756     // Block capture by reference does not change the capture or
17757     // declaration reference types.
17758     ByRef = true;
17759   } else {
17760     // Block capture by copy introduces 'const'.
17761     CaptureType = CaptureType.getNonReferenceType().withConst();
17762     DeclRefType = CaptureType;
17763   }
17764 
17765   // Actually capture the variable.
17766   if (BuildAndDiagnose)
17767     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17768                     CaptureType, Invalid);
17769 
17770   return !Invalid;
17771 }
17772 
17773 
17774 /// Capture the given variable in the captured region.
17775 static bool captureInCapturedRegion(
17776     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17777     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17778     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17779     bool IsTopScope, Sema &S, bool Invalid) {
17780   // By default, capture variables by reference.
17781   bool ByRef = true;
17782   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17783     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17784   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17785     // Using an LValue reference type is consistent with Lambdas (see below).
17786     if (S.isOpenMPCapturedDecl(Var)) {
17787       bool HasConst = DeclRefType.isConstQualified();
17788       DeclRefType = DeclRefType.getUnqualifiedType();
17789       // Don't lose diagnostics about assignments to const.
17790       if (HasConst)
17791         DeclRefType.addConst();
17792     }
17793     // Do not capture firstprivates in tasks.
17794     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17795         OMPC_unknown)
17796       return true;
17797     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17798                                     RSI->OpenMPCaptureLevel);
17799   }
17800 
17801   if (ByRef)
17802     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17803   else
17804     CaptureType = DeclRefType;
17805 
17806   // Actually capture the variable.
17807   if (BuildAndDiagnose)
17808     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17809                     Loc, SourceLocation(), CaptureType, Invalid);
17810 
17811   return !Invalid;
17812 }
17813 
17814 /// Capture the given variable in the lambda.
17815 static bool captureInLambda(LambdaScopeInfo *LSI,
17816                             VarDecl *Var,
17817                             SourceLocation Loc,
17818                             const bool BuildAndDiagnose,
17819                             QualType &CaptureType,
17820                             QualType &DeclRefType,
17821                             const bool RefersToCapturedVariable,
17822                             const Sema::TryCaptureKind Kind,
17823                             SourceLocation EllipsisLoc,
17824                             const bool IsTopScope,
17825                             Sema &S, bool Invalid) {
17826   // Determine whether we are capturing by reference or by value.
17827   bool ByRef = false;
17828   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17829     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17830   } else {
17831     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17832   }
17833 
17834   // Compute the type of the field that will capture this variable.
17835   if (ByRef) {
17836     // C++11 [expr.prim.lambda]p15:
17837     //   An entity is captured by reference if it is implicitly or
17838     //   explicitly captured but not captured by copy. It is
17839     //   unspecified whether additional unnamed non-static data
17840     //   members are declared in the closure type for entities
17841     //   captured by reference.
17842     //
17843     // FIXME: It is not clear whether we want to build an lvalue reference
17844     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17845     // to do the former, while EDG does the latter. Core issue 1249 will
17846     // clarify, but for now we follow GCC because it's a more permissive and
17847     // easily defensible position.
17848     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17849   } else {
17850     // C++11 [expr.prim.lambda]p14:
17851     //   For each entity captured by copy, an unnamed non-static
17852     //   data member is declared in the closure type. The
17853     //   declaration order of these members is unspecified. The type
17854     //   of such a data member is the type of the corresponding
17855     //   captured entity if the entity is not a reference to an
17856     //   object, or the referenced type otherwise. [Note: If the
17857     //   captured entity is a reference to a function, the
17858     //   corresponding data member is also a reference to a
17859     //   function. - end note ]
17860     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17861       if (!RefType->getPointeeType()->isFunctionType())
17862         CaptureType = RefType->getPointeeType();
17863     }
17864 
17865     // Forbid the lambda copy-capture of autoreleasing variables.
17866     if (!Invalid &&
17867         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17868       if (BuildAndDiagnose) {
17869         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17870         S.Diag(Var->getLocation(), diag::note_previous_decl)
17871           << Var->getDeclName();
17872         Invalid = true;
17873       } else {
17874         return false;
17875       }
17876     }
17877 
17878     // Make sure that by-copy captures are of a complete and non-abstract type.
17879     if (!Invalid && BuildAndDiagnose) {
17880       if (!CaptureType->isDependentType() &&
17881           S.RequireCompleteSizedType(
17882               Loc, CaptureType,
17883               diag::err_capture_of_incomplete_or_sizeless_type,
17884               Var->getDeclName()))
17885         Invalid = true;
17886       else if (S.RequireNonAbstractType(Loc, CaptureType,
17887                                         diag::err_capture_of_abstract_type))
17888         Invalid = true;
17889     }
17890   }
17891 
17892   // Compute the type of a reference to this captured variable.
17893   if (ByRef)
17894     DeclRefType = CaptureType.getNonReferenceType();
17895   else {
17896     // C++ [expr.prim.lambda]p5:
17897     //   The closure type for a lambda-expression has a public inline
17898     //   function call operator [...]. This function call operator is
17899     //   declared const (9.3.1) if and only if the lambda-expression's
17900     //   parameter-declaration-clause is not followed by mutable.
17901     DeclRefType = CaptureType.getNonReferenceType();
17902     if (!LSI->Mutable && !CaptureType->isReferenceType())
17903       DeclRefType.addConst();
17904   }
17905 
17906   // Add the capture.
17907   if (BuildAndDiagnose)
17908     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17909                     Loc, EllipsisLoc, CaptureType, Invalid);
17910 
17911   return !Invalid;
17912 }
17913 
17914 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17915   // Offer a Copy fix even if the type is dependent.
17916   if (Var->getType()->isDependentType())
17917     return true;
17918   QualType T = Var->getType().getNonReferenceType();
17919   if (T.isTriviallyCopyableType(Context))
17920     return true;
17921   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17922 
17923     if (!(RD = RD->getDefinition()))
17924       return false;
17925     if (RD->hasSimpleCopyConstructor())
17926       return true;
17927     if (RD->hasUserDeclaredCopyConstructor())
17928       for (CXXConstructorDecl *Ctor : RD->ctors())
17929         if (Ctor->isCopyConstructor())
17930           return !Ctor->isDeleted();
17931   }
17932   return false;
17933 }
17934 
17935 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17936 /// default capture. Fixes may be omitted if they aren't allowed by the
17937 /// standard, for example we can't emit a default copy capture fix-it if we
17938 /// already explicitly copy capture capture another variable.
17939 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17940                                     VarDecl *Var) {
17941   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17942   // Don't offer Capture by copy of default capture by copy fixes if Var is
17943   // known not to be copy constructible.
17944   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17945 
17946   SmallString<32> FixBuffer;
17947   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17948   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17949     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17950     if (ShouldOfferCopyFix) {
17951       // Offer fixes to insert an explicit capture for the variable.
17952       // [] -> [VarName]
17953       // [OtherCapture] -> [OtherCapture, VarName]
17954       FixBuffer.assign({Separator, Var->getName()});
17955       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17956           << Var << /*value*/ 0
17957           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17958     }
17959     // As above but capture by reference.
17960     FixBuffer.assign({Separator, "&", Var->getName()});
17961     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17962         << Var << /*reference*/ 1
17963         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17964   }
17965 
17966   // Only try to offer default capture if there are no captures excluding this
17967   // and init captures.
17968   // [this]: OK.
17969   // [X = Y]: OK.
17970   // [&A, &B]: Don't offer.
17971   // [A, B]: Don't offer.
17972   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17973         return !C.isThisCapture() && !C.isInitCapture();
17974       }))
17975     return;
17976 
17977   // The default capture specifiers, '=' or '&', must appear first in the
17978   // capture body.
17979   SourceLocation DefaultInsertLoc =
17980       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17981 
17982   if (ShouldOfferCopyFix) {
17983     bool CanDefaultCopyCapture = true;
17984     // [=, *this] OK since c++17
17985     // [=, this] OK since c++20
17986     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17987       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17988                                   ? LSI->getCXXThisCapture().isCopyCapture()
17989                                   : false;
17990     // We can't use default capture by copy if any captures already specified
17991     // capture by copy.
17992     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17993           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17994         })) {
17995       FixBuffer.assign({"=", Separator});
17996       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17997           << /*value*/ 0
17998           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17999     }
18000   }
18001 
18002   // We can't use default capture by reference if any captures already specified
18003   // capture by reference.
18004   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18005         return !C.isInitCapture() && C.isReferenceCapture() &&
18006                !C.isThisCapture();
18007       })) {
18008     FixBuffer.assign({"&", Separator});
18009     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18010         << /*reference*/ 1
18011         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18012   }
18013 }
18014 
18015 bool Sema::tryCaptureVariable(
18016     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18017     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18018     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18019   // An init-capture is notionally from the context surrounding its
18020   // declaration, but its parent DC is the lambda class.
18021   DeclContext *VarDC = Var->getDeclContext();
18022   if (Var->isInitCapture())
18023     VarDC = VarDC->getParent();
18024 
18025   DeclContext *DC = CurContext;
18026   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18027       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18028   // We need to sync up the Declaration Context with the
18029   // FunctionScopeIndexToStopAt
18030   if (FunctionScopeIndexToStopAt) {
18031     unsigned FSIndex = FunctionScopes.size() - 1;
18032     while (FSIndex != MaxFunctionScopesIndex) {
18033       DC = getLambdaAwareParentOfDeclContext(DC);
18034       --FSIndex;
18035     }
18036   }
18037 
18038 
18039   // If the variable is declared in the current context, there is no need to
18040   // capture it.
18041   if (VarDC == DC) return true;
18042 
18043   // Capture global variables if it is required to use private copy of this
18044   // variable.
18045   bool IsGlobal = !Var->hasLocalStorage();
18046   if (IsGlobal &&
18047       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18048                                                 MaxFunctionScopesIndex)))
18049     return true;
18050   Var = Var->getCanonicalDecl();
18051 
18052   // Walk up the stack to determine whether we can capture the variable,
18053   // performing the "simple" checks that don't depend on type. We stop when
18054   // we've either hit the declared scope of the variable or find an existing
18055   // capture of that variable.  We start from the innermost capturing-entity
18056   // (the DC) and ensure that all intervening capturing-entities
18057   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18058   // declcontext can either capture the variable or have already captured
18059   // the variable.
18060   CaptureType = Var->getType();
18061   DeclRefType = CaptureType.getNonReferenceType();
18062   bool Nested = false;
18063   bool Explicit = (Kind != TryCapture_Implicit);
18064   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18065   do {
18066     // Only block literals, captured statements, and lambda expressions can
18067     // capture; other scopes don't work.
18068     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18069                                                               ExprLoc,
18070                                                               BuildAndDiagnose,
18071                                                               *this);
18072     // We need to check for the parent *first* because, if we *have*
18073     // private-captured a global variable, we need to recursively capture it in
18074     // intermediate blocks, lambdas, etc.
18075     if (!ParentDC) {
18076       if (IsGlobal) {
18077         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18078         break;
18079       }
18080       return true;
18081     }
18082 
18083     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18084     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18085 
18086 
18087     // Check whether we've already captured it.
18088     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18089                                              DeclRefType)) {
18090       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18091       break;
18092     }
18093     // If we are instantiating a generic lambda call operator body,
18094     // we do not want to capture new variables.  What was captured
18095     // during either a lambdas transformation or initial parsing
18096     // should be used.
18097     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18098       if (BuildAndDiagnose) {
18099         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18100         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18101           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18102           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18103           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18104           buildLambdaCaptureFixit(*this, LSI, Var);
18105         } else
18106           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18107       }
18108       return true;
18109     }
18110 
18111     // Try to capture variable-length arrays types.
18112     if (Var->getType()->isVariablyModifiedType()) {
18113       // We're going to walk down into the type and look for VLA
18114       // expressions.
18115       QualType QTy = Var->getType();
18116       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18117         QTy = PVD->getOriginalType();
18118       captureVariablyModifiedType(Context, QTy, CSI);
18119     }
18120 
18121     if (getLangOpts().OpenMP) {
18122       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18123         // OpenMP private variables should not be captured in outer scope, so
18124         // just break here. Similarly, global variables that are captured in a
18125         // target region should not be captured outside the scope of the region.
18126         if (RSI->CapRegionKind == CR_OpenMP) {
18127           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18128               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18129           // If the variable is private (i.e. not captured) and has variably
18130           // modified type, we still need to capture the type for correct
18131           // codegen in all regions, associated with the construct. Currently,
18132           // it is captured in the innermost captured region only.
18133           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18134               Var->getType()->isVariablyModifiedType()) {
18135             QualType QTy = Var->getType();
18136             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18137               QTy = PVD->getOriginalType();
18138             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18139                  I < E; ++I) {
18140               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18141                   FunctionScopes[FunctionScopesIndex - I]);
18142               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18143                      "Wrong number of captured regions associated with the "
18144                      "OpenMP construct.");
18145               captureVariablyModifiedType(Context, QTy, OuterRSI);
18146             }
18147           }
18148           bool IsTargetCap =
18149               IsOpenMPPrivateDecl != OMPC_private &&
18150               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18151                                          RSI->OpenMPCaptureLevel);
18152           // Do not capture global if it is not privatized in outer regions.
18153           bool IsGlobalCap =
18154               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18155                                                      RSI->OpenMPCaptureLevel);
18156 
18157           // When we detect target captures we are looking from inside the
18158           // target region, therefore we need to propagate the capture from the
18159           // enclosing region. Therefore, the capture is not initially nested.
18160           if (IsTargetCap)
18161             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18162 
18163           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18164               (IsGlobal && !IsGlobalCap)) {
18165             Nested = !IsTargetCap;
18166             bool HasConst = DeclRefType.isConstQualified();
18167             DeclRefType = DeclRefType.getUnqualifiedType();
18168             // Don't lose diagnostics about assignments to const.
18169             if (HasConst)
18170               DeclRefType.addConst();
18171             CaptureType = Context.getLValueReferenceType(DeclRefType);
18172             break;
18173           }
18174         }
18175       }
18176     }
18177     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18178       // No capture-default, and this is not an explicit capture
18179       // so cannot capture this variable.
18180       if (BuildAndDiagnose) {
18181         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18182         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18183         auto *LSI = cast<LambdaScopeInfo>(CSI);
18184         if (LSI->Lambda) {
18185           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18186           buildLambdaCaptureFixit(*this, LSI, Var);
18187         }
18188         // FIXME: If we error out because an outer lambda can not implicitly
18189         // capture a variable that an inner lambda explicitly captures, we
18190         // should have the inner lambda do the explicit capture - because
18191         // it makes for cleaner diagnostics later.  This would purely be done
18192         // so that the diagnostic does not misleadingly claim that a variable
18193         // can not be captured by a lambda implicitly even though it is captured
18194         // explicitly.  Suggestion:
18195         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18196         //    at the function head
18197         //  - cache the StartingDeclContext - this must be a lambda
18198         //  - captureInLambda in the innermost lambda the variable.
18199       }
18200       return true;
18201     }
18202 
18203     FunctionScopesIndex--;
18204     DC = ParentDC;
18205     Explicit = false;
18206   } while (!VarDC->Equals(DC));
18207 
18208   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18209   // computing the type of the capture at each step, checking type-specific
18210   // requirements, and adding captures if requested.
18211   // If the variable had already been captured previously, we start capturing
18212   // at the lambda nested within that one.
18213   bool Invalid = false;
18214   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18215        ++I) {
18216     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18217 
18218     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18219     // certain types of variables (unnamed, variably modified types etc.)
18220     // so check for eligibility.
18221     if (!Invalid)
18222       Invalid =
18223           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18224 
18225     // After encountering an error, if we're actually supposed to capture, keep
18226     // capturing in nested contexts to suppress any follow-on diagnostics.
18227     if (Invalid && !BuildAndDiagnose)
18228       return true;
18229 
18230     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18231       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18232                                DeclRefType, Nested, *this, Invalid);
18233       Nested = true;
18234     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18235       Invalid = !captureInCapturedRegion(
18236           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18237           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18238       Nested = true;
18239     } else {
18240       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18241       Invalid =
18242           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18243                            DeclRefType, Nested, Kind, EllipsisLoc,
18244                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18245       Nested = true;
18246     }
18247 
18248     if (Invalid && !BuildAndDiagnose)
18249       return true;
18250   }
18251   return Invalid;
18252 }
18253 
18254 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18255                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18256   QualType CaptureType;
18257   QualType DeclRefType;
18258   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18259                             /*BuildAndDiagnose=*/true, CaptureType,
18260                             DeclRefType, nullptr);
18261 }
18262 
18263 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18264   QualType CaptureType;
18265   QualType DeclRefType;
18266   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18267                              /*BuildAndDiagnose=*/false, CaptureType,
18268                              DeclRefType, nullptr);
18269 }
18270 
18271 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18272   QualType CaptureType;
18273   QualType DeclRefType;
18274 
18275   // Determine whether we can capture this variable.
18276   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18277                          /*BuildAndDiagnose=*/false, CaptureType,
18278                          DeclRefType, nullptr))
18279     return QualType();
18280 
18281   return DeclRefType;
18282 }
18283 
18284 namespace {
18285 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18286 // The produced TemplateArgumentListInfo* points to data stored within this
18287 // object, so should only be used in contexts where the pointer will not be
18288 // used after the CopiedTemplateArgs object is destroyed.
18289 class CopiedTemplateArgs {
18290   bool HasArgs;
18291   TemplateArgumentListInfo TemplateArgStorage;
18292 public:
18293   template<typename RefExpr>
18294   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18295     if (HasArgs)
18296       E->copyTemplateArgumentsInto(TemplateArgStorage);
18297   }
18298   operator TemplateArgumentListInfo*()
18299 #ifdef __has_cpp_attribute
18300 #if __has_cpp_attribute(clang::lifetimebound)
18301   [[clang::lifetimebound]]
18302 #endif
18303 #endif
18304   {
18305     return HasArgs ? &TemplateArgStorage : nullptr;
18306   }
18307 };
18308 }
18309 
18310 /// Walk the set of potential results of an expression and mark them all as
18311 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18312 ///
18313 /// \return A new expression if we found any potential results, ExprEmpty() if
18314 ///         not, and ExprError() if we diagnosed an error.
18315 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18316                                                       NonOdrUseReason NOUR) {
18317   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18318   // an object that satisfies the requirements for appearing in a
18319   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18320   // is immediately applied."  This function handles the lvalue-to-rvalue
18321   // conversion part.
18322   //
18323   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18324   // transform it into the relevant kind of non-odr-use node and rebuild the
18325   // tree of nodes leading to it.
18326   //
18327   // This is a mini-TreeTransform that only transforms a restricted subset of
18328   // nodes (and only certain operands of them).
18329 
18330   // Rebuild a subexpression.
18331   auto Rebuild = [&](Expr *Sub) {
18332     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18333   };
18334 
18335   // Check whether a potential result satisfies the requirements of NOUR.
18336   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18337     // Any entity other than a VarDecl is always odr-used whenever it's named
18338     // in a potentially-evaluated expression.
18339     auto *VD = dyn_cast<VarDecl>(D);
18340     if (!VD)
18341       return true;
18342 
18343     // C++2a [basic.def.odr]p4:
18344     //   A variable x whose name appears as a potentially-evalauted expression
18345     //   e is odr-used by e unless
18346     //   -- x is a reference that is usable in constant expressions, or
18347     //   -- x is a variable of non-reference type that is usable in constant
18348     //      expressions and has no mutable subobjects, and e is an element of
18349     //      the set of potential results of an expression of
18350     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18351     //      conversion is applied, or
18352     //   -- x is a variable of non-reference type, and e is an element of the
18353     //      set of potential results of a discarded-value expression to which
18354     //      the lvalue-to-rvalue conversion is not applied
18355     //
18356     // We check the first bullet and the "potentially-evaluated" condition in
18357     // BuildDeclRefExpr. We check the type requirements in the second bullet
18358     // in CheckLValueToRValueConversionOperand below.
18359     switch (NOUR) {
18360     case NOUR_None:
18361     case NOUR_Unevaluated:
18362       llvm_unreachable("unexpected non-odr-use-reason");
18363 
18364     case NOUR_Constant:
18365       // Constant references were handled when they were built.
18366       if (VD->getType()->isReferenceType())
18367         return true;
18368       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18369         if (RD->hasMutableFields())
18370           return true;
18371       if (!VD->isUsableInConstantExpressions(S.Context))
18372         return true;
18373       break;
18374 
18375     case NOUR_Discarded:
18376       if (VD->getType()->isReferenceType())
18377         return true;
18378       break;
18379     }
18380     return false;
18381   };
18382 
18383   // Mark that this expression does not constitute an odr-use.
18384   auto MarkNotOdrUsed = [&] {
18385     S.MaybeODRUseExprs.remove(E);
18386     if (LambdaScopeInfo *LSI = S.getCurLambda())
18387       LSI->markVariableExprAsNonODRUsed(E);
18388   };
18389 
18390   // C++2a [basic.def.odr]p2:
18391   //   The set of potential results of an expression e is defined as follows:
18392   switch (E->getStmtClass()) {
18393   //   -- If e is an id-expression, ...
18394   case Expr::DeclRefExprClass: {
18395     auto *DRE = cast<DeclRefExpr>(E);
18396     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18397       break;
18398 
18399     // Rebuild as a non-odr-use DeclRefExpr.
18400     MarkNotOdrUsed();
18401     return DeclRefExpr::Create(
18402         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18403         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18404         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18405         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18406   }
18407 
18408   case Expr::FunctionParmPackExprClass: {
18409     auto *FPPE = cast<FunctionParmPackExpr>(E);
18410     // If any of the declarations in the pack is odr-used, then the expression
18411     // as a whole constitutes an odr-use.
18412     for (VarDecl *D : *FPPE)
18413       if (IsPotentialResultOdrUsed(D))
18414         return ExprEmpty();
18415 
18416     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18417     // nothing cares about whether we marked this as an odr-use, but it might
18418     // be useful for non-compiler tools.
18419     MarkNotOdrUsed();
18420     break;
18421   }
18422 
18423   //   -- If e is a subscripting operation with an array operand...
18424   case Expr::ArraySubscriptExprClass: {
18425     auto *ASE = cast<ArraySubscriptExpr>(E);
18426     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18427     if (!OldBase->getType()->isArrayType())
18428       break;
18429     ExprResult Base = Rebuild(OldBase);
18430     if (!Base.isUsable())
18431       return Base;
18432     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18433     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18434     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18435     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18436                                      ASE->getRBracketLoc());
18437   }
18438 
18439   case Expr::MemberExprClass: {
18440     auto *ME = cast<MemberExpr>(E);
18441     // -- If e is a class member access expression [...] naming a non-static
18442     //    data member...
18443     if (isa<FieldDecl>(ME->getMemberDecl())) {
18444       ExprResult Base = Rebuild(ME->getBase());
18445       if (!Base.isUsable())
18446         return Base;
18447       return MemberExpr::Create(
18448           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18449           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18450           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18451           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18452           ME->getObjectKind(), ME->isNonOdrUse());
18453     }
18454 
18455     if (ME->getMemberDecl()->isCXXInstanceMember())
18456       break;
18457 
18458     // -- If e is a class member access expression naming a static data member,
18459     //    ...
18460     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18461       break;
18462 
18463     // Rebuild as a non-odr-use MemberExpr.
18464     MarkNotOdrUsed();
18465     return MemberExpr::Create(
18466         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18467         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18468         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18469         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18470   }
18471 
18472   case Expr::BinaryOperatorClass: {
18473     auto *BO = cast<BinaryOperator>(E);
18474     Expr *LHS = BO->getLHS();
18475     Expr *RHS = BO->getRHS();
18476     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18477     if (BO->getOpcode() == BO_PtrMemD) {
18478       ExprResult Sub = Rebuild(LHS);
18479       if (!Sub.isUsable())
18480         return Sub;
18481       LHS = Sub.get();
18482     //   -- If e is a comma expression, ...
18483     } else if (BO->getOpcode() == BO_Comma) {
18484       ExprResult Sub = Rebuild(RHS);
18485       if (!Sub.isUsable())
18486         return Sub;
18487       RHS = Sub.get();
18488     } else {
18489       break;
18490     }
18491     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18492                         LHS, RHS);
18493   }
18494 
18495   //   -- If e has the form (e1)...
18496   case Expr::ParenExprClass: {
18497     auto *PE = cast<ParenExpr>(E);
18498     ExprResult Sub = Rebuild(PE->getSubExpr());
18499     if (!Sub.isUsable())
18500       return Sub;
18501     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18502   }
18503 
18504   //   -- If e is a glvalue conditional expression, ...
18505   // We don't apply this to a binary conditional operator. FIXME: Should we?
18506   case Expr::ConditionalOperatorClass: {
18507     auto *CO = cast<ConditionalOperator>(E);
18508     ExprResult LHS = Rebuild(CO->getLHS());
18509     if (LHS.isInvalid())
18510       return ExprError();
18511     ExprResult RHS = Rebuild(CO->getRHS());
18512     if (RHS.isInvalid())
18513       return ExprError();
18514     if (!LHS.isUsable() && !RHS.isUsable())
18515       return ExprEmpty();
18516     if (!LHS.isUsable())
18517       LHS = CO->getLHS();
18518     if (!RHS.isUsable())
18519       RHS = CO->getRHS();
18520     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18521                                 CO->getCond(), LHS.get(), RHS.get());
18522   }
18523 
18524   // [Clang extension]
18525   //   -- If e has the form __extension__ e1...
18526   case Expr::UnaryOperatorClass: {
18527     auto *UO = cast<UnaryOperator>(E);
18528     if (UO->getOpcode() != UO_Extension)
18529       break;
18530     ExprResult Sub = Rebuild(UO->getSubExpr());
18531     if (!Sub.isUsable())
18532       return Sub;
18533     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18534                           Sub.get());
18535   }
18536 
18537   // [Clang extension]
18538   //   -- If e has the form _Generic(...), the set of potential results is the
18539   //      union of the sets of potential results of the associated expressions.
18540   case Expr::GenericSelectionExprClass: {
18541     auto *GSE = cast<GenericSelectionExpr>(E);
18542 
18543     SmallVector<Expr *, 4> AssocExprs;
18544     bool AnyChanged = false;
18545     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18546       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18547       if (AssocExpr.isInvalid())
18548         return ExprError();
18549       if (AssocExpr.isUsable()) {
18550         AssocExprs.push_back(AssocExpr.get());
18551         AnyChanged = true;
18552       } else {
18553         AssocExprs.push_back(OrigAssocExpr);
18554       }
18555     }
18556 
18557     return AnyChanged ? S.CreateGenericSelectionExpr(
18558                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18559                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18560                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18561                       : ExprEmpty();
18562   }
18563 
18564   // [Clang extension]
18565   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18566   //      results is the union of the sets of potential results of the
18567   //      second and third subexpressions.
18568   case Expr::ChooseExprClass: {
18569     auto *CE = cast<ChooseExpr>(E);
18570 
18571     ExprResult LHS = Rebuild(CE->getLHS());
18572     if (LHS.isInvalid())
18573       return ExprError();
18574 
18575     ExprResult RHS = Rebuild(CE->getLHS());
18576     if (RHS.isInvalid())
18577       return ExprError();
18578 
18579     if (!LHS.get() && !RHS.get())
18580       return ExprEmpty();
18581     if (!LHS.isUsable())
18582       LHS = CE->getLHS();
18583     if (!RHS.isUsable())
18584       RHS = CE->getRHS();
18585 
18586     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18587                              RHS.get(), CE->getRParenLoc());
18588   }
18589 
18590   // Step through non-syntactic nodes.
18591   case Expr::ConstantExprClass: {
18592     auto *CE = cast<ConstantExpr>(E);
18593     ExprResult Sub = Rebuild(CE->getSubExpr());
18594     if (!Sub.isUsable())
18595       return Sub;
18596     return ConstantExpr::Create(S.Context, Sub.get());
18597   }
18598 
18599   // We could mostly rely on the recursive rebuilding to rebuild implicit
18600   // casts, but not at the top level, so rebuild them here.
18601   case Expr::ImplicitCastExprClass: {
18602     auto *ICE = cast<ImplicitCastExpr>(E);
18603     // Only step through the narrow set of cast kinds we expect to encounter.
18604     // Anything else suggests we've left the region in which potential results
18605     // can be found.
18606     switch (ICE->getCastKind()) {
18607     case CK_NoOp:
18608     case CK_DerivedToBase:
18609     case CK_UncheckedDerivedToBase: {
18610       ExprResult Sub = Rebuild(ICE->getSubExpr());
18611       if (!Sub.isUsable())
18612         return Sub;
18613       CXXCastPath Path(ICE->path());
18614       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18615                                  ICE->getValueKind(), &Path);
18616     }
18617 
18618     default:
18619       break;
18620     }
18621     break;
18622   }
18623 
18624   default:
18625     break;
18626   }
18627 
18628   // Can't traverse through this node. Nothing to do.
18629   return ExprEmpty();
18630 }
18631 
18632 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18633   // Check whether the operand is or contains an object of non-trivial C union
18634   // type.
18635   if (E->getType().isVolatileQualified() &&
18636       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18637        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18638     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18639                           Sema::NTCUC_LValueToRValueVolatile,
18640                           NTCUK_Destruct|NTCUK_Copy);
18641 
18642   // C++2a [basic.def.odr]p4:
18643   //   [...] an expression of non-volatile-qualified non-class type to which
18644   //   the lvalue-to-rvalue conversion is applied [...]
18645   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18646     return E;
18647 
18648   ExprResult Result =
18649       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18650   if (Result.isInvalid())
18651     return ExprError();
18652   return Result.get() ? Result : E;
18653 }
18654 
18655 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18656   Res = CorrectDelayedTyposInExpr(Res);
18657 
18658   if (!Res.isUsable())
18659     return Res;
18660 
18661   // If a constant-expression is a reference to a variable where we delay
18662   // deciding whether it is an odr-use, just assume we will apply the
18663   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18664   // (a non-type template argument), we have special handling anyway.
18665   return CheckLValueToRValueConversionOperand(Res.get());
18666 }
18667 
18668 void Sema::CleanupVarDeclMarking() {
18669   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18670   // call.
18671   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18672   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18673 
18674   for (Expr *E : LocalMaybeODRUseExprs) {
18675     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18676       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18677                          DRE->getLocation(), *this);
18678     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18679       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18680                          *this);
18681     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18682       for (VarDecl *VD : *FP)
18683         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18684     } else {
18685       llvm_unreachable("Unexpected expression");
18686     }
18687   }
18688 
18689   assert(MaybeODRUseExprs.empty() &&
18690          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18691 }
18692 
18693 static void DoMarkVarDeclReferenced(
18694     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18695     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18696   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18697           isa<FunctionParmPackExpr>(E)) &&
18698          "Invalid Expr argument to DoMarkVarDeclReferenced");
18699   Var->setReferenced();
18700 
18701   if (Var->isInvalidDecl())
18702     return;
18703 
18704   auto *MSI = Var->getMemberSpecializationInfo();
18705   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18706                                        : Var->getTemplateSpecializationKind();
18707 
18708   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18709   bool UsableInConstantExpr =
18710       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18711 
18712   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18713     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18714   }
18715 
18716   // C++20 [expr.const]p12:
18717   //   A variable [...] is needed for constant evaluation if it is [...] a
18718   //   variable whose name appears as a potentially constant evaluated
18719   //   expression that is either a contexpr variable or is of non-volatile
18720   //   const-qualified integral type or of reference type
18721   bool NeededForConstantEvaluation =
18722       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18723 
18724   bool NeedDefinition =
18725       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18726 
18727   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18728          "Can't instantiate a partial template specialization.");
18729 
18730   // If this might be a member specialization of a static data member, check
18731   // the specialization is visible. We already did the checks for variable
18732   // template specializations when we created them.
18733   if (NeedDefinition && TSK != TSK_Undeclared &&
18734       !isa<VarTemplateSpecializationDecl>(Var))
18735     SemaRef.checkSpecializationVisibility(Loc, Var);
18736 
18737   // Perform implicit instantiation of static data members, static data member
18738   // templates of class templates, and variable template specializations. Delay
18739   // instantiations of variable templates, except for those that could be used
18740   // in a constant expression.
18741   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18742     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18743     // instantiation declaration if a variable is usable in a constant
18744     // expression (among other cases).
18745     bool TryInstantiating =
18746         TSK == TSK_ImplicitInstantiation ||
18747         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18748 
18749     if (TryInstantiating) {
18750       SourceLocation PointOfInstantiation =
18751           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18752       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18753       if (FirstInstantiation) {
18754         PointOfInstantiation = Loc;
18755         if (MSI)
18756           MSI->setPointOfInstantiation(PointOfInstantiation);
18757           // FIXME: Notify listener.
18758         else
18759           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18760       }
18761 
18762       if (UsableInConstantExpr) {
18763         // Do not defer instantiations of variables that could be used in a
18764         // constant expression.
18765         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18766           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18767         });
18768 
18769         // Re-set the member to trigger a recomputation of the dependence bits
18770         // for the expression.
18771         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18772           DRE->setDecl(DRE->getDecl());
18773         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18774           ME->setMemberDecl(ME->getMemberDecl());
18775       } else if (FirstInstantiation ||
18776                  isa<VarTemplateSpecializationDecl>(Var)) {
18777         // FIXME: For a specialization of a variable template, we don't
18778         // distinguish between "declaration and type implicitly instantiated"
18779         // and "implicit instantiation of definition requested", so we have
18780         // no direct way to avoid enqueueing the pending instantiation
18781         // multiple times.
18782         SemaRef.PendingInstantiations
18783             .push_back(std::make_pair(Var, PointOfInstantiation));
18784       }
18785     }
18786   }
18787 
18788   // C++2a [basic.def.odr]p4:
18789   //   A variable x whose name appears as a potentially-evaluated expression e
18790   //   is odr-used by e unless
18791   //   -- x is a reference that is usable in constant expressions
18792   //   -- x is a variable of non-reference type that is usable in constant
18793   //      expressions and has no mutable subobjects [FIXME], and e is an
18794   //      element of the set of potential results of an expression of
18795   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18796   //      conversion is applied
18797   //   -- x is a variable of non-reference type, and e is an element of the set
18798   //      of potential results of a discarded-value expression to which the
18799   //      lvalue-to-rvalue conversion is not applied [FIXME]
18800   //
18801   // We check the first part of the second bullet here, and
18802   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18803   // FIXME: To get the third bullet right, we need to delay this even for
18804   // variables that are not usable in constant expressions.
18805 
18806   // If we already know this isn't an odr-use, there's nothing more to do.
18807   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18808     if (DRE->isNonOdrUse())
18809       return;
18810   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18811     if (ME->isNonOdrUse())
18812       return;
18813 
18814   switch (OdrUse) {
18815   case OdrUseContext::None:
18816     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18817            "missing non-odr-use marking for unevaluated decl ref");
18818     break;
18819 
18820   case OdrUseContext::FormallyOdrUsed:
18821     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18822     // behavior.
18823     break;
18824 
18825   case OdrUseContext::Used:
18826     // If we might later find that this expression isn't actually an odr-use,
18827     // delay the marking.
18828     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18829       SemaRef.MaybeODRUseExprs.insert(E);
18830     else
18831       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18832     break;
18833 
18834   case OdrUseContext::Dependent:
18835     // If this is a dependent context, we don't need to mark variables as
18836     // odr-used, but we may still need to track them for lambda capture.
18837     // FIXME: Do we also need to do this inside dependent typeid expressions
18838     // (which are modeled as unevaluated at this point)?
18839     const bool RefersToEnclosingScope =
18840         (SemaRef.CurContext != Var->getDeclContext() &&
18841          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18842     if (RefersToEnclosingScope) {
18843       LambdaScopeInfo *const LSI =
18844           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18845       if (LSI && (!LSI->CallOperator ||
18846                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18847         // If a variable could potentially be odr-used, defer marking it so
18848         // until we finish analyzing the full expression for any
18849         // lvalue-to-rvalue
18850         // or discarded value conversions that would obviate odr-use.
18851         // Add it to the list of potential captures that will be analyzed
18852         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18853         // unless the variable is a reference that was initialized by a constant
18854         // expression (this will never need to be captured or odr-used).
18855         //
18856         // FIXME: We can simplify this a lot after implementing P0588R1.
18857         assert(E && "Capture variable should be used in an expression.");
18858         if (!Var->getType()->isReferenceType() ||
18859             !Var->isUsableInConstantExpressions(SemaRef.Context))
18860           LSI->addPotentialCapture(E->IgnoreParens());
18861       }
18862     }
18863     break;
18864   }
18865 }
18866 
18867 /// Mark a variable referenced, and check whether it is odr-used
18868 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18869 /// used directly for normal expressions referring to VarDecl.
18870 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18871   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18872 }
18873 
18874 static void
18875 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18876                    bool MightBeOdrUse,
18877                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18878   if (SemaRef.isInOpenMPDeclareTargetContext())
18879     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18880 
18881   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18882     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18883     return;
18884   }
18885 
18886   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18887 
18888   // If this is a call to a method via a cast, also mark the method in the
18889   // derived class used in case codegen can devirtualize the call.
18890   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18891   if (!ME)
18892     return;
18893   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18894   if (!MD)
18895     return;
18896   // Only attempt to devirtualize if this is truly a virtual call.
18897   bool IsVirtualCall = MD->isVirtual() &&
18898                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18899   if (!IsVirtualCall)
18900     return;
18901 
18902   // If it's possible to devirtualize the call, mark the called function
18903   // referenced.
18904   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18905       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18906   if (DM)
18907     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18908 }
18909 
18910 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18911 ///
18912 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18913 /// handled with care if the DeclRefExpr is not newly-created.
18914 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18915   // TODO: update this with DR# once a defect report is filed.
18916   // C++11 defect. The address of a pure member should not be an ODR use, even
18917   // if it's a qualified reference.
18918   bool OdrUse = true;
18919   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18920     if (Method->isVirtual() &&
18921         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18922       OdrUse = false;
18923 
18924   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18925     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
18926         FD->isConsteval() && !RebuildingImmediateInvocation)
18927       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18928   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18929                      RefsMinusAssignments);
18930 }
18931 
18932 /// Perform reference-marking and odr-use handling for a MemberExpr.
18933 void Sema::MarkMemberReferenced(MemberExpr *E) {
18934   // C++11 [basic.def.odr]p2:
18935   //   A non-overloaded function whose name appears as a potentially-evaluated
18936   //   expression or a member of a set of candidate functions, if selected by
18937   //   overload resolution when referred to from a potentially-evaluated
18938   //   expression, is odr-used, unless it is a pure virtual function and its
18939   //   name is not explicitly qualified.
18940   bool MightBeOdrUse = true;
18941   if (E->performsVirtualDispatch(getLangOpts())) {
18942     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18943       if (Method->isPure())
18944         MightBeOdrUse = false;
18945   }
18946   SourceLocation Loc =
18947       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18948   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18949                      RefsMinusAssignments);
18950 }
18951 
18952 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18953 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18954   for (VarDecl *VD : *E)
18955     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18956                        RefsMinusAssignments);
18957 }
18958 
18959 /// Perform marking for a reference to an arbitrary declaration.  It
18960 /// marks the declaration referenced, and performs odr-use checking for
18961 /// functions and variables. This method should not be used when building a
18962 /// normal expression which refers to a variable.
18963 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18964                                  bool MightBeOdrUse) {
18965   if (MightBeOdrUse) {
18966     if (auto *VD = dyn_cast<VarDecl>(D)) {
18967       MarkVariableReferenced(Loc, VD);
18968       return;
18969     }
18970   }
18971   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18972     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18973     return;
18974   }
18975   D->setReferenced();
18976 }
18977 
18978 namespace {
18979   // Mark all of the declarations used by a type as referenced.
18980   // FIXME: Not fully implemented yet! We need to have a better understanding
18981   // of when we're entering a context we should not recurse into.
18982   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18983   // TreeTransforms rebuilding the type in a new context. Rather than
18984   // duplicating the TreeTransform logic, we should consider reusing it here.
18985   // Currently that causes problems when rebuilding LambdaExprs.
18986   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18987     Sema &S;
18988     SourceLocation Loc;
18989 
18990   public:
18991     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18992 
18993     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18994 
18995     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18996   };
18997 }
18998 
18999 bool MarkReferencedDecls::TraverseTemplateArgument(
19000     const TemplateArgument &Arg) {
19001   {
19002     // A non-type template argument is a constant-evaluated context.
19003     EnterExpressionEvaluationContext Evaluated(
19004         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19005     if (Arg.getKind() == TemplateArgument::Declaration) {
19006       if (Decl *D = Arg.getAsDecl())
19007         S.MarkAnyDeclReferenced(Loc, D, true);
19008     } else if (Arg.getKind() == TemplateArgument::Expression) {
19009       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19010     }
19011   }
19012 
19013   return Inherited::TraverseTemplateArgument(Arg);
19014 }
19015 
19016 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19017   MarkReferencedDecls Marker(*this, Loc);
19018   Marker.TraverseType(T);
19019 }
19020 
19021 namespace {
19022 /// Helper class that marks all of the declarations referenced by
19023 /// potentially-evaluated subexpressions as "referenced".
19024 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19025 public:
19026   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19027   bool SkipLocalVariables;
19028   ArrayRef<const Expr *> StopAt;
19029 
19030   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19031                       ArrayRef<const Expr *> StopAt)
19032       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19033 
19034   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19035     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19036   }
19037 
19038   void Visit(Expr *E) {
19039     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19040       return;
19041     Inherited::Visit(E);
19042   }
19043 
19044   void VisitDeclRefExpr(DeclRefExpr *E) {
19045     // If we were asked not to visit local variables, don't.
19046     if (SkipLocalVariables) {
19047       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19048         if (VD->hasLocalStorage())
19049           return;
19050     }
19051 
19052     // FIXME: This can trigger the instantiation of the initializer of a
19053     // variable, which can cause the expression to become value-dependent
19054     // or error-dependent. Do we need to propagate the new dependence bits?
19055     S.MarkDeclRefReferenced(E);
19056   }
19057 
19058   void VisitMemberExpr(MemberExpr *E) {
19059     S.MarkMemberReferenced(E);
19060     Visit(E->getBase());
19061   }
19062 };
19063 } // namespace
19064 
19065 /// Mark any declarations that appear within this expression or any
19066 /// potentially-evaluated subexpressions as "referenced".
19067 ///
19068 /// \param SkipLocalVariables If true, don't mark local variables as
19069 /// 'referenced'.
19070 /// \param StopAt Subexpressions that we shouldn't recurse into.
19071 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19072                                             bool SkipLocalVariables,
19073                                             ArrayRef<const Expr*> StopAt) {
19074   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19075 }
19076 
19077 /// Emit a diagnostic when statements are reachable.
19078 /// FIXME: check for reachability even in expressions for which we don't build a
19079 ///        CFG (eg, in the initializer of a global or in a constant expression).
19080 ///        For example,
19081 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19082 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19083                            const PartialDiagnostic &PD) {
19084   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19085     if (!FunctionScopes.empty())
19086       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19087           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19088     return true;
19089   }
19090 
19091   // The initializer of a constexpr variable or of the first declaration of a
19092   // static data member is not syntactically a constant evaluated constant,
19093   // but nonetheless is always required to be a constant expression, so we
19094   // can skip diagnosing.
19095   // FIXME: Using the mangling context here is a hack.
19096   if (auto *VD = dyn_cast_or_null<VarDecl>(
19097           ExprEvalContexts.back().ManglingContextDecl)) {
19098     if (VD->isConstexpr() ||
19099         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19100       return false;
19101     // FIXME: For any other kind of variable, we should build a CFG for its
19102     // initializer and check whether the context in question is reachable.
19103   }
19104 
19105   Diag(Loc, PD);
19106   return true;
19107 }
19108 
19109 /// Emit a diagnostic that describes an effect on the run-time behavior
19110 /// of the program being compiled.
19111 ///
19112 /// This routine emits the given diagnostic when the code currently being
19113 /// type-checked is "potentially evaluated", meaning that there is a
19114 /// possibility that the code will actually be executable. Code in sizeof()
19115 /// expressions, code used only during overload resolution, etc., are not
19116 /// potentially evaluated. This routine will suppress such diagnostics or,
19117 /// in the absolutely nutty case of potentially potentially evaluated
19118 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19119 /// later.
19120 ///
19121 /// This routine should be used for all diagnostics that describe the run-time
19122 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19123 /// Failure to do so will likely result in spurious diagnostics or failures
19124 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19125 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19126                                const PartialDiagnostic &PD) {
19127 
19128   if (ExprEvalContexts.back().isDiscardedStatementContext())
19129     return false;
19130 
19131   switch (ExprEvalContexts.back().Context) {
19132   case ExpressionEvaluationContext::Unevaluated:
19133   case ExpressionEvaluationContext::UnevaluatedList:
19134   case ExpressionEvaluationContext::UnevaluatedAbstract:
19135   case ExpressionEvaluationContext::DiscardedStatement:
19136     // The argument will never be evaluated, so don't complain.
19137     break;
19138 
19139   case ExpressionEvaluationContext::ConstantEvaluated:
19140   case ExpressionEvaluationContext::ImmediateFunctionContext:
19141     // Relevant diagnostics should be produced by constant evaluation.
19142     break;
19143 
19144   case ExpressionEvaluationContext::PotentiallyEvaluated:
19145   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19146     return DiagIfReachable(Loc, Stmts, PD);
19147   }
19148 
19149   return false;
19150 }
19151 
19152 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19153                                const PartialDiagnostic &PD) {
19154   return DiagRuntimeBehavior(
19155       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19156 }
19157 
19158 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19159                                CallExpr *CE, FunctionDecl *FD) {
19160   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19161     return false;
19162 
19163   // If we're inside a decltype's expression, don't check for a valid return
19164   // type or construct temporaries until we know whether this is the last call.
19165   if (ExprEvalContexts.back().ExprContext ==
19166       ExpressionEvaluationContextRecord::EK_Decltype) {
19167     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19168     return false;
19169   }
19170 
19171   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19172     FunctionDecl *FD;
19173     CallExpr *CE;
19174 
19175   public:
19176     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19177       : FD(FD), CE(CE) { }
19178 
19179     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19180       if (!FD) {
19181         S.Diag(Loc, diag::err_call_incomplete_return)
19182           << T << CE->getSourceRange();
19183         return;
19184       }
19185 
19186       S.Diag(Loc, diag::err_call_function_incomplete_return)
19187           << CE->getSourceRange() << FD << T;
19188       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19189           << FD->getDeclName();
19190     }
19191   } Diagnoser(FD, CE);
19192 
19193   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19194     return true;
19195 
19196   return false;
19197 }
19198 
19199 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19200 // will prevent this condition from triggering, which is what we want.
19201 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19202   SourceLocation Loc;
19203 
19204   unsigned diagnostic = diag::warn_condition_is_assignment;
19205   bool IsOrAssign = false;
19206 
19207   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19208     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19209       return;
19210 
19211     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19212 
19213     // Greylist some idioms by putting them into a warning subcategory.
19214     if (ObjCMessageExpr *ME
19215           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19216       Selector Sel = ME->getSelector();
19217 
19218       // self = [<foo> init...]
19219       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19220         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19221 
19222       // <foo> = [<bar> nextObject]
19223       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19224         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19225     }
19226 
19227     Loc = Op->getOperatorLoc();
19228   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19229     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19230       return;
19231 
19232     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19233     Loc = Op->getOperatorLoc();
19234   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19235     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19236   else {
19237     // Not an assignment.
19238     return;
19239   }
19240 
19241   Diag(Loc, diagnostic) << E->getSourceRange();
19242 
19243   SourceLocation Open = E->getBeginLoc();
19244   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19245   Diag(Loc, diag::note_condition_assign_silence)
19246         << FixItHint::CreateInsertion(Open, "(")
19247         << FixItHint::CreateInsertion(Close, ")");
19248 
19249   if (IsOrAssign)
19250     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19251       << FixItHint::CreateReplacement(Loc, "!=");
19252   else
19253     Diag(Loc, diag::note_condition_assign_to_comparison)
19254       << FixItHint::CreateReplacement(Loc, "==");
19255 }
19256 
19257 /// Redundant parentheses over an equality comparison can indicate
19258 /// that the user intended an assignment used as condition.
19259 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19260   // Don't warn if the parens came from a macro.
19261   SourceLocation parenLoc = ParenE->getBeginLoc();
19262   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19263     return;
19264   // Don't warn for dependent expressions.
19265   if (ParenE->isTypeDependent())
19266     return;
19267 
19268   Expr *E = ParenE->IgnoreParens();
19269 
19270   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19271     if (opE->getOpcode() == BO_EQ &&
19272         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19273                                                            == Expr::MLV_Valid) {
19274       SourceLocation Loc = opE->getOperatorLoc();
19275 
19276       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19277       SourceRange ParenERange = ParenE->getSourceRange();
19278       Diag(Loc, diag::note_equality_comparison_silence)
19279         << FixItHint::CreateRemoval(ParenERange.getBegin())
19280         << FixItHint::CreateRemoval(ParenERange.getEnd());
19281       Diag(Loc, diag::note_equality_comparison_to_assign)
19282         << FixItHint::CreateReplacement(Loc, "=");
19283     }
19284 }
19285 
19286 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19287                                        bool IsConstexpr) {
19288   DiagnoseAssignmentAsCondition(E);
19289   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19290     DiagnoseEqualityWithExtraParens(parenE);
19291 
19292   ExprResult result = CheckPlaceholderExpr(E);
19293   if (result.isInvalid()) return ExprError();
19294   E = result.get();
19295 
19296   if (!E->isTypeDependent()) {
19297     if (getLangOpts().CPlusPlus)
19298       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19299 
19300     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19301     if (ERes.isInvalid())
19302       return ExprError();
19303     E = ERes.get();
19304 
19305     QualType T = E->getType();
19306     if (!T->isScalarType()) { // C99 6.8.4.1p1
19307       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19308         << T << E->getSourceRange();
19309       return ExprError();
19310     }
19311     CheckBoolLikeConversion(E, Loc);
19312   }
19313 
19314   return E;
19315 }
19316 
19317 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19318                                            Expr *SubExpr, ConditionKind CK,
19319                                            bool MissingOK) {
19320   // MissingOK indicates whether having no condition expression is valid
19321   // (for loop) or invalid (e.g. while loop).
19322   if (!SubExpr)
19323     return MissingOK ? ConditionResult() : ConditionError();
19324 
19325   ExprResult Cond;
19326   switch (CK) {
19327   case ConditionKind::Boolean:
19328     Cond = CheckBooleanCondition(Loc, SubExpr);
19329     break;
19330 
19331   case ConditionKind::ConstexprIf:
19332     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19333     break;
19334 
19335   case ConditionKind::Switch:
19336     Cond = CheckSwitchCondition(Loc, SubExpr);
19337     break;
19338   }
19339   if (Cond.isInvalid()) {
19340     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19341                               {SubExpr}, PreferredConditionType(CK));
19342     if (!Cond.get())
19343       return ConditionError();
19344   }
19345   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19346   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19347   if (!FullExpr.get())
19348     return ConditionError();
19349 
19350   return ConditionResult(*this, nullptr, FullExpr,
19351                          CK == ConditionKind::ConstexprIf);
19352 }
19353 
19354 namespace {
19355   /// A visitor for rebuilding a call to an __unknown_any expression
19356   /// to have an appropriate type.
19357   struct RebuildUnknownAnyFunction
19358     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19359 
19360     Sema &S;
19361 
19362     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19363 
19364     ExprResult VisitStmt(Stmt *S) {
19365       llvm_unreachable("unexpected statement!");
19366     }
19367 
19368     ExprResult VisitExpr(Expr *E) {
19369       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19370         << E->getSourceRange();
19371       return ExprError();
19372     }
19373 
19374     /// Rebuild an expression which simply semantically wraps another
19375     /// expression which it shares the type and value kind of.
19376     template <class T> ExprResult rebuildSugarExpr(T *E) {
19377       ExprResult SubResult = Visit(E->getSubExpr());
19378       if (SubResult.isInvalid()) return ExprError();
19379 
19380       Expr *SubExpr = SubResult.get();
19381       E->setSubExpr(SubExpr);
19382       E->setType(SubExpr->getType());
19383       E->setValueKind(SubExpr->getValueKind());
19384       assert(E->getObjectKind() == OK_Ordinary);
19385       return E;
19386     }
19387 
19388     ExprResult VisitParenExpr(ParenExpr *E) {
19389       return rebuildSugarExpr(E);
19390     }
19391 
19392     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19393       return rebuildSugarExpr(E);
19394     }
19395 
19396     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19397       ExprResult SubResult = Visit(E->getSubExpr());
19398       if (SubResult.isInvalid()) return ExprError();
19399 
19400       Expr *SubExpr = SubResult.get();
19401       E->setSubExpr(SubExpr);
19402       E->setType(S.Context.getPointerType(SubExpr->getType()));
19403       assert(E->isPRValue());
19404       assert(E->getObjectKind() == OK_Ordinary);
19405       return E;
19406     }
19407 
19408     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19409       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19410 
19411       E->setType(VD->getType());
19412 
19413       assert(E->isPRValue());
19414       if (S.getLangOpts().CPlusPlus &&
19415           !(isa<CXXMethodDecl>(VD) &&
19416             cast<CXXMethodDecl>(VD)->isInstance()))
19417         E->setValueKind(VK_LValue);
19418 
19419       return E;
19420     }
19421 
19422     ExprResult VisitMemberExpr(MemberExpr *E) {
19423       return resolveDecl(E, E->getMemberDecl());
19424     }
19425 
19426     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19427       return resolveDecl(E, E->getDecl());
19428     }
19429   };
19430 }
19431 
19432 /// Given a function expression of unknown-any type, try to rebuild it
19433 /// to have a function type.
19434 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19435   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19436   if (Result.isInvalid()) return ExprError();
19437   return S.DefaultFunctionArrayConversion(Result.get());
19438 }
19439 
19440 namespace {
19441   /// A visitor for rebuilding an expression of type __unknown_anytype
19442   /// into one which resolves the type directly on the referring
19443   /// expression.  Strict preservation of the original source
19444   /// structure is not a goal.
19445   struct RebuildUnknownAnyExpr
19446     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19447 
19448     Sema &S;
19449 
19450     /// The current destination type.
19451     QualType DestType;
19452 
19453     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19454       : S(S), DestType(CastType) {}
19455 
19456     ExprResult VisitStmt(Stmt *S) {
19457       llvm_unreachable("unexpected statement!");
19458     }
19459 
19460     ExprResult VisitExpr(Expr *E) {
19461       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19462         << E->getSourceRange();
19463       return ExprError();
19464     }
19465 
19466     ExprResult VisitCallExpr(CallExpr *E);
19467     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19468 
19469     /// Rebuild an expression which simply semantically wraps another
19470     /// expression which it shares the type and value kind of.
19471     template <class T> ExprResult rebuildSugarExpr(T *E) {
19472       ExprResult SubResult = Visit(E->getSubExpr());
19473       if (SubResult.isInvalid()) return ExprError();
19474       Expr *SubExpr = SubResult.get();
19475       E->setSubExpr(SubExpr);
19476       E->setType(SubExpr->getType());
19477       E->setValueKind(SubExpr->getValueKind());
19478       assert(E->getObjectKind() == OK_Ordinary);
19479       return E;
19480     }
19481 
19482     ExprResult VisitParenExpr(ParenExpr *E) {
19483       return rebuildSugarExpr(E);
19484     }
19485 
19486     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19487       return rebuildSugarExpr(E);
19488     }
19489 
19490     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19491       const PointerType *Ptr = DestType->getAs<PointerType>();
19492       if (!Ptr) {
19493         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19494           << E->getSourceRange();
19495         return ExprError();
19496       }
19497 
19498       if (isa<CallExpr>(E->getSubExpr())) {
19499         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19500           << E->getSourceRange();
19501         return ExprError();
19502       }
19503 
19504       assert(E->isPRValue());
19505       assert(E->getObjectKind() == OK_Ordinary);
19506       E->setType(DestType);
19507 
19508       // Build the sub-expression as if it were an object of the pointee type.
19509       DestType = Ptr->getPointeeType();
19510       ExprResult SubResult = Visit(E->getSubExpr());
19511       if (SubResult.isInvalid()) return ExprError();
19512       E->setSubExpr(SubResult.get());
19513       return E;
19514     }
19515 
19516     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19517 
19518     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19519 
19520     ExprResult VisitMemberExpr(MemberExpr *E) {
19521       return resolveDecl(E, E->getMemberDecl());
19522     }
19523 
19524     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19525       return resolveDecl(E, E->getDecl());
19526     }
19527   };
19528 }
19529 
19530 /// Rebuilds a call expression which yielded __unknown_anytype.
19531 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19532   Expr *CalleeExpr = E->getCallee();
19533 
19534   enum FnKind {
19535     FK_MemberFunction,
19536     FK_FunctionPointer,
19537     FK_BlockPointer
19538   };
19539 
19540   FnKind Kind;
19541   QualType CalleeType = CalleeExpr->getType();
19542   if (CalleeType == S.Context.BoundMemberTy) {
19543     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19544     Kind = FK_MemberFunction;
19545     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19546   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19547     CalleeType = Ptr->getPointeeType();
19548     Kind = FK_FunctionPointer;
19549   } else {
19550     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19551     Kind = FK_BlockPointer;
19552   }
19553   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19554 
19555   // Verify that this is a legal result type of a function.
19556   if (DestType->isArrayType() || DestType->isFunctionType()) {
19557     unsigned diagID = diag::err_func_returning_array_function;
19558     if (Kind == FK_BlockPointer)
19559       diagID = diag::err_block_returning_array_function;
19560 
19561     S.Diag(E->getExprLoc(), diagID)
19562       << DestType->isFunctionType() << DestType;
19563     return ExprError();
19564   }
19565 
19566   // Otherwise, go ahead and set DestType as the call's result.
19567   E->setType(DestType.getNonLValueExprType(S.Context));
19568   E->setValueKind(Expr::getValueKindForType(DestType));
19569   assert(E->getObjectKind() == OK_Ordinary);
19570 
19571   // Rebuild the function type, replacing the result type with DestType.
19572   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19573   if (Proto) {
19574     // __unknown_anytype(...) is a special case used by the debugger when
19575     // it has no idea what a function's signature is.
19576     //
19577     // We want to build this call essentially under the K&R
19578     // unprototyped rules, but making a FunctionNoProtoType in C++
19579     // would foul up all sorts of assumptions.  However, we cannot
19580     // simply pass all arguments as variadic arguments, nor can we
19581     // portably just call the function under a non-variadic type; see
19582     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19583     // However, it turns out that in practice it is generally safe to
19584     // call a function declared as "A foo(B,C,D);" under the prototype
19585     // "A foo(B,C,D,...);".  The only known exception is with the
19586     // Windows ABI, where any variadic function is implicitly cdecl
19587     // regardless of its normal CC.  Therefore we change the parameter
19588     // types to match the types of the arguments.
19589     //
19590     // This is a hack, but it is far superior to moving the
19591     // corresponding target-specific code from IR-gen to Sema/AST.
19592 
19593     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19594     SmallVector<QualType, 8> ArgTypes;
19595     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19596       ArgTypes.reserve(E->getNumArgs());
19597       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19598         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19599       }
19600       ParamTypes = ArgTypes;
19601     }
19602     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19603                                          Proto->getExtProtoInfo());
19604   } else {
19605     DestType = S.Context.getFunctionNoProtoType(DestType,
19606                                                 FnType->getExtInfo());
19607   }
19608 
19609   // Rebuild the appropriate pointer-to-function type.
19610   switch (Kind) {
19611   case FK_MemberFunction:
19612     // Nothing to do.
19613     break;
19614 
19615   case FK_FunctionPointer:
19616     DestType = S.Context.getPointerType(DestType);
19617     break;
19618 
19619   case FK_BlockPointer:
19620     DestType = S.Context.getBlockPointerType(DestType);
19621     break;
19622   }
19623 
19624   // Finally, we can recurse.
19625   ExprResult CalleeResult = Visit(CalleeExpr);
19626   if (!CalleeResult.isUsable()) return ExprError();
19627   E->setCallee(CalleeResult.get());
19628 
19629   // Bind a temporary if necessary.
19630   return S.MaybeBindToTemporary(E);
19631 }
19632 
19633 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19634   // Verify that this is a legal result type of a call.
19635   if (DestType->isArrayType() || DestType->isFunctionType()) {
19636     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19637       << DestType->isFunctionType() << DestType;
19638     return ExprError();
19639   }
19640 
19641   // Rewrite the method result type if available.
19642   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19643     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19644     Method->setReturnType(DestType);
19645   }
19646 
19647   // Change the type of the message.
19648   E->setType(DestType.getNonReferenceType());
19649   E->setValueKind(Expr::getValueKindForType(DestType));
19650 
19651   return S.MaybeBindToTemporary(E);
19652 }
19653 
19654 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19655   // The only case we should ever see here is a function-to-pointer decay.
19656   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19657     assert(E->isPRValue());
19658     assert(E->getObjectKind() == OK_Ordinary);
19659 
19660     E->setType(DestType);
19661 
19662     // Rebuild the sub-expression as the pointee (function) type.
19663     DestType = DestType->castAs<PointerType>()->getPointeeType();
19664 
19665     ExprResult Result = Visit(E->getSubExpr());
19666     if (!Result.isUsable()) return ExprError();
19667 
19668     E->setSubExpr(Result.get());
19669     return E;
19670   } else if (E->getCastKind() == CK_LValueToRValue) {
19671     assert(E->isPRValue());
19672     assert(E->getObjectKind() == OK_Ordinary);
19673 
19674     assert(isa<BlockPointerType>(E->getType()));
19675 
19676     E->setType(DestType);
19677 
19678     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19679     DestType = S.Context.getLValueReferenceType(DestType);
19680 
19681     ExprResult Result = Visit(E->getSubExpr());
19682     if (!Result.isUsable()) return ExprError();
19683 
19684     E->setSubExpr(Result.get());
19685     return E;
19686   } else {
19687     llvm_unreachable("Unhandled cast type!");
19688   }
19689 }
19690 
19691 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19692   ExprValueKind ValueKind = VK_LValue;
19693   QualType Type = DestType;
19694 
19695   // We know how to make this work for certain kinds of decls:
19696 
19697   //  - functions
19698   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19699     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19700       DestType = Ptr->getPointeeType();
19701       ExprResult Result = resolveDecl(E, VD);
19702       if (Result.isInvalid()) return ExprError();
19703       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19704                                  VK_PRValue);
19705     }
19706 
19707     if (!Type->isFunctionType()) {
19708       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19709         << VD << E->getSourceRange();
19710       return ExprError();
19711     }
19712     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19713       // We must match the FunctionDecl's type to the hack introduced in
19714       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19715       // type. See the lengthy commentary in that routine.
19716       QualType FDT = FD->getType();
19717       const FunctionType *FnType = FDT->castAs<FunctionType>();
19718       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19719       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19720       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19721         SourceLocation Loc = FD->getLocation();
19722         FunctionDecl *NewFD = FunctionDecl::Create(
19723             S.Context, FD->getDeclContext(), Loc, Loc,
19724             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19725             SC_None, S.getCurFPFeatures().isFPConstrained(),
19726             false /*isInlineSpecified*/, FD->hasPrototype(),
19727             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19728 
19729         if (FD->getQualifier())
19730           NewFD->setQualifierInfo(FD->getQualifierLoc());
19731 
19732         SmallVector<ParmVarDecl*, 16> Params;
19733         for (const auto &AI : FT->param_types()) {
19734           ParmVarDecl *Param =
19735             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19736           Param->setScopeInfo(0, Params.size());
19737           Params.push_back(Param);
19738         }
19739         NewFD->setParams(Params);
19740         DRE->setDecl(NewFD);
19741         VD = DRE->getDecl();
19742       }
19743     }
19744 
19745     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19746       if (MD->isInstance()) {
19747         ValueKind = VK_PRValue;
19748         Type = S.Context.BoundMemberTy;
19749       }
19750 
19751     // Function references aren't l-values in C.
19752     if (!S.getLangOpts().CPlusPlus)
19753       ValueKind = VK_PRValue;
19754 
19755   //  - variables
19756   } else if (isa<VarDecl>(VD)) {
19757     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19758       Type = RefTy->getPointeeType();
19759     } else if (Type->isFunctionType()) {
19760       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19761         << VD << E->getSourceRange();
19762       return ExprError();
19763     }
19764 
19765   //  - nothing else
19766   } else {
19767     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19768       << VD << E->getSourceRange();
19769     return ExprError();
19770   }
19771 
19772   // Modifying the declaration like this is friendly to IR-gen but
19773   // also really dangerous.
19774   VD->setType(DestType);
19775   E->setType(Type);
19776   E->setValueKind(ValueKind);
19777   return E;
19778 }
19779 
19780 /// Check a cast of an unknown-any type.  We intentionally only
19781 /// trigger this for C-style casts.
19782 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19783                                      Expr *CastExpr, CastKind &CastKind,
19784                                      ExprValueKind &VK, CXXCastPath &Path) {
19785   // The type we're casting to must be either void or complete.
19786   if (!CastType->isVoidType() &&
19787       RequireCompleteType(TypeRange.getBegin(), CastType,
19788                           diag::err_typecheck_cast_to_incomplete))
19789     return ExprError();
19790 
19791   // Rewrite the casted expression from scratch.
19792   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19793   if (!result.isUsable()) return ExprError();
19794 
19795   CastExpr = result.get();
19796   VK = CastExpr->getValueKind();
19797   CastKind = CK_NoOp;
19798 
19799   return CastExpr;
19800 }
19801 
19802 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19803   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19804 }
19805 
19806 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19807                                     Expr *arg, QualType &paramType) {
19808   // If the syntactic form of the argument is not an explicit cast of
19809   // any sort, just do default argument promotion.
19810   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19811   if (!castArg) {
19812     ExprResult result = DefaultArgumentPromotion(arg);
19813     if (result.isInvalid()) return ExprError();
19814     paramType = result.get()->getType();
19815     return result;
19816   }
19817 
19818   // Otherwise, use the type that was written in the explicit cast.
19819   assert(!arg->hasPlaceholderType());
19820   paramType = castArg->getTypeAsWritten();
19821 
19822   // Copy-initialize a parameter of that type.
19823   InitializedEntity entity =
19824     InitializedEntity::InitializeParameter(Context, paramType,
19825                                            /*consumed*/ false);
19826   return PerformCopyInitialization(entity, callLoc, arg);
19827 }
19828 
19829 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19830   Expr *orig = E;
19831   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19832   while (true) {
19833     E = E->IgnoreParenImpCasts();
19834     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19835       E = call->getCallee();
19836       diagID = diag::err_uncasted_call_of_unknown_any;
19837     } else {
19838       break;
19839     }
19840   }
19841 
19842   SourceLocation loc;
19843   NamedDecl *d;
19844   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19845     loc = ref->getLocation();
19846     d = ref->getDecl();
19847   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19848     loc = mem->getMemberLoc();
19849     d = mem->getMemberDecl();
19850   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19851     diagID = diag::err_uncasted_call_of_unknown_any;
19852     loc = msg->getSelectorStartLoc();
19853     d = msg->getMethodDecl();
19854     if (!d) {
19855       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19856         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19857         << orig->getSourceRange();
19858       return ExprError();
19859     }
19860   } else {
19861     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19862       << E->getSourceRange();
19863     return ExprError();
19864   }
19865 
19866   S.Diag(loc, diagID) << d << orig->getSourceRange();
19867 
19868   // Never recoverable.
19869   return ExprError();
19870 }
19871 
19872 /// Check for operands with placeholder types and complain if found.
19873 /// Returns ExprError() if there was an error and no recovery was possible.
19874 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19875   if (!Context.isDependenceAllowed()) {
19876     // C cannot handle TypoExpr nodes on either side of a binop because it
19877     // doesn't handle dependent types properly, so make sure any TypoExprs have
19878     // been dealt with before checking the operands.
19879     ExprResult Result = CorrectDelayedTyposInExpr(E);
19880     if (!Result.isUsable()) return ExprError();
19881     E = Result.get();
19882   }
19883 
19884   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19885   if (!placeholderType) return E;
19886 
19887   switch (placeholderType->getKind()) {
19888 
19889   // Overloaded expressions.
19890   case BuiltinType::Overload: {
19891     // Try to resolve a single function template specialization.
19892     // This is obligatory.
19893     ExprResult Result = E;
19894     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19895       return Result;
19896 
19897     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19898     // leaves Result unchanged on failure.
19899     Result = E;
19900     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19901       return Result;
19902 
19903     // If that failed, try to recover with a call.
19904     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19905                          /*complain*/ true);
19906     return Result;
19907   }
19908 
19909   // Bound member functions.
19910   case BuiltinType::BoundMember: {
19911     ExprResult result = E;
19912     const Expr *BME = E->IgnoreParens();
19913     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19914     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19915     if (isa<CXXPseudoDestructorExpr>(BME)) {
19916       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19917     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19918       if (ME->getMemberNameInfo().getName().getNameKind() ==
19919           DeclarationName::CXXDestructorName)
19920         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19921     }
19922     tryToRecoverWithCall(result, PD,
19923                          /*complain*/ true);
19924     return result;
19925   }
19926 
19927   // ARC unbridged casts.
19928   case BuiltinType::ARCUnbridgedCast: {
19929     Expr *realCast = stripARCUnbridgedCast(E);
19930     diagnoseARCUnbridgedCast(realCast);
19931     return realCast;
19932   }
19933 
19934   // Expressions of unknown type.
19935   case BuiltinType::UnknownAny:
19936     return diagnoseUnknownAnyExpr(*this, E);
19937 
19938   // Pseudo-objects.
19939   case BuiltinType::PseudoObject:
19940     return checkPseudoObjectRValue(E);
19941 
19942   case BuiltinType::BuiltinFn: {
19943     // Accept __noop without parens by implicitly converting it to a call expr.
19944     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19945     if (DRE) {
19946       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19947       if (FD->getBuiltinID() == Builtin::BI__noop) {
19948         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19949                               CK_BuiltinFnToFnPtr)
19950                 .get();
19951         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19952                                 VK_PRValue, SourceLocation(),
19953                                 FPOptionsOverride());
19954       }
19955     }
19956 
19957     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19958     return ExprError();
19959   }
19960 
19961   case BuiltinType::IncompleteMatrixIdx:
19962     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19963              ->getRowIdx()
19964              ->getBeginLoc(),
19965          diag::err_matrix_incomplete_index);
19966     return ExprError();
19967 
19968   // Expressions of unknown type.
19969   case BuiltinType::OMPArraySection:
19970     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19971     return ExprError();
19972 
19973   // Expressions of unknown type.
19974   case BuiltinType::OMPArrayShaping:
19975     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19976 
19977   case BuiltinType::OMPIterator:
19978     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19979 
19980   // Everything else should be impossible.
19981 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19982   case BuiltinType::Id:
19983 #include "clang/Basic/OpenCLImageTypes.def"
19984 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19985   case BuiltinType::Id:
19986 #include "clang/Basic/OpenCLExtensionTypes.def"
19987 #define SVE_TYPE(Name, Id, SingletonId) \
19988   case BuiltinType::Id:
19989 #include "clang/Basic/AArch64SVEACLETypes.def"
19990 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19991   case BuiltinType::Id:
19992 #include "clang/Basic/PPCTypes.def"
19993 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19994 #include "clang/Basic/RISCVVTypes.def"
19995 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19996 #define PLACEHOLDER_TYPE(Id, SingletonId)
19997 #include "clang/AST/BuiltinTypes.def"
19998     break;
19999   }
20000 
20001   llvm_unreachable("invalid placeholder type!");
20002 }
20003 
20004 bool Sema::CheckCaseExpression(Expr *E) {
20005   if (E->isTypeDependent())
20006     return true;
20007   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20008     return E->getType()->isIntegralOrEnumerationType();
20009   return false;
20010 }
20011 
20012 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20013 ExprResult
20014 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20015   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20016          "Unknown Objective-C Boolean value!");
20017   QualType BoolT = Context.ObjCBuiltinBoolTy;
20018   if (!Context.getBOOLDecl()) {
20019     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20020                         Sema::LookupOrdinaryName);
20021     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20022       NamedDecl *ND = Result.getFoundDecl();
20023       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20024         Context.setBOOLDecl(TD);
20025     }
20026   }
20027   if (Context.getBOOLDecl())
20028     BoolT = Context.getBOOLType();
20029   return new (Context)
20030       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20031 }
20032 
20033 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20034     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20035     SourceLocation RParen) {
20036   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20037     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20038       return Spec.getPlatform() == Platform;
20039     });
20040     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20041     // for "maccatalyst" if "maccatalyst" is not specified.
20042     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20043       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20044         return Spec.getPlatform() == "ios";
20045       });
20046     }
20047     if (Spec == AvailSpecs.end())
20048       return None;
20049     return Spec->getVersion();
20050   };
20051 
20052   VersionTuple Version;
20053   if (auto MaybeVersion =
20054           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20055     Version = *MaybeVersion;
20056 
20057   // The use of `@available` in the enclosing context should be analyzed to
20058   // warn when it's used inappropriately (i.e. not if(@available)).
20059   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20060     Context->HasPotentialAvailabilityViolations = true;
20061 
20062   return new (Context)
20063       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20064 }
20065 
20066 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20067                                     ArrayRef<Expr *> SubExprs, QualType T) {
20068   if (!Context.getLangOpts().RecoveryAST)
20069     return ExprError();
20070 
20071   if (isSFINAEContext())
20072     return ExprError();
20073 
20074   if (T.isNull() || T->isUndeducedType() ||
20075       !Context.getLangOpts().RecoveryASTType)
20076     // We don't know the concrete type, fallback to dependent type.
20077     T = Context.DependentTy;
20078 
20079   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20080 }
20081