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     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3926     // but we do not currently support the suffix in C++ mode because it's not
3927     // entirely clear whether WG21 will prefer this suffix to return a library
3928     // type such as std::bit_int instead of returning a _BitInt.
3929     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3930       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3931                                      ? diag::warn_c2x_compat_bitint_suffix
3932                                      : diag::ext_c2x_bitint_suffix);
3933 
3934     // Get the value in the widest-possible width. What is "widest" depends on
3935     // whether the literal is a bit-precise integer or not. For a bit-precise
3936     // integer type, try to scan the source to determine how many bits are
3937     // needed to represent the value. This may seem a bit expensive, but trying
3938     // to get the integer value from an overly-wide APInt is *extremely*
3939     // expensive, so the naive approach of assuming
3940     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3941     unsigned BitsNeeded =
3942         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3943                                Literal.getLiteralDigits(), Literal.getRadix())
3944                          : Context.getTargetInfo().getIntMaxTWidth();
3945     llvm::APInt ResultVal(BitsNeeded, 0);
3946 
3947     if (Literal.GetIntegerValue(ResultVal)) {
3948       // If this value didn't fit into uintmax_t, error and force to ull.
3949       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3950           << /* Unsigned */ 1;
3951       Ty = Context.UnsignedLongLongTy;
3952       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3953              "long long is not intmax_t?");
3954     } else {
3955       // If this value fits into a ULL, try to figure out what else it fits into
3956       // according to the rules of C99 6.4.4.1p5.
3957 
3958       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3959       // be an unsigned int.
3960       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3961 
3962       // Check from smallest to largest, picking the smallest type we can.
3963       unsigned Width = 0;
3964 
3965       // Microsoft specific integer suffixes are explicitly sized.
3966       if (Literal.MicrosoftInteger) {
3967         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3968           Width = 8;
3969           Ty = Context.CharTy;
3970         } else {
3971           Width = Literal.MicrosoftInteger;
3972           Ty = Context.getIntTypeForBitwidth(Width,
3973                                              /*Signed=*/!Literal.isUnsigned);
3974         }
3975       }
3976 
3977       // Bit-precise integer literals are automagically-sized based on the
3978       // width required by the literal.
3979       if (Literal.isBitInt) {
3980         // The signed version has one more bit for the sign value. There are no
3981         // zero-width bit-precise integers, even if the literal value is 0.
3982         Width = std::max(ResultVal.getActiveBits(), 1u) +
3983                 (Literal.isUnsigned ? 0u : 1u);
3984 
3985         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3986         // and reset the type to the largest supported width.
3987         unsigned int MaxBitIntWidth =
3988             Context.getTargetInfo().getMaxBitIntWidth();
3989         if (Width > MaxBitIntWidth) {
3990           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3991               << Literal.isUnsigned;
3992           Width = MaxBitIntWidth;
3993         }
3994 
3995         // Reset the result value to the smaller APInt and select the correct
3996         // type to be used. Note, we zext even for signed values because the
3997         // literal itself is always an unsigned value (a preceeding - is a
3998         // unary operator, not part of the literal).
3999         ResultVal = ResultVal.zextOrTrunc(Width);
4000         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4001       }
4002 
4003       // Check C++2b size_t literals.
4004       if (Literal.isSizeT) {
4005         assert(!Literal.MicrosoftInteger &&
4006                "size_t literals can't be Microsoft literals");
4007         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4008             Context.getTargetInfo().getSizeType());
4009 
4010         // Does it fit in size_t?
4011         if (ResultVal.isIntN(SizeTSize)) {
4012           // Does it fit in ssize_t?
4013           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4014             Ty = Context.getSignedSizeType();
4015           else if (AllowUnsigned)
4016             Ty = Context.getSizeType();
4017           Width = SizeTSize;
4018         }
4019       }
4020 
4021       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4022           !Literal.isSizeT) {
4023         // Are int/unsigned possibilities?
4024         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4025 
4026         // Does it fit in a unsigned int?
4027         if (ResultVal.isIntN(IntSize)) {
4028           // Does it fit in a signed int?
4029           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4030             Ty = Context.IntTy;
4031           else if (AllowUnsigned)
4032             Ty = Context.UnsignedIntTy;
4033           Width = IntSize;
4034         }
4035       }
4036 
4037       // Are long/unsigned long possibilities?
4038       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4039         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4040 
4041         // Does it fit in a unsigned long?
4042         if (ResultVal.isIntN(LongSize)) {
4043           // Does it fit in a signed long?
4044           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4045             Ty = Context.LongTy;
4046           else if (AllowUnsigned)
4047             Ty = Context.UnsignedLongTy;
4048           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4049           // is compatible.
4050           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4051             const unsigned LongLongSize =
4052                 Context.getTargetInfo().getLongLongWidth();
4053             Diag(Tok.getLocation(),
4054                  getLangOpts().CPlusPlus
4055                      ? Literal.isLong
4056                            ? diag::warn_old_implicitly_unsigned_long_cxx
4057                            : /*C++98 UB*/ diag::
4058                                  ext_old_implicitly_unsigned_long_cxx
4059                      : diag::warn_old_implicitly_unsigned_long)
4060                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4061                                             : /*will be ill-formed*/ 1);
4062             Ty = Context.UnsignedLongTy;
4063           }
4064           Width = LongSize;
4065         }
4066       }
4067 
4068       // Check long long if needed.
4069       if (Ty.isNull() && !Literal.isSizeT) {
4070         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4071 
4072         // Does it fit in a unsigned long long?
4073         if (ResultVal.isIntN(LongLongSize)) {
4074           // Does it fit in a signed long long?
4075           // To be compatible with MSVC, hex integer literals ending with the
4076           // LL or i64 suffix are always signed in Microsoft mode.
4077           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4078               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4079             Ty = Context.LongLongTy;
4080           else if (AllowUnsigned)
4081             Ty = Context.UnsignedLongLongTy;
4082           Width = LongLongSize;
4083         }
4084       }
4085 
4086       // If we still couldn't decide a type, we either have 'size_t' literal
4087       // that is out of range, or a decimal literal that does not fit in a
4088       // signed long long and has no U suffix.
4089       if (Ty.isNull()) {
4090         if (Literal.isSizeT)
4091           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4092               << Literal.isUnsigned;
4093         else
4094           Diag(Tok.getLocation(),
4095                diag::ext_integer_literal_too_large_for_signed);
4096         Ty = Context.UnsignedLongLongTy;
4097         Width = Context.getTargetInfo().getLongLongWidth();
4098       }
4099 
4100       if (ResultVal.getBitWidth() != Width)
4101         ResultVal = ResultVal.trunc(Width);
4102     }
4103     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4104   }
4105 
4106   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4107   if (Literal.isImaginary) {
4108     Res = new (Context) ImaginaryLiteral(Res,
4109                                         Context.getComplexType(Res->getType()));
4110 
4111     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4112   }
4113   return Res;
4114 }
4115 
4116 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4117   assert(E && "ActOnParenExpr() missing expr");
4118   QualType ExprTy = E->getType();
4119   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4120       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4121     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4122   return new (Context) ParenExpr(L, R, E);
4123 }
4124 
4125 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4126                                          SourceLocation Loc,
4127                                          SourceRange ArgRange) {
4128   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4129   // scalar or vector data type argument..."
4130   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4131   // type (C99 6.2.5p18) or void.
4132   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4133     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4134       << T << ArgRange;
4135     return true;
4136   }
4137 
4138   assert((T->isVoidType() || !T->isIncompleteType()) &&
4139          "Scalar types should always be complete");
4140   return false;
4141 }
4142 
4143 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4144                                            SourceLocation Loc,
4145                                            SourceRange ArgRange,
4146                                            UnaryExprOrTypeTrait TraitKind) {
4147   // Invalid types must be hard errors for SFINAE in C++.
4148   if (S.LangOpts.CPlusPlus)
4149     return true;
4150 
4151   // C99 6.5.3.4p1:
4152   if (T->isFunctionType() &&
4153       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4154        TraitKind == UETT_PreferredAlignOf)) {
4155     // sizeof(function)/alignof(function) is allowed as an extension.
4156     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4157         << getTraitSpelling(TraitKind) << ArgRange;
4158     return false;
4159   }
4160 
4161   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4162   // this is an error (OpenCL v1.1 s6.3.k)
4163   if (T->isVoidType()) {
4164     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4165                                         : diag::ext_sizeof_alignof_void_type;
4166     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4167     return false;
4168   }
4169 
4170   return true;
4171 }
4172 
4173 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4174                                              SourceLocation Loc,
4175                                              SourceRange ArgRange,
4176                                              UnaryExprOrTypeTrait TraitKind) {
4177   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4178   // runtime doesn't allow it.
4179   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4180     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4181       << T << (TraitKind == UETT_SizeOf)
4182       << ArgRange;
4183     return true;
4184   }
4185 
4186   return false;
4187 }
4188 
4189 /// Check whether E is a pointer from a decayed array type (the decayed
4190 /// pointer type is equal to T) and emit a warning if it is.
4191 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4192                                      Expr *E) {
4193   // Don't warn if the operation changed the type.
4194   if (T != E->getType())
4195     return;
4196 
4197   // Now look for array decays.
4198   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4199   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4200     return;
4201 
4202   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4203                                              << ICE->getType()
4204                                              << ICE->getSubExpr()->getType();
4205 }
4206 
4207 /// Check the constraints on expression operands to unary type expression
4208 /// and type traits.
4209 ///
4210 /// Completes any types necessary and validates the constraints on the operand
4211 /// expression. The logic mostly mirrors the type-based overload, but may modify
4212 /// the expression as it completes the type for that expression through template
4213 /// instantiation, etc.
4214 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4215                                             UnaryExprOrTypeTrait ExprKind) {
4216   QualType ExprTy = E->getType();
4217   assert(!ExprTy->isReferenceType());
4218 
4219   bool IsUnevaluatedOperand =
4220       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4221        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4222   if (IsUnevaluatedOperand) {
4223     ExprResult Result = CheckUnevaluatedOperand(E);
4224     if (Result.isInvalid())
4225       return true;
4226     E = Result.get();
4227   }
4228 
4229   // The operand for sizeof and alignof is in an unevaluated expression context,
4230   // so side effects could result in unintended consequences.
4231   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4232   // used to build SFINAE gadgets.
4233   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4234   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4235       !E->isInstantiationDependent() &&
4236       E->HasSideEffects(Context, false))
4237     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4238 
4239   if (ExprKind == UETT_VecStep)
4240     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4241                                         E->getSourceRange());
4242 
4243   // Explicitly list some types as extensions.
4244   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4245                                       E->getSourceRange(), ExprKind))
4246     return false;
4247 
4248   // 'alignof' applied to an expression only requires the base element type of
4249   // the expression to be complete. 'sizeof' requires the expression's type to
4250   // be complete (and will attempt to complete it if it's an array of unknown
4251   // bound).
4252   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4253     if (RequireCompleteSizedType(
4254             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4255             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4256             getTraitSpelling(ExprKind), E->getSourceRange()))
4257       return true;
4258   } else {
4259     if (RequireCompleteSizedExprType(
4260             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4261             getTraitSpelling(ExprKind), E->getSourceRange()))
4262       return true;
4263   }
4264 
4265   // Completing the expression's type may have changed it.
4266   ExprTy = E->getType();
4267   assert(!ExprTy->isReferenceType());
4268 
4269   if (ExprTy->isFunctionType()) {
4270     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4271         << getTraitSpelling(ExprKind) << E->getSourceRange();
4272     return true;
4273   }
4274 
4275   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4276                                        E->getSourceRange(), ExprKind))
4277     return true;
4278 
4279   if (ExprKind == UETT_SizeOf) {
4280     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4281       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4282         QualType OType = PVD->getOriginalType();
4283         QualType Type = PVD->getType();
4284         if (Type->isPointerType() && OType->isArrayType()) {
4285           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4286             << Type << OType;
4287           Diag(PVD->getLocation(), diag::note_declared_at);
4288         }
4289       }
4290     }
4291 
4292     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4293     // decays into a pointer and returns an unintended result. This is most
4294     // likely a typo for "sizeof(array) op x".
4295     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4296       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4297                                BO->getLHS());
4298       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4299                                BO->getRHS());
4300     }
4301   }
4302 
4303   return false;
4304 }
4305 
4306 /// Check the constraints on operands to unary expression and type
4307 /// traits.
4308 ///
4309 /// This will complete any types necessary, and validate the various constraints
4310 /// on those operands.
4311 ///
4312 /// The UsualUnaryConversions() function is *not* called by this routine.
4313 /// C99 6.3.2.1p[2-4] all state:
4314 ///   Except when it is the operand of the sizeof operator ...
4315 ///
4316 /// C++ [expr.sizeof]p4
4317 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4318 ///   standard conversions are not applied to the operand of sizeof.
4319 ///
4320 /// This policy is followed for all of the unary trait expressions.
4321 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4322                                             SourceLocation OpLoc,
4323                                             SourceRange ExprRange,
4324                                             UnaryExprOrTypeTrait ExprKind) {
4325   if (ExprType->isDependentType())
4326     return false;
4327 
4328   // C++ [expr.sizeof]p2:
4329   //     When applied to a reference or a reference type, the result
4330   //     is the size of the referenced type.
4331   // C++11 [expr.alignof]p3:
4332   //     When alignof is applied to a reference type, the result
4333   //     shall be the alignment of the referenced type.
4334   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4335     ExprType = Ref->getPointeeType();
4336 
4337   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4338   //   When alignof or _Alignof is applied to an array type, the result
4339   //   is the alignment of the element type.
4340   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4341       ExprKind == UETT_OpenMPRequiredSimdAlign)
4342     ExprType = Context.getBaseElementType(ExprType);
4343 
4344   if (ExprKind == UETT_VecStep)
4345     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4346 
4347   // Explicitly list some types as extensions.
4348   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4349                                       ExprKind))
4350     return false;
4351 
4352   if (RequireCompleteSizedType(
4353           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4354           getTraitSpelling(ExprKind), ExprRange))
4355     return true;
4356 
4357   if (ExprType->isFunctionType()) {
4358     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4359         << getTraitSpelling(ExprKind) << ExprRange;
4360     return true;
4361   }
4362 
4363   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4364                                        ExprKind))
4365     return true;
4366 
4367   return false;
4368 }
4369 
4370 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4371   // Cannot know anything else if the expression is dependent.
4372   if (E->isTypeDependent())
4373     return false;
4374 
4375   if (E->getObjectKind() == OK_BitField) {
4376     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4377        << 1 << E->getSourceRange();
4378     return true;
4379   }
4380 
4381   ValueDecl *D = nullptr;
4382   Expr *Inner = E->IgnoreParens();
4383   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4384     D = DRE->getDecl();
4385   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4386     D = ME->getMemberDecl();
4387   }
4388 
4389   // If it's a field, require the containing struct to have a
4390   // complete definition so that we can compute the layout.
4391   //
4392   // This can happen in C++11 onwards, either by naming the member
4393   // in a way that is not transformed into a member access expression
4394   // (in an unevaluated operand, for instance), or by naming the member
4395   // in a trailing-return-type.
4396   //
4397   // For the record, since __alignof__ on expressions is a GCC
4398   // extension, GCC seems to permit this but always gives the
4399   // nonsensical answer 0.
4400   //
4401   // We don't really need the layout here --- we could instead just
4402   // directly check for all the appropriate alignment-lowing
4403   // attributes --- but that would require duplicating a lot of
4404   // logic that just isn't worth duplicating for such a marginal
4405   // use-case.
4406   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4407     // Fast path this check, since we at least know the record has a
4408     // definition if we can find a member of it.
4409     if (!FD->getParent()->isCompleteDefinition()) {
4410       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4411         << E->getSourceRange();
4412       return true;
4413     }
4414 
4415     // Otherwise, if it's a field, and the field doesn't have
4416     // reference type, then it must have a complete type (or be a
4417     // flexible array member, which we explicitly want to
4418     // white-list anyway), which makes the following checks trivial.
4419     if (!FD->getType()->isReferenceType())
4420       return false;
4421   }
4422 
4423   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4424 }
4425 
4426 bool Sema::CheckVecStepExpr(Expr *E) {
4427   E = E->IgnoreParens();
4428 
4429   // Cannot know anything else if the expression is dependent.
4430   if (E->isTypeDependent())
4431     return false;
4432 
4433   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4434 }
4435 
4436 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4437                                         CapturingScopeInfo *CSI) {
4438   assert(T->isVariablyModifiedType());
4439   assert(CSI != nullptr);
4440 
4441   // We're going to walk down into the type and look for VLA expressions.
4442   do {
4443     const Type *Ty = T.getTypePtr();
4444     switch (Ty->getTypeClass()) {
4445 #define TYPE(Class, Base)
4446 #define ABSTRACT_TYPE(Class, Base)
4447 #define NON_CANONICAL_TYPE(Class, Base)
4448 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4449 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4450 #include "clang/AST/TypeNodes.inc"
4451       T = QualType();
4452       break;
4453     // These types are never variably-modified.
4454     case Type::Builtin:
4455     case Type::Complex:
4456     case Type::Vector:
4457     case Type::ExtVector:
4458     case Type::ConstantMatrix:
4459     case Type::Record:
4460     case Type::Enum:
4461     case Type::Elaborated:
4462     case Type::TemplateSpecialization:
4463     case Type::ObjCObject:
4464     case Type::ObjCInterface:
4465     case Type::ObjCObjectPointer:
4466     case Type::ObjCTypeParam:
4467     case Type::Pipe:
4468     case Type::BitInt:
4469       llvm_unreachable("type class is never variably-modified!");
4470     case Type::Adjusted:
4471       T = cast<AdjustedType>(Ty)->getOriginalType();
4472       break;
4473     case Type::Decayed:
4474       T = cast<DecayedType>(Ty)->getPointeeType();
4475       break;
4476     case Type::Pointer:
4477       T = cast<PointerType>(Ty)->getPointeeType();
4478       break;
4479     case Type::BlockPointer:
4480       T = cast<BlockPointerType>(Ty)->getPointeeType();
4481       break;
4482     case Type::LValueReference:
4483     case Type::RValueReference:
4484       T = cast<ReferenceType>(Ty)->getPointeeType();
4485       break;
4486     case Type::MemberPointer:
4487       T = cast<MemberPointerType>(Ty)->getPointeeType();
4488       break;
4489     case Type::ConstantArray:
4490     case Type::IncompleteArray:
4491       // Losing element qualification here is fine.
4492       T = cast<ArrayType>(Ty)->getElementType();
4493       break;
4494     case Type::VariableArray: {
4495       // Losing element qualification here is fine.
4496       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4497 
4498       // Unknown size indication requires no size computation.
4499       // Otherwise, evaluate and record it.
4500       auto Size = VAT->getSizeExpr();
4501       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4502           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4503         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4504 
4505       T = VAT->getElementType();
4506       break;
4507     }
4508     case Type::FunctionProto:
4509     case Type::FunctionNoProto:
4510       T = cast<FunctionType>(Ty)->getReturnType();
4511       break;
4512     case Type::Paren:
4513     case Type::TypeOf:
4514     case Type::UnaryTransform:
4515     case Type::Attributed:
4516     case Type::BTFTagAttributed:
4517     case Type::SubstTemplateTypeParm:
4518     case Type::MacroQualified:
4519       // Keep walking after single level desugaring.
4520       T = T.getSingleStepDesugaredType(Context);
4521       break;
4522     case Type::Typedef:
4523       T = cast<TypedefType>(Ty)->desugar();
4524       break;
4525     case Type::Decltype:
4526       T = cast<DecltypeType>(Ty)->desugar();
4527       break;
4528     case Type::Using:
4529       T = cast<UsingType>(Ty)->desugar();
4530       break;
4531     case Type::Auto:
4532     case Type::DeducedTemplateSpecialization:
4533       T = cast<DeducedType>(Ty)->getDeducedType();
4534       break;
4535     case Type::TypeOfExpr:
4536       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4537       break;
4538     case Type::Atomic:
4539       T = cast<AtomicType>(Ty)->getValueType();
4540       break;
4541     }
4542   } while (!T.isNull() && T->isVariablyModifiedType());
4543 }
4544 
4545 /// Build a sizeof or alignof expression given a type operand.
4546 ExprResult
4547 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4548                                      SourceLocation OpLoc,
4549                                      UnaryExprOrTypeTrait ExprKind,
4550                                      SourceRange R) {
4551   if (!TInfo)
4552     return ExprError();
4553 
4554   QualType T = TInfo->getType();
4555 
4556   if (!T->isDependentType() &&
4557       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4558     return ExprError();
4559 
4560   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4561     if (auto *TT = T->getAs<TypedefType>()) {
4562       for (auto I = FunctionScopes.rbegin(),
4563                 E = std::prev(FunctionScopes.rend());
4564            I != E; ++I) {
4565         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4566         if (CSI == nullptr)
4567           break;
4568         DeclContext *DC = nullptr;
4569         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4570           DC = LSI->CallOperator;
4571         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4572           DC = CRSI->TheCapturedDecl;
4573         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4574           DC = BSI->TheDecl;
4575         if (DC) {
4576           if (DC->containsDecl(TT->getDecl()))
4577             break;
4578           captureVariablyModifiedType(Context, T, CSI);
4579         }
4580       }
4581     }
4582   }
4583 
4584   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4585   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4586       TInfo->getType()->isVariablyModifiedType())
4587     TInfo = TransformToPotentiallyEvaluated(TInfo);
4588 
4589   return new (Context) UnaryExprOrTypeTraitExpr(
4590       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4591 }
4592 
4593 /// Build a sizeof or alignof expression given an expression
4594 /// operand.
4595 ExprResult
4596 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4597                                      UnaryExprOrTypeTrait ExprKind) {
4598   ExprResult PE = CheckPlaceholderExpr(E);
4599   if (PE.isInvalid())
4600     return ExprError();
4601 
4602   E = PE.get();
4603 
4604   // Verify that the operand is valid.
4605   bool isInvalid = false;
4606   if (E->isTypeDependent()) {
4607     // Delay type-checking for type-dependent expressions.
4608   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4609     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4610   } else if (ExprKind == UETT_VecStep) {
4611     isInvalid = CheckVecStepExpr(E);
4612   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4613       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4614       isInvalid = true;
4615   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4616     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4617     isInvalid = true;
4618   } else {
4619     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4620   }
4621 
4622   if (isInvalid)
4623     return ExprError();
4624 
4625   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4626     PE = TransformToPotentiallyEvaluated(E);
4627     if (PE.isInvalid()) return ExprError();
4628     E = PE.get();
4629   }
4630 
4631   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4632   return new (Context) UnaryExprOrTypeTraitExpr(
4633       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4634 }
4635 
4636 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4637 /// expr and the same for @c alignof and @c __alignof
4638 /// Note that the ArgRange is invalid if isType is false.
4639 ExprResult
4640 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4641                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4642                                     void *TyOrEx, SourceRange ArgRange) {
4643   // If error parsing type, ignore.
4644   if (!TyOrEx) return ExprError();
4645 
4646   if (IsType) {
4647     TypeSourceInfo *TInfo;
4648     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4649     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4650   }
4651 
4652   Expr *ArgEx = (Expr *)TyOrEx;
4653   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4654   return Result;
4655 }
4656 
4657 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4658                                      bool IsReal) {
4659   if (V.get()->isTypeDependent())
4660     return S.Context.DependentTy;
4661 
4662   // _Real and _Imag are only l-values for normal l-values.
4663   if (V.get()->getObjectKind() != OK_Ordinary) {
4664     V = S.DefaultLvalueConversion(V.get());
4665     if (V.isInvalid())
4666       return QualType();
4667   }
4668 
4669   // These operators return the element type of a complex type.
4670   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4671     return CT->getElementType();
4672 
4673   // Otherwise they pass through real integer and floating point types here.
4674   if (V.get()->getType()->isArithmeticType())
4675     return V.get()->getType();
4676 
4677   // Test for placeholders.
4678   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4679   if (PR.isInvalid()) return QualType();
4680   if (PR.get() != V.get()) {
4681     V = PR;
4682     return CheckRealImagOperand(S, V, Loc, IsReal);
4683   }
4684 
4685   // Reject anything else.
4686   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4687     << (IsReal ? "__real" : "__imag");
4688   return QualType();
4689 }
4690 
4691 
4692 
4693 ExprResult
4694 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4695                           tok::TokenKind Kind, Expr *Input) {
4696   UnaryOperatorKind Opc;
4697   switch (Kind) {
4698   default: llvm_unreachable("Unknown unary op!");
4699   case tok::plusplus:   Opc = UO_PostInc; break;
4700   case tok::minusminus: Opc = UO_PostDec; break;
4701   }
4702 
4703   // Since this might is a postfix expression, get rid of ParenListExprs.
4704   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4705   if (Result.isInvalid()) return ExprError();
4706   Input = Result.get();
4707 
4708   return BuildUnaryOp(S, OpLoc, Opc, Input);
4709 }
4710 
4711 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4712 ///
4713 /// \return true on error
4714 static bool checkArithmeticOnObjCPointer(Sema &S,
4715                                          SourceLocation opLoc,
4716                                          Expr *op) {
4717   assert(op->getType()->isObjCObjectPointerType());
4718   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4719       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4720     return false;
4721 
4722   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4723     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4724     << op->getSourceRange();
4725   return true;
4726 }
4727 
4728 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4729   auto *BaseNoParens = Base->IgnoreParens();
4730   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4731     return MSProp->getPropertyDecl()->getType()->isArrayType();
4732   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4733 }
4734 
4735 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4736 // Typically this is DependentTy, but can sometimes be more precise.
4737 //
4738 // There are cases when we could determine a non-dependent type:
4739 //  - LHS and RHS may have non-dependent types despite being type-dependent
4740 //    (e.g. unbounded array static members of the current instantiation)
4741 //  - one may be a dependent-sized array with known element type
4742 //  - one may be a dependent-typed valid index (enum in current instantiation)
4743 //
4744 // We *always* return a dependent type, in such cases it is DependentTy.
4745 // This avoids creating type-dependent expressions with non-dependent types.
4746 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4747 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4748                                                const ASTContext &Ctx) {
4749   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4750   QualType LTy = LHS->getType(), RTy = RHS->getType();
4751   QualType Result = Ctx.DependentTy;
4752   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4753     if (const PointerType *PT = LTy->getAs<PointerType>())
4754       Result = PT->getPointeeType();
4755     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4756       Result = AT->getElementType();
4757   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4758     if (const PointerType *PT = RTy->getAs<PointerType>())
4759       Result = PT->getPointeeType();
4760     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4761       Result = AT->getElementType();
4762   }
4763   // Ensure we return a dependent type.
4764   return Result->isDependentType() ? Result : Ctx.DependentTy;
4765 }
4766 
4767 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4768 
4769 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4770                                          SourceLocation lbLoc,
4771                                          MultiExprArg ArgExprs,
4772                                          SourceLocation rbLoc) {
4773 
4774   if (base && !base->getType().isNull() &&
4775       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4776     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4777                                     SourceLocation(), /*Length*/ nullptr,
4778                                     /*Stride=*/nullptr, rbLoc);
4779 
4780   // Since this might be a postfix expression, get rid of ParenListExprs.
4781   if (isa<ParenListExpr>(base)) {
4782     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4783     if (result.isInvalid())
4784       return ExprError();
4785     base = result.get();
4786   }
4787 
4788   // Check if base and idx form a MatrixSubscriptExpr.
4789   //
4790   // Helper to check for comma expressions, which are not allowed as indices for
4791   // matrix subscript expressions.
4792   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4793     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4794       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4795           << SourceRange(base->getBeginLoc(), rbLoc);
4796       return true;
4797     }
4798     return false;
4799   };
4800   // The matrix subscript operator ([][])is considered a single operator.
4801   // Separating the index expressions by parenthesis is not allowed.
4802   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4803       !isa<MatrixSubscriptExpr>(base)) {
4804     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4805         << SourceRange(base->getBeginLoc(), rbLoc);
4806     return ExprError();
4807   }
4808   // If the base is a MatrixSubscriptExpr, try to create a new
4809   // MatrixSubscriptExpr.
4810   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4811   if (matSubscriptE) {
4812     assert(ArgExprs.size() == 1);
4813     if (CheckAndReportCommaError(ArgExprs.front()))
4814       return ExprError();
4815 
4816     assert(matSubscriptE->isIncomplete() &&
4817            "base has to be an incomplete matrix subscript");
4818     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4819                                             matSubscriptE->getRowIdx(),
4820                                             ArgExprs.front(), rbLoc);
4821   }
4822 
4823   // Handle any non-overload placeholder types in the base and index
4824   // expressions.  We can't handle overloads here because the other
4825   // operand might be an overloadable type, in which case the overload
4826   // resolution for the operator overload should get the first crack
4827   // at the overload.
4828   bool IsMSPropertySubscript = false;
4829   if (base->getType()->isNonOverloadPlaceholderType()) {
4830     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4831     if (!IsMSPropertySubscript) {
4832       ExprResult result = CheckPlaceholderExpr(base);
4833       if (result.isInvalid())
4834         return ExprError();
4835       base = result.get();
4836     }
4837   }
4838 
4839   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4840   if (base->getType()->isMatrixType()) {
4841     assert(ArgExprs.size() == 1);
4842     if (CheckAndReportCommaError(ArgExprs.front()))
4843       return ExprError();
4844 
4845     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4846                                             rbLoc);
4847   }
4848 
4849   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4850     Expr *idx = ArgExprs[0];
4851     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4852         (isa<CXXOperatorCallExpr>(idx) &&
4853          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4854       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4855           << SourceRange(base->getBeginLoc(), rbLoc);
4856     }
4857   }
4858 
4859   if (ArgExprs.size() == 1 &&
4860       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4861     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4862     if (result.isInvalid())
4863       return ExprError();
4864     ArgExprs[0] = result.get();
4865   } else {
4866     if (checkArgsForPlaceholders(*this, ArgExprs))
4867       return ExprError();
4868   }
4869 
4870   // Build an unanalyzed expression if either operand is type-dependent.
4871   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4872       (base->isTypeDependent() ||
4873        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4874     return new (Context) ArraySubscriptExpr(
4875         base, ArgExprs.front(),
4876         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4877         VK_LValue, OK_Ordinary, rbLoc);
4878   }
4879 
4880   // MSDN, property (C++)
4881   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4882   // This attribute can also be used in the declaration of an empty array in a
4883   // class or structure definition. For example:
4884   // __declspec(property(get=GetX, put=PutX)) int x[];
4885   // The above statement indicates that x[] can be used with one or more array
4886   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4887   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4888   if (IsMSPropertySubscript) {
4889     assert(ArgExprs.size() == 1);
4890     // Build MS property subscript expression if base is MS property reference
4891     // or MS property subscript.
4892     return new (Context)
4893         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4894                                 VK_LValue, OK_Ordinary, rbLoc);
4895   }
4896 
4897   // Use C++ overloaded-operator rules if either operand has record
4898   // type.  The spec says to do this if either type is *overloadable*,
4899   // but enum types can't declare subscript operators or conversion
4900   // operators, so there's nothing interesting for overload resolution
4901   // to do if there aren't any record types involved.
4902   //
4903   // ObjC pointers have their own subscripting logic that is not tied
4904   // to overload resolution and so should not take this path.
4905   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4906       ((base->getType()->isRecordType() ||
4907         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4908     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4909   }
4910 
4911   ExprResult Res =
4912       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4913 
4914   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4915     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4916 
4917   return Res;
4918 }
4919 
4920 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4921   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4922   InitializationKind Kind =
4923       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4924   InitializationSequence InitSeq(*this, Entity, Kind, E);
4925   return InitSeq.Perform(*this, Entity, Kind, E);
4926 }
4927 
4928 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4929                                                   Expr *ColumnIdx,
4930                                                   SourceLocation RBLoc) {
4931   ExprResult BaseR = CheckPlaceholderExpr(Base);
4932   if (BaseR.isInvalid())
4933     return BaseR;
4934   Base = BaseR.get();
4935 
4936   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4937   if (RowR.isInvalid())
4938     return RowR;
4939   RowIdx = RowR.get();
4940 
4941   if (!ColumnIdx)
4942     return new (Context) MatrixSubscriptExpr(
4943         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4944 
4945   // Build an unanalyzed expression if any of the operands is type-dependent.
4946   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4947       ColumnIdx->isTypeDependent())
4948     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4949                                              Context.DependentTy, RBLoc);
4950 
4951   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4952   if (ColumnR.isInvalid())
4953     return ColumnR;
4954   ColumnIdx = ColumnR.get();
4955 
4956   // Check that IndexExpr is an integer expression. If it is a constant
4957   // expression, check that it is less than Dim (= the number of elements in the
4958   // corresponding dimension).
4959   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4960                           bool IsColumnIdx) -> Expr * {
4961     if (!IndexExpr->getType()->isIntegerType() &&
4962         !IndexExpr->isTypeDependent()) {
4963       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4964           << IsColumnIdx;
4965       return nullptr;
4966     }
4967 
4968     if (Optional<llvm::APSInt> Idx =
4969             IndexExpr->getIntegerConstantExpr(Context)) {
4970       if ((*Idx < 0 || *Idx >= Dim)) {
4971         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4972             << IsColumnIdx << Dim;
4973         return nullptr;
4974       }
4975     }
4976 
4977     ExprResult ConvExpr =
4978         tryConvertExprToType(IndexExpr, Context.getSizeType());
4979     assert(!ConvExpr.isInvalid() &&
4980            "should be able to convert any integer type to size type");
4981     return ConvExpr.get();
4982   };
4983 
4984   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4985   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4986   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4987   if (!RowIdx || !ColumnIdx)
4988     return ExprError();
4989 
4990   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4991                                            MTy->getElementType(), RBLoc);
4992 }
4993 
4994 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4995   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4996   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4997 
4998   // For expressions like `&(*s).b`, the base is recorded and what should be
4999   // checked.
5000   const MemberExpr *Member = nullptr;
5001   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5002     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5003 
5004   LastRecord.PossibleDerefs.erase(StrippedExpr);
5005 }
5006 
5007 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5008   if (isUnevaluatedContext())
5009     return;
5010 
5011   QualType ResultTy = E->getType();
5012   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5013 
5014   // Bail if the element is an array since it is not memory access.
5015   if (isa<ArrayType>(ResultTy))
5016     return;
5017 
5018   if (ResultTy->hasAttr(attr::NoDeref)) {
5019     LastRecord.PossibleDerefs.insert(E);
5020     return;
5021   }
5022 
5023   // Check if the base type is a pointer to a member access of a struct
5024   // marked with noderef.
5025   const Expr *Base = E->getBase();
5026   QualType BaseTy = Base->getType();
5027   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5028     // Not a pointer access
5029     return;
5030 
5031   const MemberExpr *Member = nullptr;
5032   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5033          Member->isArrow())
5034     Base = Member->getBase();
5035 
5036   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5037     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5038       LastRecord.PossibleDerefs.insert(E);
5039   }
5040 }
5041 
5042 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5043                                           Expr *LowerBound,
5044                                           SourceLocation ColonLocFirst,
5045                                           SourceLocation ColonLocSecond,
5046                                           Expr *Length, Expr *Stride,
5047                                           SourceLocation RBLoc) {
5048   if (Base->hasPlaceholderType() &&
5049       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5050     ExprResult Result = CheckPlaceholderExpr(Base);
5051     if (Result.isInvalid())
5052       return ExprError();
5053     Base = Result.get();
5054   }
5055   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5056     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5057     if (Result.isInvalid())
5058       return ExprError();
5059     Result = DefaultLvalueConversion(Result.get());
5060     if (Result.isInvalid())
5061       return ExprError();
5062     LowerBound = Result.get();
5063   }
5064   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5065     ExprResult Result = CheckPlaceholderExpr(Length);
5066     if (Result.isInvalid())
5067       return ExprError();
5068     Result = DefaultLvalueConversion(Result.get());
5069     if (Result.isInvalid())
5070       return ExprError();
5071     Length = Result.get();
5072   }
5073   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5074     ExprResult Result = CheckPlaceholderExpr(Stride);
5075     if (Result.isInvalid())
5076       return ExprError();
5077     Result = DefaultLvalueConversion(Result.get());
5078     if (Result.isInvalid())
5079       return ExprError();
5080     Stride = Result.get();
5081   }
5082 
5083   // Build an unanalyzed expression if either operand is type-dependent.
5084   if (Base->isTypeDependent() ||
5085       (LowerBound &&
5086        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5087       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5088       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5089     return new (Context) OMPArraySectionExpr(
5090         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5091         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5092   }
5093 
5094   // Perform default conversions.
5095   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5096   QualType ResultTy;
5097   if (OriginalTy->isAnyPointerType()) {
5098     ResultTy = OriginalTy->getPointeeType();
5099   } else if (OriginalTy->isArrayType()) {
5100     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5101   } else {
5102     return ExprError(
5103         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5104         << Base->getSourceRange());
5105   }
5106   // C99 6.5.2.1p1
5107   if (LowerBound) {
5108     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5109                                                       LowerBound);
5110     if (Res.isInvalid())
5111       return ExprError(Diag(LowerBound->getExprLoc(),
5112                             diag::err_omp_typecheck_section_not_integer)
5113                        << 0 << LowerBound->getSourceRange());
5114     LowerBound = Res.get();
5115 
5116     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5117         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5118       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5119           << 0 << LowerBound->getSourceRange();
5120   }
5121   if (Length) {
5122     auto Res =
5123         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5124     if (Res.isInvalid())
5125       return ExprError(Diag(Length->getExprLoc(),
5126                             diag::err_omp_typecheck_section_not_integer)
5127                        << 1 << Length->getSourceRange());
5128     Length = Res.get();
5129 
5130     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5131         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5132       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5133           << 1 << Length->getSourceRange();
5134   }
5135   if (Stride) {
5136     ExprResult Res =
5137         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5138     if (Res.isInvalid())
5139       return ExprError(Diag(Stride->getExprLoc(),
5140                             diag::err_omp_typecheck_section_not_integer)
5141                        << 1 << Stride->getSourceRange());
5142     Stride = Res.get();
5143 
5144     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5145         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5146       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5147           << 1 << Stride->getSourceRange();
5148   }
5149 
5150   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5151   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5152   // type. Note that functions are not objects, and that (in C99 parlance)
5153   // incomplete types are not object types.
5154   if (ResultTy->isFunctionType()) {
5155     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5156         << ResultTy << Base->getSourceRange();
5157     return ExprError();
5158   }
5159 
5160   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5161                           diag::err_omp_section_incomplete_type, Base))
5162     return ExprError();
5163 
5164   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5165     Expr::EvalResult Result;
5166     if (LowerBound->EvaluateAsInt(Result, Context)) {
5167       // OpenMP 5.0, [2.1.5 Array Sections]
5168       // The array section must be a subset of the original array.
5169       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5170       if (LowerBoundValue.isNegative()) {
5171         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5172             << LowerBound->getSourceRange();
5173         return ExprError();
5174       }
5175     }
5176   }
5177 
5178   if (Length) {
5179     Expr::EvalResult Result;
5180     if (Length->EvaluateAsInt(Result, Context)) {
5181       // OpenMP 5.0, [2.1.5 Array Sections]
5182       // The length must evaluate to non-negative integers.
5183       llvm::APSInt LengthValue = Result.Val.getInt();
5184       if (LengthValue.isNegative()) {
5185         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5186             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5187             << Length->getSourceRange();
5188         return ExprError();
5189       }
5190     }
5191   } else if (ColonLocFirst.isValid() &&
5192              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5193                                       !OriginalTy->isVariableArrayType()))) {
5194     // OpenMP 5.0, [2.1.5 Array Sections]
5195     // When the size of the array dimension is not known, the length must be
5196     // specified explicitly.
5197     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5198         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5199     return ExprError();
5200   }
5201 
5202   if (Stride) {
5203     Expr::EvalResult Result;
5204     if (Stride->EvaluateAsInt(Result, Context)) {
5205       // OpenMP 5.0, [2.1.5 Array Sections]
5206       // The stride must evaluate to a positive integer.
5207       llvm::APSInt StrideValue = Result.Val.getInt();
5208       if (!StrideValue.isStrictlyPositive()) {
5209         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5210             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5211             << Stride->getSourceRange();
5212         return ExprError();
5213       }
5214     }
5215   }
5216 
5217   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5218     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5219     if (Result.isInvalid())
5220       return ExprError();
5221     Base = Result.get();
5222   }
5223   return new (Context) OMPArraySectionExpr(
5224       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5225       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5226 }
5227 
5228 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5229                                           SourceLocation RParenLoc,
5230                                           ArrayRef<Expr *> Dims,
5231                                           ArrayRef<SourceRange> Brackets) {
5232   if (Base->hasPlaceholderType()) {
5233     ExprResult Result = CheckPlaceholderExpr(Base);
5234     if (Result.isInvalid())
5235       return ExprError();
5236     Result = DefaultLvalueConversion(Result.get());
5237     if (Result.isInvalid())
5238       return ExprError();
5239     Base = Result.get();
5240   }
5241   QualType BaseTy = Base->getType();
5242   // Delay analysis of the types/expressions if instantiation/specialization is
5243   // required.
5244   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5245     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5246                                        LParenLoc, RParenLoc, Dims, Brackets);
5247   if (!BaseTy->isPointerType() ||
5248       (!Base->isTypeDependent() &&
5249        BaseTy->getPointeeType()->isIncompleteType()))
5250     return ExprError(Diag(Base->getExprLoc(),
5251                           diag::err_omp_non_pointer_type_array_shaping_base)
5252                      << Base->getSourceRange());
5253 
5254   SmallVector<Expr *, 4> NewDims;
5255   bool ErrorFound = false;
5256   for (Expr *Dim : Dims) {
5257     if (Dim->hasPlaceholderType()) {
5258       ExprResult Result = CheckPlaceholderExpr(Dim);
5259       if (Result.isInvalid()) {
5260         ErrorFound = true;
5261         continue;
5262       }
5263       Result = DefaultLvalueConversion(Result.get());
5264       if (Result.isInvalid()) {
5265         ErrorFound = true;
5266         continue;
5267       }
5268       Dim = Result.get();
5269     }
5270     if (!Dim->isTypeDependent()) {
5271       ExprResult Result =
5272           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5273       if (Result.isInvalid()) {
5274         ErrorFound = true;
5275         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5276             << Dim->getSourceRange();
5277         continue;
5278       }
5279       Dim = Result.get();
5280       Expr::EvalResult EvResult;
5281       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5282         // OpenMP 5.0, [2.1.4 Array Shaping]
5283         // Each si is an integral type expression that must evaluate to a
5284         // positive integer.
5285         llvm::APSInt Value = EvResult.Val.getInt();
5286         if (!Value.isStrictlyPositive()) {
5287           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5288               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5289               << Dim->getSourceRange();
5290           ErrorFound = true;
5291           continue;
5292         }
5293       }
5294     }
5295     NewDims.push_back(Dim);
5296   }
5297   if (ErrorFound)
5298     return ExprError();
5299   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5300                                      LParenLoc, RParenLoc, NewDims, Brackets);
5301 }
5302 
5303 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5304                                       SourceLocation LLoc, SourceLocation RLoc,
5305                                       ArrayRef<OMPIteratorData> Data) {
5306   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5307   bool IsCorrect = true;
5308   for (const OMPIteratorData &D : Data) {
5309     TypeSourceInfo *TInfo = nullptr;
5310     SourceLocation StartLoc;
5311     QualType DeclTy;
5312     if (!D.Type.getAsOpaquePtr()) {
5313       // OpenMP 5.0, 2.1.6 Iterators
5314       // In an iterator-specifier, if the iterator-type is not specified then
5315       // the type of that iterator is of int type.
5316       DeclTy = Context.IntTy;
5317       StartLoc = D.DeclIdentLoc;
5318     } else {
5319       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5320       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5321     }
5322 
5323     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5324                              DeclTy->containsUnexpandedParameterPack() ||
5325                              DeclTy->isInstantiationDependentType();
5326     if (!IsDeclTyDependent) {
5327       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5328         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5329         // The iterator-type must be an integral or pointer type.
5330         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5331             << DeclTy;
5332         IsCorrect = false;
5333         continue;
5334       }
5335       if (DeclTy.isConstant(Context)) {
5336         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5337         // The iterator-type must not be const qualified.
5338         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5339             << DeclTy;
5340         IsCorrect = false;
5341         continue;
5342       }
5343     }
5344 
5345     // Iterator declaration.
5346     assert(D.DeclIdent && "Identifier expected.");
5347     // Always try to create iterator declarator to avoid extra error messages
5348     // about unknown declarations use.
5349     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5350                                D.DeclIdent, DeclTy, TInfo, SC_None);
5351     VD->setImplicit();
5352     if (S) {
5353       // Check for conflicting previous declaration.
5354       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5355       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5356                             ForVisibleRedeclaration);
5357       Previous.suppressDiagnostics();
5358       LookupName(Previous, S);
5359 
5360       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5361                            /*AllowInlineNamespace=*/false);
5362       if (!Previous.empty()) {
5363         NamedDecl *Old = Previous.getRepresentativeDecl();
5364         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5365         Diag(Old->getLocation(), diag::note_previous_definition);
5366       } else {
5367         PushOnScopeChains(VD, S);
5368       }
5369     } else {
5370       CurContext->addDecl(VD);
5371     }
5372     Expr *Begin = D.Range.Begin;
5373     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5374       ExprResult BeginRes =
5375           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5376       Begin = BeginRes.get();
5377     }
5378     Expr *End = D.Range.End;
5379     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5380       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5381       End = EndRes.get();
5382     }
5383     Expr *Step = D.Range.Step;
5384     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5385       if (!Step->getType()->isIntegralType(Context)) {
5386         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5387             << Step << Step->getSourceRange();
5388         IsCorrect = false;
5389         continue;
5390       }
5391       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5392       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5393       // If the step expression of a range-specification equals zero, the
5394       // behavior is unspecified.
5395       if (Result && Result->isZero()) {
5396         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5397             << Step << Step->getSourceRange();
5398         IsCorrect = false;
5399         continue;
5400       }
5401     }
5402     if (!Begin || !End || !IsCorrect) {
5403       IsCorrect = false;
5404       continue;
5405     }
5406     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5407     IDElem.IteratorDecl = VD;
5408     IDElem.AssignmentLoc = D.AssignLoc;
5409     IDElem.Range.Begin = Begin;
5410     IDElem.Range.End = End;
5411     IDElem.Range.Step = Step;
5412     IDElem.ColonLoc = D.ColonLoc;
5413     IDElem.SecondColonLoc = D.SecColonLoc;
5414   }
5415   if (!IsCorrect) {
5416     // Invalidate all created iterator declarations if error is found.
5417     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5418       if (Decl *ID = D.IteratorDecl)
5419         ID->setInvalidDecl();
5420     }
5421     return ExprError();
5422   }
5423   SmallVector<OMPIteratorHelperData, 4> Helpers;
5424   if (!CurContext->isDependentContext()) {
5425     // Build number of ityeration for each iteration range.
5426     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5427     // ((Begini-Stepi-1-Endi) / -Stepi);
5428     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5429       // (Endi - Begini)
5430       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5431                                           D.Range.Begin);
5432       if(!Res.isUsable()) {
5433         IsCorrect = false;
5434         continue;
5435       }
5436       ExprResult St, St1;
5437       if (D.Range.Step) {
5438         St = D.Range.Step;
5439         // (Endi - Begini) + Stepi
5440         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5441         if (!Res.isUsable()) {
5442           IsCorrect = false;
5443           continue;
5444         }
5445         // (Endi - Begini) + Stepi - 1
5446         Res =
5447             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5448                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5449         if (!Res.isUsable()) {
5450           IsCorrect = false;
5451           continue;
5452         }
5453         // ((Endi - Begini) + Stepi - 1) / Stepi
5454         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5455         if (!Res.isUsable()) {
5456           IsCorrect = false;
5457           continue;
5458         }
5459         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5460         // (Begini - Endi)
5461         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5462                                              D.Range.Begin, D.Range.End);
5463         if (!Res1.isUsable()) {
5464           IsCorrect = false;
5465           continue;
5466         }
5467         // (Begini - Endi) - Stepi
5468         Res1 =
5469             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5470         if (!Res1.isUsable()) {
5471           IsCorrect = false;
5472           continue;
5473         }
5474         // (Begini - Endi) - Stepi - 1
5475         Res1 =
5476             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5477                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5478         if (!Res1.isUsable()) {
5479           IsCorrect = false;
5480           continue;
5481         }
5482         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5483         Res1 =
5484             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5485         if (!Res1.isUsable()) {
5486           IsCorrect = false;
5487           continue;
5488         }
5489         // Stepi > 0.
5490         ExprResult CmpRes =
5491             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5492                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5493         if (!CmpRes.isUsable()) {
5494           IsCorrect = false;
5495           continue;
5496         }
5497         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5498                                  Res.get(), Res1.get());
5499         if (!Res.isUsable()) {
5500           IsCorrect = false;
5501           continue;
5502         }
5503       }
5504       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5505       if (!Res.isUsable()) {
5506         IsCorrect = false;
5507         continue;
5508       }
5509 
5510       // Build counter update.
5511       // Build counter.
5512       auto *CounterVD =
5513           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5514                           D.IteratorDecl->getBeginLoc(), nullptr,
5515                           Res.get()->getType(), nullptr, SC_None);
5516       CounterVD->setImplicit();
5517       ExprResult RefRes =
5518           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5519                            D.IteratorDecl->getBeginLoc());
5520       // Build counter update.
5521       // I = Begini + counter * Stepi;
5522       ExprResult UpdateRes;
5523       if (D.Range.Step) {
5524         UpdateRes = CreateBuiltinBinOp(
5525             D.AssignmentLoc, BO_Mul,
5526             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5527       } else {
5528         UpdateRes = DefaultLvalueConversion(RefRes.get());
5529       }
5530       if (!UpdateRes.isUsable()) {
5531         IsCorrect = false;
5532         continue;
5533       }
5534       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5535                                      UpdateRes.get());
5536       if (!UpdateRes.isUsable()) {
5537         IsCorrect = false;
5538         continue;
5539       }
5540       ExprResult VDRes =
5541           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5542                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5543                            D.IteratorDecl->getBeginLoc());
5544       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5545                                      UpdateRes.get());
5546       if (!UpdateRes.isUsable()) {
5547         IsCorrect = false;
5548         continue;
5549       }
5550       UpdateRes =
5551           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5552       if (!UpdateRes.isUsable()) {
5553         IsCorrect = false;
5554         continue;
5555       }
5556       ExprResult CounterUpdateRes =
5557           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5558       if (!CounterUpdateRes.isUsable()) {
5559         IsCorrect = false;
5560         continue;
5561       }
5562       CounterUpdateRes =
5563           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5564       if (!CounterUpdateRes.isUsable()) {
5565         IsCorrect = false;
5566         continue;
5567       }
5568       OMPIteratorHelperData &HD = Helpers.emplace_back();
5569       HD.CounterVD = CounterVD;
5570       HD.Upper = Res.get();
5571       HD.Update = UpdateRes.get();
5572       HD.CounterUpdate = CounterUpdateRes.get();
5573     }
5574   } else {
5575     Helpers.assign(ID.size(), {});
5576   }
5577   if (!IsCorrect) {
5578     // Invalidate all created iterator declarations if error is found.
5579     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5580       if (Decl *ID = D.IteratorDecl)
5581         ID->setInvalidDecl();
5582     }
5583     return ExprError();
5584   }
5585   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5586                                  LLoc, RLoc, ID, Helpers);
5587 }
5588 
5589 ExprResult
5590 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5591                                       Expr *Idx, SourceLocation RLoc) {
5592   Expr *LHSExp = Base;
5593   Expr *RHSExp = Idx;
5594 
5595   ExprValueKind VK = VK_LValue;
5596   ExprObjectKind OK = OK_Ordinary;
5597 
5598   // Per C++ core issue 1213, the result is an xvalue if either operand is
5599   // a non-lvalue array, and an lvalue otherwise.
5600   if (getLangOpts().CPlusPlus11) {
5601     for (auto *Op : {LHSExp, RHSExp}) {
5602       Op = Op->IgnoreImplicit();
5603       if (Op->getType()->isArrayType() && !Op->isLValue())
5604         VK = VK_XValue;
5605     }
5606   }
5607 
5608   // Perform default conversions.
5609   if (!LHSExp->getType()->getAs<VectorType>()) {
5610     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5611     if (Result.isInvalid())
5612       return ExprError();
5613     LHSExp = Result.get();
5614   }
5615   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5616   if (Result.isInvalid())
5617     return ExprError();
5618   RHSExp = Result.get();
5619 
5620   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5621 
5622   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5623   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5624   // in the subscript position. As a result, we need to derive the array base
5625   // and index from the expression types.
5626   Expr *BaseExpr, *IndexExpr;
5627   QualType ResultType;
5628   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5629     BaseExpr = LHSExp;
5630     IndexExpr = RHSExp;
5631     ResultType =
5632         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5633   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5634     BaseExpr = LHSExp;
5635     IndexExpr = RHSExp;
5636     ResultType = PTy->getPointeeType();
5637   } else if (const ObjCObjectPointerType *PTy =
5638                LHSTy->getAs<ObjCObjectPointerType>()) {
5639     BaseExpr = LHSExp;
5640     IndexExpr = RHSExp;
5641 
5642     // Use custom logic if this should be the pseudo-object subscript
5643     // expression.
5644     if (!LangOpts.isSubscriptPointerArithmetic())
5645       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5646                                           nullptr);
5647 
5648     ResultType = PTy->getPointeeType();
5649   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5650      // Handle the uncommon case of "123[Ptr]".
5651     BaseExpr = RHSExp;
5652     IndexExpr = LHSExp;
5653     ResultType = PTy->getPointeeType();
5654   } else if (const ObjCObjectPointerType *PTy =
5655                RHSTy->getAs<ObjCObjectPointerType>()) {
5656      // Handle the uncommon case of "123[Ptr]".
5657     BaseExpr = RHSExp;
5658     IndexExpr = LHSExp;
5659     ResultType = PTy->getPointeeType();
5660     if (!LangOpts.isSubscriptPointerArithmetic()) {
5661       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5662         << ResultType << BaseExpr->getSourceRange();
5663       return ExprError();
5664     }
5665   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5666     BaseExpr = LHSExp;    // vectors: V[123]
5667     IndexExpr = RHSExp;
5668     // We apply C++ DR1213 to vector subscripting too.
5669     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5670       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5671       if (Materialized.isInvalid())
5672         return ExprError();
5673       LHSExp = Materialized.get();
5674     }
5675     VK = LHSExp->getValueKind();
5676     if (VK != VK_PRValue)
5677       OK = OK_VectorComponent;
5678 
5679     ResultType = VTy->getElementType();
5680     QualType BaseType = BaseExpr->getType();
5681     Qualifiers BaseQuals = BaseType.getQualifiers();
5682     Qualifiers MemberQuals = ResultType.getQualifiers();
5683     Qualifiers Combined = BaseQuals + MemberQuals;
5684     if (Combined != MemberQuals)
5685       ResultType = Context.getQualifiedType(ResultType, Combined);
5686   } else if (LHSTy->isArrayType()) {
5687     // If we see an array that wasn't promoted by
5688     // DefaultFunctionArrayLvalueConversion, it must be an array that
5689     // wasn't promoted because of the C90 rule that doesn't
5690     // allow promoting non-lvalue arrays.  Warn, then
5691     // force the promotion here.
5692     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5693         << LHSExp->getSourceRange();
5694     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5695                                CK_ArrayToPointerDecay).get();
5696     LHSTy = LHSExp->getType();
5697 
5698     BaseExpr = LHSExp;
5699     IndexExpr = RHSExp;
5700     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5701   } else if (RHSTy->isArrayType()) {
5702     // Same as previous, except for 123[f().a] case
5703     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5704         << RHSExp->getSourceRange();
5705     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5706                                CK_ArrayToPointerDecay).get();
5707     RHSTy = RHSExp->getType();
5708 
5709     BaseExpr = RHSExp;
5710     IndexExpr = LHSExp;
5711     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5712   } else {
5713     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5714        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5715   }
5716   // C99 6.5.2.1p1
5717   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5718     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5719                      << IndexExpr->getSourceRange());
5720 
5721   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5722        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5723          && !IndexExpr->isTypeDependent())
5724     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5725 
5726   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5727   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5728   // type. Note that Functions are not objects, and that (in C99 parlance)
5729   // incomplete types are not object types.
5730   if (ResultType->isFunctionType()) {
5731     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5732         << ResultType << BaseExpr->getSourceRange();
5733     return ExprError();
5734   }
5735 
5736   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5737     // GNU extension: subscripting on pointer to void
5738     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5739       << BaseExpr->getSourceRange();
5740 
5741     // C forbids expressions of unqualified void type from being l-values.
5742     // See IsCForbiddenLValueType.
5743     if (!ResultType.hasQualifiers())
5744       VK = VK_PRValue;
5745   } else if (!ResultType->isDependentType() &&
5746              RequireCompleteSizedType(
5747                  LLoc, ResultType,
5748                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5749     return ExprError();
5750 
5751   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5752          !ResultType.isCForbiddenLValueType());
5753 
5754   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5755       FunctionScopes.size() > 1) {
5756     if (auto *TT =
5757             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5758       for (auto I = FunctionScopes.rbegin(),
5759                 E = std::prev(FunctionScopes.rend());
5760            I != E; ++I) {
5761         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5762         if (CSI == nullptr)
5763           break;
5764         DeclContext *DC = nullptr;
5765         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5766           DC = LSI->CallOperator;
5767         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5768           DC = CRSI->TheCapturedDecl;
5769         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5770           DC = BSI->TheDecl;
5771         if (DC) {
5772           if (DC->containsDecl(TT->getDecl()))
5773             break;
5774           captureVariablyModifiedType(
5775               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5776         }
5777       }
5778     }
5779   }
5780 
5781   return new (Context)
5782       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5783 }
5784 
5785 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5786                                   ParmVarDecl *Param) {
5787   if (Param->hasUnparsedDefaultArg()) {
5788     // If we've already cleared out the location for the default argument,
5789     // that means we're parsing it right now.
5790     if (!UnparsedDefaultArgLocs.count(Param)) {
5791       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5792       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5793       Param->setInvalidDecl();
5794       return true;
5795     }
5796 
5797     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5798         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5799     Diag(UnparsedDefaultArgLocs[Param],
5800          diag::note_default_argument_declared_here);
5801     return true;
5802   }
5803 
5804   if (Param->hasUninstantiatedDefaultArg() &&
5805       InstantiateDefaultArgument(CallLoc, FD, Param))
5806     return true;
5807 
5808   assert(Param->hasInit() && "default argument but no initializer?");
5809 
5810   // If the default expression creates temporaries, we need to
5811   // push them to the current stack of expression temporaries so they'll
5812   // be properly destroyed.
5813   // FIXME: We should really be rebuilding the default argument with new
5814   // bound temporaries; see the comment in PR5810.
5815   // We don't need to do that with block decls, though, because
5816   // blocks in default argument expression can never capture anything.
5817   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5818     // Set the "needs cleanups" bit regardless of whether there are
5819     // any explicit objects.
5820     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5821 
5822     // Append all the objects to the cleanup list.  Right now, this
5823     // should always be a no-op, because blocks in default argument
5824     // expressions should never be able to capture anything.
5825     assert(!Init->getNumObjects() &&
5826            "default argument expression has capturing blocks?");
5827   }
5828 
5829   // We already type-checked the argument, so we know it works.
5830   // Just mark all of the declarations in this potentially-evaluated expression
5831   // as being "referenced".
5832   EnterExpressionEvaluationContext EvalContext(
5833       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5834   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5835                                    /*SkipLocalVariables=*/true);
5836   return false;
5837 }
5838 
5839 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5840                                         FunctionDecl *FD, ParmVarDecl *Param) {
5841   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5842   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5843     return ExprError();
5844   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5845 }
5846 
5847 Sema::VariadicCallType
5848 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5849                           Expr *Fn) {
5850   if (Proto && Proto->isVariadic()) {
5851     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5852       return VariadicConstructor;
5853     else if (Fn && Fn->getType()->isBlockPointerType())
5854       return VariadicBlock;
5855     else if (FDecl) {
5856       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5857         if (Method->isInstance())
5858           return VariadicMethod;
5859     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5860       return VariadicMethod;
5861     return VariadicFunction;
5862   }
5863   return VariadicDoesNotApply;
5864 }
5865 
5866 namespace {
5867 class FunctionCallCCC final : public FunctionCallFilterCCC {
5868 public:
5869   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5870                   unsigned NumArgs, MemberExpr *ME)
5871       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5872         FunctionName(FuncName) {}
5873 
5874   bool ValidateCandidate(const TypoCorrection &candidate) override {
5875     if (!candidate.getCorrectionSpecifier() ||
5876         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5877       return false;
5878     }
5879 
5880     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5881   }
5882 
5883   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5884     return std::make_unique<FunctionCallCCC>(*this);
5885   }
5886 
5887 private:
5888   const IdentifierInfo *const FunctionName;
5889 };
5890 }
5891 
5892 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5893                                                FunctionDecl *FDecl,
5894                                                ArrayRef<Expr *> Args) {
5895   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5896   DeclarationName FuncName = FDecl->getDeclName();
5897   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5898 
5899   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5900   if (TypoCorrection Corrected = S.CorrectTypo(
5901           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5902           S.getScopeForContext(S.CurContext), nullptr, CCC,
5903           Sema::CTK_ErrorRecovery)) {
5904     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5905       if (Corrected.isOverloaded()) {
5906         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5907         OverloadCandidateSet::iterator Best;
5908         for (NamedDecl *CD : Corrected) {
5909           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5910             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5911                                    OCS);
5912         }
5913         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5914         case OR_Success:
5915           ND = Best->FoundDecl;
5916           Corrected.setCorrectionDecl(ND);
5917           break;
5918         default:
5919           break;
5920         }
5921       }
5922       ND = ND->getUnderlyingDecl();
5923       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5924         return Corrected;
5925     }
5926   }
5927   return TypoCorrection();
5928 }
5929 
5930 /// ConvertArgumentsForCall - Converts the arguments specified in
5931 /// Args/NumArgs to the parameter types of the function FDecl with
5932 /// function prototype Proto. Call is the call expression itself, and
5933 /// Fn is the function expression. For a C++ member function, this
5934 /// routine does not attempt to convert the object argument. Returns
5935 /// true if the call is ill-formed.
5936 bool
5937 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5938                               FunctionDecl *FDecl,
5939                               const FunctionProtoType *Proto,
5940                               ArrayRef<Expr *> Args,
5941                               SourceLocation RParenLoc,
5942                               bool IsExecConfig) {
5943   // Bail out early if calling a builtin with custom typechecking.
5944   if (FDecl)
5945     if (unsigned ID = FDecl->getBuiltinID())
5946       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5947         return false;
5948 
5949   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5950   // assignment, to the types of the corresponding parameter, ...
5951   unsigned NumParams = Proto->getNumParams();
5952   bool Invalid = false;
5953   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5954   unsigned FnKind = Fn->getType()->isBlockPointerType()
5955                        ? 1 /* block */
5956                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5957                                        : 0 /* function */);
5958 
5959   // If too few arguments are available (and we don't have default
5960   // arguments for the remaining parameters), don't make the call.
5961   if (Args.size() < NumParams) {
5962     if (Args.size() < MinArgs) {
5963       TypoCorrection TC;
5964       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5965         unsigned diag_id =
5966             MinArgs == NumParams && !Proto->isVariadic()
5967                 ? diag::err_typecheck_call_too_few_args_suggest
5968                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5969         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5970                                         << static_cast<unsigned>(Args.size())
5971                                         << TC.getCorrectionRange());
5972       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5973         Diag(RParenLoc,
5974              MinArgs == NumParams && !Proto->isVariadic()
5975                  ? diag::err_typecheck_call_too_few_args_one
5976                  : diag::err_typecheck_call_too_few_args_at_least_one)
5977             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5978       else
5979         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5980                             ? diag::err_typecheck_call_too_few_args
5981                             : diag::err_typecheck_call_too_few_args_at_least)
5982             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5983             << Fn->getSourceRange();
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       return true;
5990     }
5991     // We reserve space for the default arguments when we create
5992     // the call expression, before calling ConvertArgumentsForCall.
5993     assert((Call->getNumArgs() == NumParams) &&
5994            "We should have reserved space for the default arguments before!");
5995   }
5996 
5997   // If too many are passed and not variadic, error on the extras and drop
5998   // them.
5999   if (Args.size() > NumParams) {
6000     if (!Proto->isVariadic()) {
6001       TypoCorrection TC;
6002       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6003         unsigned diag_id =
6004             MinArgs == NumParams && !Proto->isVariadic()
6005                 ? diag::err_typecheck_call_too_many_args_suggest
6006                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6007         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6008                                         << static_cast<unsigned>(Args.size())
6009                                         << TC.getCorrectionRange());
6010       } else if (NumParams == 1 && FDecl &&
6011                  FDecl->getParamDecl(0)->getDeclName())
6012         Diag(Args[NumParams]->getBeginLoc(),
6013              MinArgs == NumParams
6014                  ? diag::err_typecheck_call_too_many_args_one
6015                  : diag::err_typecheck_call_too_many_args_at_most_one)
6016             << FnKind << FDecl->getParamDecl(0)
6017             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6018             << SourceRange(Args[NumParams]->getBeginLoc(),
6019                            Args.back()->getEndLoc());
6020       else
6021         Diag(Args[NumParams]->getBeginLoc(),
6022              MinArgs == NumParams
6023                  ? diag::err_typecheck_call_too_many_args
6024                  : diag::err_typecheck_call_too_many_args_at_most)
6025             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6026             << Fn->getSourceRange()
6027             << SourceRange(Args[NumParams]->getBeginLoc(),
6028                            Args.back()->getEndLoc());
6029 
6030       // Emit the location of the prototype.
6031       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6032         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6033 
6034       // This deletes the extra arguments.
6035       Call->shrinkNumArgs(NumParams);
6036       return true;
6037     }
6038   }
6039   SmallVector<Expr *, 8> AllArgs;
6040   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6041 
6042   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6043                                    AllArgs, CallType);
6044   if (Invalid)
6045     return true;
6046   unsigned TotalNumArgs = AllArgs.size();
6047   for (unsigned i = 0; i < TotalNumArgs; ++i)
6048     Call->setArg(i, AllArgs[i]);
6049 
6050   Call->computeDependence();
6051   return false;
6052 }
6053 
6054 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6055                                   const FunctionProtoType *Proto,
6056                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6057                                   SmallVectorImpl<Expr *> &AllArgs,
6058                                   VariadicCallType CallType, bool AllowExplicit,
6059                                   bool IsListInitialization) {
6060   unsigned NumParams = Proto->getNumParams();
6061   bool Invalid = false;
6062   size_t ArgIx = 0;
6063   // Continue to check argument types (even if we have too few/many args).
6064   for (unsigned i = FirstParam; i < NumParams; i++) {
6065     QualType ProtoArgType = Proto->getParamType(i);
6066 
6067     Expr *Arg;
6068     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6069     if (ArgIx < Args.size()) {
6070       Arg = Args[ArgIx++];
6071 
6072       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6073                               diag::err_call_incomplete_argument, Arg))
6074         return true;
6075 
6076       // Strip the unbridged-cast placeholder expression off, if applicable.
6077       bool CFAudited = false;
6078       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6079           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6080           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6081         Arg = stripARCUnbridgedCast(Arg);
6082       else if (getLangOpts().ObjCAutoRefCount &&
6083                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6084                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6085         CFAudited = true;
6086 
6087       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6088           ProtoArgType->isBlockPointerType())
6089         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6090           BE->getBlockDecl()->setDoesNotEscape();
6091 
6092       InitializedEntity Entity =
6093           Param ? InitializedEntity::InitializeParameter(Context, Param,
6094                                                          ProtoArgType)
6095                 : InitializedEntity::InitializeParameter(
6096                       Context, ProtoArgType, Proto->isParamConsumed(i));
6097 
6098       // Remember that parameter belongs to a CF audited API.
6099       if (CFAudited)
6100         Entity.setParameterCFAudited();
6101 
6102       ExprResult ArgE = PerformCopyInitialization(
6103           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6104       if (ArgE.isInvalid())
6105         return true;
6106 
6107       Arg = ArgE.getAs<Expr>();
6108     } else {
6109       assert(Param && "can't use default arguments without a known callee");
6110 
6111       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6112       if (ArgExpr.isInvalid())
6113         return true;
6114 
6115       Arg = ArgExpr.getAs<Expr>();
6116     }
6117 
6118     // Check for array bounds violations for each argument to the call. This
6119     // check only triggers warnings when the argument isn't a more complex Expr
6120     // with its own checking, such as a BinaryOperator.
6121     CheckArrayAccess(Arg);
6122 
6123     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6124     CheckStaticArrayArgument(CallLoc, Param, Arg);
6125 
6126     AllArgs.push_back(Arg);
6127   }
6128 
6129   // If this is a variadic call, handle args passed through "...".
6130   if (CallType != VariadicDoesNotApply) {
6131     // Assume that extern "C" functions with variadic arguments that
6132     // return __unknown_anytype aren't *really* variadic.
6133     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6134         FDecl->isExternC()) {
6135       for (Expr *A : Args.slice(ArgIx)) {
6136         QualType paramType; // ignored
6137         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6138         Invalid |= arg.isInvalid();
6139         AllArgs.push_back(arg.get());
6140       }
6141 
6142     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6143     } else {
6144       for (Expr *A : Args.slice(ArgIx)) {
6145         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6146         Invalid |= Arg.isInvalid();
6147         AllArgs.push_back(Arg.get());
6148       }
6149     }
6150 
6151     // Check for array bounds violations.
6152     for (Expr *A : Args.slice(ArgIx))
6153       CheckArrayAccess(A);
6154   }
6155   return Invalid;
6156 }
6157 
6158 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6159   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6160   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6161     TL = DTL.getOriginalLoc();
6162   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6163     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6164       << ATL.getLocalSourceRange();
6165 }
6166 
6167 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6168 /// array parameter, check that it is non-null, and that if it is formed by
6169 /// array-to-pointer decay, the underlying array is sufficiently large.
6170 ///
6171 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6172 /// array type derivation, then for each call to the function, the value of the
6173 /// corresponding actual argument shall provide access to the first element of
6174 /// an array with at least as many elements as specified by the size expression.
6175 void
6176 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6177                                ParmVarDecl *Param,
6178                                const Expr *ArgExpr) {
6179   // Static array parameters are not supported in C++.
6180   if (!Param || getLangOpts().CPlusPlus)
6181     return;
6182 
6183   QualType OrigTy = Param->getOriginalType();
6184 
6185   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6186   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6187     return;
6188 
6189   if (ArgExpr->isNullPointerConstant(Context,
6190                                      Expr::NPC_NeverValueDependent)) {
6191     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6192     DiagnoseCalleeStaticArrayParam(*this, Param);
6193     return;
6194   }
6195 
6196   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6197   if (!CAT)
6198     return;
6199 
6200   const ConstantArrayType *ArgCAT =
6201     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6202   if (!ArgCAT)
6203     return;
6204 
6205   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6206                                              ArgCAT->getElementType())) {
6207     if (ArgCAT->getSize().ult(CAT->getSize())) {
6208       Diag(CallLoc, diag::warn_static_array_too_small)
6209           << ArgExpr->getSourceRange()
6210           << (unsigned)ArgCAT->getSize().getZExtValue()
6211           << (unsigned)CAT->getSize().getZExtValue() << 0;
6212       DiagnoseCalleeStaticArrayParam(*this, Param);
6213     }
6214     return;
6215   }
6216 
6217   Optional<CharUnits> ArgSize =
6218       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6219   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6220   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6221     Diag(CallLoc, diag::warn_static_array_too_small)
6222         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6223         << (unsigned)ParmSize->getQuantity() << 1;
6224     DiagnoseCalleeStaticArrayParam(*this, Param);
6225   }
6226 }
6227 
6228 /// Given a function expression of unknown-any type, try to rebuild it
6229 /// to have a function type.
6230 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6231 
6232 /// Is the given type a placeholder that we need to lower out
6233 /// immediately during argument processing?
6234 static bool isPlaceholderToRemoveAsArg(QualType type) {
6235   // Placeholders are never sugared.
6236   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6237   if (!placeholder) return false;
6238 
6239   switch (placeholder->getKind()) {
6240   // Ignore all the non-placeholder types.
6241 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6242   case BuiltinType::Id:
6243 #include "clang/Basic/OpenCLImageTypes.def"
6244 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6245   case BuiltinType::Id:
6246 #include "clang/Basic/OpenCLExtensionTypes.def"
6247   // In practice we'll never use this, since all SVE types are sugared
6248   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6249 #define SVE_TYPE(Name, Id, SingletonId) \
6250   case BuiltinType::Id:
6251 #include "clang/Basic/AArch64SVEACLETypes.def"
6252 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6253   case BuiltinType::Id:
6254 #include "clang/Basic/PPCTypes.def"
6255 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6256 #include "clang/Basic/RISCVVTypes.def"
6257 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6258 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6259 #include "clang/AST/BuiltinTypes.def"
6260     return false;
6261 
6262   // We cannot lower out overload sets; they might validly be resolved
6263   // by the call machinery.
6264   case BuiltinType::Overload:
6265     return false;
6266 
6267   // Unbridged casts in ARC can be handled in some call positions and
6268   // should be left in place.
6269   case BuiltinType::ARCUnbridgedCast:
6270     return false;
6271 
6272   // Pseudo-objects should be converted as soon as possible.
6273   case BuiltinType::PseudoObject:
6274     return true;
6275 
6276   // The debugger mode could theoretically but currently does not try
6277   // to resolve unknown-typed arguments based on known parameter types.
6278   case BuiltinType::UnknownAny:
6279     return true;
6280 
6281   // These are always invalid as call arguments and should be reported.
6282   case BuiltinType::BoundMember:
6283   case BuiltinType::BuiltinFn:
6284   case BuiltinType::IncompleteMatrixIdx:
6285   case BuiltinType::OMPArraySection:
6286   case BuiltinType::OMPArrayShaping:
6287   case BuiltinType::OMPIterator:
6288     return true;
6289 
6290   }
6291   llvm_unreachable("bad builtin type kind");
6292 }
6293 
6294 /// Check an argument list for placeholders that we won't try to
6295 /// handle later.
6296 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6297   // Apply this processing to all the arguments at once instead of
6298   // dying at the first failure.
6299   bool hasInvalid = false;
6300   for (size_t i = 0, e = args.size(); i != e; i++) {
6301     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6302       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6303       if (result.isInvalid()) hasInvalid = true;
6304       else args[i] = result.get();
6305     }
6306   }
6307   return hasInvalid;
6308 }
6309 
6310 /// If a builtin function has a pointer argument with no explicit address
6311 /// space, then it should be able to accept a pointer to any address
6312 /// space as input.  In order to do this, we need to replace the
6313 /// standard builtin declaration with one that uses the same address space
6314 /// as the call.
6315 ///
6316 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6317 ///                  it does not contain any pointer arguments without
6318 ///                  an address space qualifer.  Otherwise the rewritten
6319 ///                  FunctionDecl is returned.
6320 /// TODO: Handle pointer return types.
6321 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6322                                                 FunctionDecl *FDecl,
6323                                                 MultiExprArg ArgExprs) {
6324 
6325   QualType DeclType = FDecl->getType();
6326   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6327 
6328   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6329       ArgExprs.size() < FT->getNumParams())
6330     return nullptr;
6331 
6332   bool NeedsNewDecl = false;
6333   unsigned i = 0;
6334   SmallVector<QualType, 8> OverloadParams;
6335 
6336   for (QualType ParamType : FT->param_types()) {
6337 
6338     // Convert array arguments to pointer to simplify type lookup.
6339     ExprResult ArgRes =
6340         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6341     if (ArgRes.isInvalid())
6342       return nullptr;
6343     Expr *Arg = ArgRes.get();
6344     QualType ArgType = Arg->getType();
6345     if (!ParamType->isPointerType() ||
6346         ParamType.hasAddressSpace() ||
6347         !ArgType->isPointerType() ||
6348         !ArgType->getPointeeType().hasAddressSpace()) {
6349       OverloadParams.push_back(ParamType);
6350       continue;
6351     }
6352 
6353     QualType PointeeType = ParamType->getPointeeType();
6354     if (PointeeType.hasAddressSpace())
6355       continue;
6356 
6357     NeedsNewDecl = true;
6358     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6359 
6360     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6361     OverloadParams.push_back(Context.getPointerType(PointeeType));
6362   }
6363 
6364   if (!NeedsNewDecl)
6365     return nullptr;
6366 
6367   FunctionProtoType::ExtProtoInfo EPI;
6368   EPI.Variadic = FT->isVariadic();
6369   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6370                                                 OverloadParams, EPI);
6371   DeclContext *Parent = FDecl->getParent();
6372   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6373       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6374       FDecl->getIdentifier(), OverloadTy,
6375       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6376       false,
6377       /*hasPrototype=*/true);
6378   SmallVector<ParmVarDecl*, 16> Params;
6379   FT = cast<FunctionProtoType>(OverloadTy);
6380   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6381     QualType ParamType = FT->getParamType(i);
6382     ParmVarDecl *Parm =
6383         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6384                                 SourceLocation(), nullptr, ParamType,
6385                                 /*TInfo=*/nullptr, SC_None, nullptr);
6386     Parm->setScopeInfo(0, i);
6387     Params.push_back(Parm);
6388   }
6389   OverloadDecl->setParams(Params);
6390   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6391   return OverloadDecl;
6392 }
6393 
6394 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6395                                     FunctionDecl *Callee,
6396                                     MultiExprArg ArgExprs) {
6397   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6398   // similar attributes) really don't like it when functions are called with an
6399   // invalid number of args.
6400   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6401                          /*PartialOverloading=*/false) &&
6402       !Callee->isVariadic())
6403     return;
6404   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6405     return;
6406 
6407   if (const EnableIfAttr *Attr =
6408           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6409     S.Diag(Fn->getBeginLoc(),
6410            isa<CXXMethodDecl>(Callee)
6411                ? diag::err_ovl_no_viable_member_function_in_call
6412                : diag::err_ovl_no_viable_function_in_call)
6413         << Callee << Callee->getSourceRange();
6414     S.Diag(Callee->getLocation(),
6415            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6416         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6417     return;
6418   }
6419 }
6420 
6421 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6422     const UnresolvedMemberExpr *const UME, Sema &S) {
6423 
6424   const auto GetFunctionLevelDCIfCXXClass =
6425       [](Sema &S) -> const CXXRecordDecl * {
6426     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6427     if (!DC || !DC->getParent())
6428       return nullptr;
6429 
6430     // If the call to some member function was made from within a member
6431     // function body 'M' return return 'M's parent.
6432     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6433       return MD->getParent()->getCanonicalDecl();
6434     // else the call was made from within a default member initializer of a
6435     // class, so return the class.
6436     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6437       return RD->getCanonicalDecl();
6438     return nullptr;
6439   };
6440   // If our DeclContext is neither a member function nor a class (in the
6441   // case of a lambda in a default member initializer), we can't have an
6442   // enclosing 'this'.
6443 
6444   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6445   if (!CurParentClass)
6446     return false;
6447 
6448   // The naming class for implicit member functions call is the class in which
6449   // name lookup starts.
6450   const CXXRecordDecl *const NamingClass =
6451       UME->getNamingClass()->getCanonicalDecl();
6452   assert(NamingClass && "Must have naming class even for implicit access");
6453 
6454   // If the unresolved member functions were found in a 'naming class' that is
6455   // related (either the same or derived from) to the class that contains the
6456   // member function that itself contained the implicit member access.
6457 
6458   return CurParentClass == NamingClass ||
6459          CurParentClass->isDerivedFrom(NamingClass);
6460 }
6461 
6462 static void
6463 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6464     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6465 
6466   if (!UME)
6467     return;
6468 
6469   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6470   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6471   // already been captured, or if this is an implicit member function call (if
6472   // it isn't, an attempt to capture 'this' should already have been made).
6473   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6474       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6475     return;
6476 
6477   // Check if the naming class in which the unresolved members were found is
6478   // related (same as or is a base of) to the enclosing class.
6479 
6480   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6481     return;
6482 
6483 
6484   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6485   // If the enclosing function is not dependent, then this lambda is
6486   // capture ready, so if we can capture this, do so.
6487   if (!EnclosingFunctionCtx->isDependentContext()) {
6488     // If the current lambda and all enclosing lambdas can capture 'this' -
6489     // then go ahead and capture 'this' (since our unresolved overload set
6490     // contains at least one non-static member function).
6491     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6492       S.CheckCXXThisCapture(CallLoc);
6493   } else if (S.CurContext->isDependentContext()) {
6494     // ... since this is an implicit member reference, that might potentially
6495     // involve a 'this' capture, mark 'this' for potential capture in
6496     // enclosing lambdas.
6497     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6498       CurLSI->addPotentialThisCapture(CallLoc);
6499   }
6500 }
6501 
6502 // Once a call is fully resolved, warn for unqualified calls to specific
6503 // C++ standard functions, like move and forward.
6504 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6505   // We are only checking unary move and forward so exit early here.
6506   if (Call->getNumArgs() != 1)
6507     return;
6508 
6509   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6510   if (!E || isa<UnresolvedLookupExpr>(E))
6511     return;
6512   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6513   if (!DRE || !DRE->getLocation().isValid())
6514     return;
6515 
6516   if (DRE->getQualifier())
6517     return;
6518 
6519   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6520   if (!D || !D->isInStdNamespace())
6521     return;
6522 
6523   // Only warn for some functions deemed more frequent or problematic.
6524   static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6525   auto it = llvm::find(SpecialFunctions, D->getName());
6526   if (it == std::end(SpecialFunctions))
6527     return;
6528 
6529   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6530       << D->getQualifiedNameAsString()
6531       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6532 }
6533 
6534 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6535                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6536                                Expr *ExecConfig) {
6537   ExprResult Call =
6538       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6539                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6540   if (Call.isInvalid())
6541     return Call;
6542 
6543   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6544   // language modes.
6545   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6546     if (ULE->hasExplicitTemplateArgs() &&
6547         ULE->decls_begin() == ULE->decls_end()) {
6548       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6549                                  ? diag::warn_cxx17_compat_adl_only_template_id
6550                                  : diag::ext_adl_only_template_id)
6551           << ULE->getName();
6552     }
6553   }
6554 
6555   if (LangOpts.OpenMP)
6556     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6557                            ExecConfig);
6558   if (LangOpts.CPlusPlus) {
6559     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6560     if (CE)
6561       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6562   }
6563   return Call;
6564 }
6565 
6566 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6567 /// This provides the location of the left/right parens and a list of comma
6568 /// locations.
6569 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6570                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6571                                Expr *ExecConfig, bool IsExecConfig,
6572                                bool AllowRecovery) {
6573   // Since this might be a postfix expression, get rid of ParenListExprs.
6574   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6575   if (Result.isInvalid()) return ExprError();
6576   Fn = Result.get();
6577 
6578   if (checkArgsForPlaceholders(*this, ArgExprs))
6579     return ExprError();
6580 
6581   if (getLangOpts().CPlusPlus) {
6582     // If this is a pseudo-destructor expression, build the call immediately.
6583     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6584       if (!ArgExprs.empty()) {
6585         // Pseudo-destructor calls should not have any arguments.
6586         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6587             << FixItHint::CreateRemoval(
6588                    SourceRange(ArgExprs.front()->getBeginLoc(),
6589                                ArgExprs.back()->getEndLoc()));
6590       }
6591 
6592       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6593                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6594     }
6595     if (Fn->getType() == Context.PseudoObjectTy) {
6596       ExprResult result = CheckPlaceholderExpr(Fn);
6597       if (result.isInvalid()) return ExprError();
6598       Fn = result.get();
6599     }
6600 
6601     // Determine whether this is a dependent call inside a C++ template,
6602     // in which case we won't do any semantic analysis now.
6603     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6604       if (ExecConfig) {
6605         return CUDAKernelCallExpr::Create(Context, Fn,
6606                                           cast<CallExpr>(ExecConfig), ArgExprs,
6607                                           Context.DependentTy, VK_PRValue,
6608                                           RParenLoc, CurFPFeatureOverrides());
6609       } else {
6610 
6611         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6612             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6613             Fn->getBeginLoc());
6614 
6615         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6616                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6617       }
6618     }
6619 
6620     // Determine whether this is a call to an object (C++ [over.call.object]).
6621     if (Fn->getType()->isRecordType())
6622       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6623                                           RParenLoc);
6624 
6625     if (Fn->getType() == Context.UnknownAnyTy) {
6626       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6627       if (result.isInvalid()) return ExprError();
6628       Fn = result.get();
6629     }
6630 
6631     if (Fn->getType() == Context.BoundMemberTy) {
6632       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6633                                        RParenLoc, ExecConfig, IsExecConfig,
6634                                        AllowRecovery);
6635     }
6636   }
6637 
6638   // Check for overloaded calls.  This can happen even in C due to extensions.
6639   if (Fn->getType() == Context.OverloadTy) {
6640     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6641 
6642     // We aren't supposed to apply this logic if there's an '&' involved.
6643     if (!find.HasFormOfMemberPointer) {
6644       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6645         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6646                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6647       OverloadExpr *ovl = find.Expression;
6648       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6649         return BuildOverloadedCallExpr(
6650             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6651             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6652       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6653                                        RParenLoc, ExecConfig, IsExecConfig,
6654                                        AllowRecovery);
6655     }
6656   }
6657 
6658   // If we're directly calling a function, get the appropriate declaration.
6659   if (Fn->getType() == Context.UnknownAnyTy) {
6660     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6661     if (result.isInvalid()) return ExprError();
6662     Fn = result.get();
6663   }
6664 
6665   Expr *NakedFn = Fn->IgnoreParens();
6666 
6667   bool CallingNDeclIndirectly = false;
6668   NamedDecl *NDecl = nullptr;
6669   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6670     if (UnOp->getOpcode() == UO_AddrOf) {
6671       CallingNDeclIndirectly = true;
6672       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6673     }
6674   }
6675 
6676   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6677     NDecl = DRE->getDecl();
6678 
6679     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6680     if (FDecl && FDecl->getBuiltinID()) {
6681       // Rewrite the function decl for this builtin by replacing parameters
6682       // with no explicit address space with the address space of the arguments
6683       // in ArgExprs.
6684       if ((FDecl =
6685                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6686         NDecl = FDecl;
6687         Fn = DeclRefExpr::Create(
6688             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6689             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6690             nullptr, DRE->isNonOdrUse());
6691       }
6692     }
6693   } else if (isa<MemberExpr>(NakedFn))
6694     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6695 
6696   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6697     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6698                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6699       return ExprError();
6700 
6701     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6702 
6703     // If this expression is a call to a builtin function in HIP device
6704     // compilation, allow a pointer-type argument to default address space to be
6705     // passed as a pointer-type parameter to a non-default address space.
6706     // If Arg is declared in the default address space and Param is declared
6707     // in a non-default address space, perform an implicit address space cast to
6708     // the parameter type.
6709     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6710         FD->getBuiltinID()) {
6711       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6712         ParmVarDecl *Param = FD->getParamDecl(Idx);
6713         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6714             !ArgExprs[Idx]->getType()->isPointerType())
6715           continue;
6716 
6717         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6718         auto ArgTy = ArgExprs[Idx]->getType();
6719         auto ArgPtTy = ArgTy->getPointeeType();
6720         auto ArgAS = ArgPtTy.getAddressSpace();
6721 
6722         // Add address space cast if target address spaces are different
6723         bool NeedImplicitASC =
6724           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6725           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6726                                               // or from specific AS which has target AS matching that of Param.
6727           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6728         if (!NeedImplicitASC)
6729           continue;
6730 
6731         // First, ensure that the Arg is an RValue.
6732         if (ArgExprs[Idx]->isGLValue()) {
6733           ArgExprs[Idx] = ImplicitCastExpr::Create(
6734               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6735               nullptr, VK_PRValue, FPOptionsOverride());
6736         }
6737 
6738         // Construct a new arg type with address space of Param
6739         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6740         ArgPtQuals.setAddressSpace(ParamAS);
6741         auto NewArgPtTy =
6742             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6743         auto NewArgTy =
6744             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6745                                      ArgTy.getQualifiers());
6746 
6747         // Finally perform an implicit address space cast
6748         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6749                                           CK_AddressSpaceConversion)
6750                             .get();
6751       }
6752     }
6753   }
6754 
6755   if (Context.isDependenceAllowed() &&
6756       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6757     assert(!getLangOpts().CPlusPlus);
6758     assert((Fn->containsErrors() ||
6759             llvm::any_of(ArgExprs,
6760                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6761            "should only occur in error-recovery path.");
6762     QualType ReturnType =
6763         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6764             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6765             : Context.DependentTy;
6766     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6767                             Expr::getValueKindForType(ReturnType), RParenLoc,
6768                             CurFPFeatureOverrides());
6769   }
6770   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6771                                ExecConfig, IsExecConfig);
6772 }
6773 
6774 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6775 //  with the specified CallArgs
6776 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6777                                  MultiExprArg CallArgs) {
6778   StringRef Name = Context.BuiltinInfo.getName(Id);
6779   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6780                  Sema::LookupOrdinaryName);
6781   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6782 
6783   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6784   assert(BuiltInDecl && "failed to find builtin declaration");
6785 
6786   ExprResult DeclRef =
6787       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6788   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6789 
6790   ExprResult Call =
6791       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6792 
6793   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6794   return Call.get();
6795 }
6796 
6797 /// Parse a __builtin_astype expression.
6798 ///
6799 /// __builtin_astype( value, dst type )
6800 ///
6801 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6802                                  SourceLocation BuiltinLoc,
6803                                  SourceLocation RParenLoc) {
6804   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6805   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6806 }
6807 
6808 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6809 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6810                                  SourceLocation BuiltinLoc,
6811                                  SourceLocation RParenLoc) {
6812   ExprValueKind VK = VK_PRValue;
6813   ExprObjectKind OK = OK_Ordinary;
6814   QualType SrcTy = E->getType();
6815   if (!SrcTy->isDependentType() &&
6816       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6817     return ExprError(
6818         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6819         << DestTy << SrcTy << E->getSourceRange());
6820   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6821 }
6822 
6823 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6824 /// provided arguments.
6825 ///
6826 /// __builtin_convertvector( value, dst type )
6827 ///
6828 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6829                                         SourceLocation BuiltinLoc,
6830                                         SourceLocation RParenLoc) {
6831   TypeSourceInfo *TInfo;
6832   GetTypeFromParser(ParsedDestTy, &TInfo);
6833   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6834 }
6835 
6836 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6837 /// i.e. an expression not of \p OverloadTy.  The expression should
6838 /// unary-convert to an expression of function-pointer or
6839 /// block-pointer type.
6840 ///
6841 /// \param NDecl the declaration being called, if available
6842 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6843                                        SourceLocation LParenLoc,
6844                                        ArrayRef<Expr *> Args,
6845                                        SourceLocation RParenLoc, Expr *Config,
6846                                        bool IsExecConfig, ADLCallKind UsesADL) {
6847   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6848   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6849 
6850   // Functions with 'interrupt' attribute cannot be called directly.
6851   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6852     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6853     return ExprError();
6854   }
6855 
6856   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6857   // so there's some risk when calling out to non-interrupt handler functions
6858   // that the callee might not preserve them. This is easy to diagnose here,
6859   // but can be very challenging to debug.
6860   // Likewise, X86 interrupt handlers may only call routines with attribute
6861   // no_caller_saved_registers since there is no efficient way to
6862   // save and restore the non-GPR state.
6863   if (auto *Caller = getCurFunctionDecl()) {
6864     if (Caller->hasAttr<ARMInterruptAttr>()) {
6865       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6866       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6867         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6868         if (FDecl)
6869           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6870       }
6871     }
6872     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6873         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6874       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6875       if (FDecl)
6876         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6877     }
6878   }
6879 
6880   // Promote the function operand.
6881   // We special-case function promotion here because we only allow promoting
6882   // builtin functions to function pointers in the callee of a call.
6883   ExprResult Result;
6884   QualType ResultTy;
6885   if (BuiltinID &&
6886       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6887     // Extract the return type from the (builtin) function pointer type.
6888     // FIXME Several builtins still have setType in
6889     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6890     // Builtins.def to ensure they are correct before removing setType calls.
6891     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6892     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6893     ResultTy = FDecl->getCallResultType();
6894   } else {
6895     Result = CallExprUnaryConversions(Fn);
6896     ResultTy = Context.BoolTy;
6897   }
6898   if (Result.isInvalid())
6899     return ExprError();
6900   Fn = Result.get();
6901 
6902   // Check for a valid function type, but only if it is not a builtin which
6903   // requires custom type checking. These will be handled by
6904   // CheckBuiltinFunctionCall below just after creation of the call expression.
6905   const FunctionType *FuncT = nullptr;
6906   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6907   retry:
6908     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6909       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6910       // have type pointer to function".
6911       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6912       if (!FuncT)
6913         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6914                          << Fn->getType() << Fn->getSourceRange());
6915     } else if (const BlockPointerType *BPT =
6916                    Fn->getType()->getAs<BlockPointerType>()) {
6917       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6918     } else {
6919       // Handle calls to expressions of unknown-any type.
6920       if (Fn->getType() == Context.UnknownAnyTy) {
6921         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6922         if (rewrite.isInvalid())
6923           return ExprError();
6924         Fn = rewrite.get();
6925         goto retry;
6926       }
6927 
6928       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6929                        << Fn->getType() << Fn->getSourceRange());
6930     }
6931   }
6932 
6933   // Get the number of parameters in the function prototype, if any.
6934   // We will allocate space for max(Args.size(), NumParams) arguments
6935   // in the call expression.
6936   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6937   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6938 
6939   CallExpr *TheCall;
6940   if (Config) {
6941     assert(UsesADL == ADLCallKind::NotADL &&
6942            "CUDAKernelCallExpr should not use ADL");
6943     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6944                                          Args, ResultTy, VK_PRValue, RParenLoc,
6945                                          CurFPFeatureOverrides(), NumParams);
6946   } else {
6947     TheCall =
6948         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6949                          CurFPFeatureOverrides(), NumParams, UsesADL);
6950   }
6951 
6952   if (!Context.isDependenceAllowed()) {
6953     // Forget about the nulled arguments since typo correction
6954     // do not handle them well.
6955     TheCall->shrinkNumArgs(Args.size());
6956     // C cannot always handle TypoExpr nodes in builtin calls and direct
6957     // function calls as their argument checking don't necessarily handle
6958     // dependent types properly, so make sure any TypoExprs have been
6959     // dealt with.
6960     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6961     if (!Result.isUsable()) return ExprError();
6962     CallExpr *TheOldCall = TheCall;
6963     TheCall = dyn_cast<CallExpr>(Result.get());
6964     bool CorrectedTypos = TheCall != TheOldCall;
6965     if (!TheCall) return Result;
6966     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6967 
6968     // A new call expression node was created if some typos were corrected.
6969     // However it may not have been constructed with enough storage. In this
6970     // case, rebuild the node with enough storage. The waste of space is
6971     // immaterial since this only happens when some typos were corrected.
6972     if (CorrectedTypos && Args.size() < NumParams) {
6973       if (Config)
6974         TheCall = CUDAKernelCallExpr::Create(
6975             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6976             RParenLoc, CurFPFeatureOverrides(), NumParams);
6977       else
6978         TheCall =
6979             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6980                              CurFPFeatureOverrides(), NumParams, UsesADL);
6981     }
6982     // We can now handle the nulled arguments for the default arguments.
6983     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6984   }
6985 
6986   // Bail out early if calling a builtin with custom type checking.
6987   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6988     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6989 
6990   if (getLangOpts().CUDA) {
6991     if (Config) {
6992       // CUDA: Kernel calls must be to global functions
6993       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6994         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6995             << FDecl << Fn->getSourceRange());
6996 
6997       // CUDA: Kernel function must have 'void' return type
6998       if (!FuncT->getReturnType()->isVoidType() &&
6999           !FuncT->getReturnType()->getAs<AutoType>() &&
7000           !FuncT->getReturnType()->isInstantiationDependentType())
7001         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7002             << Fn->getType() << Fn->getSourceRange());
7003     } else {
7004       // CUDA: Calls to global functions must be configured
7005       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7006         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7007             << FDecl << Fn->getSourceRange());
7008     }
7009   }
7010 
7011   // Check for a valid return type
7012   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7013                           FDecl))
7014     return ExprError();
7015 
7016   // We know the result type of the call, set it.
7017   TheCall->setType(FuncT->getCallResultType(Context));
7018   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7019 
7020   if (Proto) {
7021     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7022                                 IsExecConfig))
7023       return ExprError();
7024   } else {
7025     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7026 
7027     if (FDecl) {
7028       // Check if we have too few/too many template arguments, based
7029       // on our knowledge of the function definition.
7030       const FunctionDecl *Def = nullptr;
7031       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7032         Proto = Def->getType()->getAs<FunctionProtoType>();
7033        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7034           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7035           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7036       }
7037 
7038       // If the function we're calling isn't a function prototype, but we have
7039       // a function prototype from a prior declaratiom, use that prototype.
7040       if (!FDecl->hasPrototype())
7041         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7042     }
7043 
7044     // Promote the arguments (C99 6.5.2.2p6).
7045     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7046       Expr *Arg = Args[i];
7047 
7048       if (Proto && i < Proto->getNumParams()) {
7049         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7050             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7051         ExprResult ArgE =
7052             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7053         if (ArgE.isInvalid())
7054           return true;
7055 
7056         Arg = ArgE.getAs<Expr>();
7057 
7058       } else {
7059         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7060 
7061         if (ArgE.isInvalid())
7062           return true;
7063 
7064         Arg = ArgE.getAs<Expr>();
7065       }
7066 
7067       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7068                               diag::err_call_incomplete_argument, Arg))
7069         return ExprError();
7070 
7071       TheCall->setArg(i, Arg);
7072     }
7073     TheCall->computeDependence();
7074   }
7075 
7076   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7077     if (!Method->isStatic())
7078       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7079         << Fn->getSourceRange());
7080 
7081   // Check for sentinels
7082   if (NDecl)
7083     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7084 
7085   // Warn for unions passing across security boundary (CMSE).
7086   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7087     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7088       if (const auto *RT =
7089               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7090         if (RT->getDecl()->isOrContainsUnion())
7091           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7092               << 0 << i;
7093       }
7094     }
7095   }
7096 
7097   // Do special checking on direct calls to functions.
7098   if (FDecl) {
7099     if (CheckFunctionCall(FDecl, TheCall, Proto))
7100       return ExprError();
7101 
7102     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7103 
7104     if (BuiltinID)
7105       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7106   } else if (NDecl) {
7107     if (CheckPointerCall(NDecl, TheCall, Proto))
7108       return ExprError();
7109   } else {
7110     if (CheckOtherCall(TheCall, Proto))
7111       return ExprError();
7112   }
7113 
7114   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7115 }
7116 
7117 ExprResult
7118 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7119                            SourceLocation RParenLoc, Expr *InitExpr) {
7120   assert(Ty && "ActOnCompoundLiteral(): missing type");
7121   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7122 
7123   TypeSourceInfo *TInfo;
7124   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7125   if (!TInfo)
7126     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7127 
7128   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7129 }
7130 
7131 ExprResult
7132 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7133                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7134   QualType literalType = TInfo->getType();
7135 
7136   if (literalType->isArrayType()) {
7137     if (RequireCompleteSizedType(
7138             LParenLoc, Context.getBaseElementType(literalType),
7139             diag::err_array_incomplete_or_sizeless_type,
7140             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7141       return ExprError();
7142     if (literalType->isVariableArrayType()) {
7143       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7144                                            diag::err_variable_object_no_init)) {
7145         return ExprError();
7146       }
7147     }
7148   } else if (!literalType->isDependentType() &&
7149              RequireCompleteType(LParenLoc, literalType,
7150                diag::err_typecheck_decl_incomplete_type,
7151                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7152     return ExprError();
7153 
7154   InitializedEntity Entity
7155     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7156   InitializationKind Kind
7157     = InitializationKind::CreateCStyleCast(LParenLoc,
7158                                            SourceRange(LParenLoc, RParenLoc),
7159                                            /*InitList=*/true);
7160   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7161   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7162                                       &literalType);
7163   if (Result.isInvalid())
7164     return ExprError();
7165   LiteralExpr = Result.get();
7166 
7167   bool isFileScope = !CurContext->isFunctionOrMethod();
7168 
7169   // In C, compound literals are l-values for some reason.
7170   // For GCC compatibility, in C++, file-scope array compound literals with
7171   // constant initializers are also l-values, and compound literals are
7172   // otherwise prvalues.
7173   //
7174   // (GCC also treats C++ list-initialized file-scope array prvalues with
7175   // constant initializers as l-values, but that's non-conforming, so we don't
7176   // follow it there.)
7177   //
7178   // FIXME: It would be better to handle the lvalue cases as materializing and
7179   // lifetime-extending a temporary object, but our materialized temporaries
7180   // representation only supports lifetime extension from a variable, not "out
7181   // of thin air".
7182   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7183   // is bound to the result of applying array-to-pointer decay to the compound
7184   // literal.
7185   // FIXME: GCC supports compound literals of reference type, which should
7186   // obviously have a value kind derived from the kind of reference involved.
7187   ExprValueKind VK =
7188       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7189           ? VK_PRValue
7190           : VK_LValue;
7191 
7192   if (isFileScope)
7193     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7194       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7195         Expr *Init = ILE->getInit(i);
7196         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7197       }
7198 
7199   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7200                                               VK, LiteralExpr, isFileScope);
7201   if (isFileScope) {
7202     if (!LiteralExpr->isTypeDependent() &&
7203         !LiteralExpr->isValueDependent() &&
7204         !literalType->isDependentType()) // C99 6.5.2.5p3
7205       if (CheckForConstantInitializer(LiteralExpr, literalType))
7206         return ExprError();
7207   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7208              literalType.getAddressSpace() != LangAS::Default) {
7209     // Embedded-C extensions to C99 6.5.2.5:
7210     //   "If the compound literal occurs inside the body of a function, the
7211     //   type name shall not be qualified by an address-space qualifier."
7212     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7213       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7214     return ExprError();
7215   }
7216 
7217   if (!isFileScope && !getLangOpts().CPlusPlus) {
7218     // Compound literals that have automatic storage duration are destroyed at
7219     // the end of the scope in C; in C++, they're just temporaries.
7220 
7221     // Emit diagnostics if it is or contains a C union type that is non-trivial
7222     // to destruct.
7223     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7224       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7225                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7226 
7227     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7228     if (literalType.isDestructedType()) {
7229       Cleanup.setExprNeedsCleanups(true);
7230       ExprCleanupObjects.push_back(E);
7231       getCurFunction()->setHasBranchProtectedScope();
7232     }
7233   }
7234 
7235   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7236       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7237     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7238                                        E->getInitializer()->getExprLoc());
7239 
7240   return MaybeBindToTemporary(E);
7241 }
7242 
7243 ExprResult
7244 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7245                     SourceLocation RBraceLoc) {
7246   // Only produce each kind of designated initialization diagnostic once.
7247   SourceLocation FirstDesignator;
7248   bool DiagnosedArrayDesignator = false;
7249   bool DiagnosedNestedDesignator = false;
7250   bool DiagnosedMixedDesignator = false;
7251 
7252   // Check that any designated initializers are syntactically valid in the
7253   // current language mode.
7254   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7255     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7256       if (FirstDesignator.isInvalid())
7257         FirstDesignator = DIE->getBeginLoc();
7258 
7259       if (!getLangOpts().CPlusPlus)
7260         break;
7261 
7262       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7263         DiagnosedNestedDesignator = true;
7264         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7265           << DIE->getDesignatorsSourceRange();
7266       }
7267 
7268       for (auto &Desig : DIE->designators()) {
7269         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7270           DiagnosedArrayDesignator = true;
7271           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7272             << Desig.getSourceRange();
7273         }
7274       }
7275 
7276       if (!DiagnosedMixedDesignator &&
7277           !isa<DesignatedInitExpr>(InitArgList[0])) {
7278         DiagnosedMixedDesignator = true;
7279         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7280           << DIE->getSourceRange();
7281         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7282           << InitArgList[0]->getSourceRange();
7283       }
7284     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7285                isa<DesignatedInitExpr>(InitArgList[0])) {
7286       DiagnosedMixedDesignator = true;
7287       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7288       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7289         << DIE->getSourceRange();
7290       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7291         << InitArgList[I]->getSourceRange();
7292     }
7293   }
7294 
7295   if (FirstDesignator.isValid()) {
7296     // Only diagnose designated initiaization as a C++20 extension if we didn't
7297     // already diagnose use of (non-C++20) C99 designator syntax.
7298     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7299         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7300       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7301                                 ? diag::warn_cxx17_compat_designated_init
7302                                 : diag::ext_cxx_designated_init);
7303     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7304       Diag(FirstDesignator, diag::ext_designated_init);
7305     }
7306   }
7307 
7308   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7309 }
7310 
7311 ExprResult
7312 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7313                     SourceLocation RBraceLoc) {
7314   // Semantic analysis for initializers is done by ActOnDeclarator() and
7315   // CheckInitializer() - it requires knowledge of the object being initialized.
7316 
7317   // Immediately handle non-overload placeholders.  Overloads can be
7318   // resolved contextually, but everything else here can't.
7319   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7320     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7321       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7322 
7323       // Ignore failures; dropping the entire initializer list because
7324       // of one failure would be terrible for indexing/etc.
7325       if (result.isInvalid()) continue;
7326 
7327       InitArgList[I] = result.get();
7328     }
7329   }
7330 
7331   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7332                                                RBraceLoc);
7333   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7334   return E;
7335 }
7336 
7337 /// Do an explicit extend of the given block pointer if we're in ARC.
7338 void Sema::maybeExtendBlockObject(ExprResult &E) {
7339   assert(E.get()->getType()->isBlockPointerType());
7340   assert(E.get()->isPRValue());
7341 
7342   // Only do this in an r-value context.
7343   if (!getLangOpts().ObjCAutoRefCount) return;
7344 
7345   E = ImplicitCastExpr::Create(
7346       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7347       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7348   Cleanup.setExprNeedsCleanups(true);
7349 }
7350 
7351 /// Prepare a conversion of the given expression to an ObjC object
7352 /// pointer type.
7353 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7354   QualType type = E.get()->getType();
7355   if (type->isObjCObjectPointerType()) {
7356     return CK_BitCast;
7357   } else if (type->isBlockPointerType()) {
7358     maybeExtendBlockObject(E);
7359     return CK_BlockPointerToObjCPointerCast;
7360   } else {
7361     assert(type->isPointerType());
7362     return CK_CPointerToObjCPointerCast;
7363   }
7364 }
7365 
7366 /// Prepares for a scalar cast, performing all the necessary stages
7367 /// except the final cast and returning the kind required.
7368 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7369   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7370   // Also, callers should have filtered out the invalid cases with
7371   // pointers.  Everything else should be possible.
7372 
7373   QualType SrcTy = Src.get()->getType();
7374   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7375     return CK_NoOp;
7376 
7377   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7378   case Type::STK_MemberPointer:
7379     llvm_unreachable("member pointer type in C");
7380 
7381   case Type::STK_CPointer:
7382   case Type::STK_BlockPointer:
7383   case Type::STK_ObjCObjectPointer:
7384     switch (DestTy->getScalarTypeKind()) {
7385     case Type::STK_CPointer: {
7386       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7387       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7388       if (SrcAS != DestAS)
7389         return CK_AddressSpaceConversion;
7390       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7391         return CK_NoOp;
7392       return CK_BitCast;
7393     }
7394     case Type::STK_BlockPointer:
7395       return (SrcKind == Type::STK_BlockPointer
7396                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7397     case Type::STK_ObjCObjectPointer:
7398       if (SrcKind == Type::STK_ObjCObjectPointer)
7399         return CK_BitCast;
7400       if (SrcKind == Type::STK_CPointer)
7401         return CK_CPointerToObjCPointerCast;
7402       maybeExtendBlockObject(Src);
7403       return CK_BlockPointerToObjCPointerCast;
7404     case Type::STK_Bool:
7405       return CK_PointerToBoolean;
7406     case Type::STK_Integral:
7407       return CK_PointerToIntegral;
7408     case Type::STK_Floating:
7409     case Type::STK_FloatingComplex:
7410     case Type::STK_IntegralComplex:
7411     case Type::STK_MemberPointer:
7412     case Type::STK_FixedPoint:
7413       llvm_unreachable("illegal cast from pointer");
7414     }
7415     llvm_unreachable("Should have returned before this");
7416 
7417   case Type::STK_FixedPoint:
7418     switch (DestTy->getScalarTypeKind()) {
7419     case Type::STK_FixedPoint:
7420       return CK_FixedPointCast;
7421     case Type::STK_Bool:
7422       return CK_FixedPointToBoolean;
7423     case Type::STK_Integral:
7424       return CK_FixedPointToIntegral;
7425     case Type::STK_Floating:
7426       return CK_FixedPointToFloating;
7427     case Type::STK_IntegralComplex:
7428     case Type::STK_FloatingComplex:
7429       Diag(Src.get()->getExprLoc(),
7430            diag::err_unimplemented_conversion_with_fixed_point_type)
7431           << DestTy;
7432       return CK_IntegralCast;
7433     case Type::STK_CPointer:
7434     case Type::STK_ObjCObjectPointer:
7435     case Type::STK_BlockPointer:
7436     case Type::STK_MemberPointer:
7437       llvm_unreachable("illegal cast to pointer type");
7438     }
7439     llvm_unreachable("Should have returned before this");
7440 
7441   case Type::STK_Bool: // casting from bool is like casting from an integer
7442   case Type::STK_Integral:
7443     switch (DestTy->getScalarTypeKind()) {
7444     case Type::STK_CPointer:
7445     case Type::STK_ObjCObjectPointer:
7446     case Type::STK_BlockPointer:
7447       if (Src.get()->isNullPointerConstant(Context,
7448                                            Expr::NPC_ValueDependentIsNull))
7449         return CK_NullToPointer;
7450       return CK_IntegralToPointer;
7451     case Type::STK_Bool:
7452       return CK_IntegralToBoolean;
7453     case Type::STK_Integral:
7454       return CK_IntegralCast;
7455     case Type::STK_Floating:
7456       return CK_IntegralToFloating;
7457     case Type::STK_IntegralComplex:
7458       Src = ImpCastExprToType(Src.get(),
7459                       DestTy->castAs<ComplexType>()->getElementType(),
7460                       CK_IntegralCast);
7461       return CK_IntegralRealToComplex;
7462     case Type::STK_FloatingComplex:
7463       Src = ImpCastExprToType(Src.get(),
7464                       DestTy->castAs<ComplexType>()->getElementType(),
7465                       CK_IntegralToFloating);
7466       return CK_FloatingRealToComplex;
7467     case Type::STK_MemberPointer:
7468       llvm_unreachable("member pointer type in C");
7469     case Type::STK_FixedPoint:
7470       return CK_IntegralToFixedPoint;
7471     }
7472     llvm_unreachable("Should have returned before this");
7473 
7474   case Type::STK_Floating:
7475     switch (DestTy->getScalarTypeKind()) {
7476     case Type::STK_Floating:
7477       return CK_FloatingCast;
7478     case Type::STK_Bool:
7479       return CK_FloatingToBoolean;
7480     case Type::STK_Integral:
7481       return CK_FloatingToIntegral;
7482     case Type::STK_FloatingComplex:
7483       Src = ImpCastExprToType(Src.get(),
7484                               DestTy->castAs<ComplexType>()->getElementType(),
7485                               CK_FloatingCast);
7486       return CK_FloatingRealToComplex;
7487     case Type::STK_IntegralComplex:
7488       Src = ImpCastExprToType(Src.get(),
7489                               DestTy->castAs<ComplexType>()->getElementType(),
7490                               CK_FloatingToIntegral);
7491       return CK_IntegralRealToComplex;
7492     case Type::STK_CPointer:
7493     case Type::STK_ObjCObjectPointer:
7494     case Type::STK_BlockPointer:
7495       llvm_unreachable("valid float->pointer cast?");
7496     case Type::STK_MemberPointer:
7497       llvm_unreachable("member pointer type in C");
7498     case Type::STK_FixedPoint:
7499       return CK_FloatingToFixedPoint;
7500     }
7501     llvm_unreachable("Should have returned before this");
7502 
7503   case Type::STK_FloatingComplex:
7504     switch (DestTy->getScalarTypeKind()) {
7505     case Type::STK_FloatingComplex:
7506       return CK_FloatingComplexCast;
7507     case Type::STK_IntegralComplex:
7508       return CK_FloatingComplexToIntegralComplex;
7509     case Type::STK_Floating: {
7510       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7511       if (Context.hasSameType(ET, DestTy))
7512         return CK_FloatingComplexToReal;
7513       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7514       return CK_FloatingCast;
7515     }
7516     case Type::STK_Bool:
7517       return CK_FloatingComplexToBoolean;
7518     case Type::STK_Integral:
7519       Src = ImpCastExprToType(Src.get(),
7520                               SrcTy->castAs<ComplexType>()->getElementType(),
7521                               CK_FloatingComplexToReal);
7522       return CK_FloatingToIntegral;
7523     case Type::STK_CPointer:
7524     case Type::STK_ObjCObjectPointer:
7525     case Type::STK_BlockPointer:
7526       llvm_unreachable("valid complex float->pointer cast?");
7527     case Type::STK_MemberPointer:
7528       llvm_unreachable("member pointer type in C");
7529     case Type::STK_FixedPoint:
7530       Diag(Src.get()->getExprLoc(),
7531            diag::err_unimplemented_conversion_with_fixed_point_type)
7532           << SrcTy;
7533       return CK_IntegralCast;
7534     }
7535     llvm_unreachable("Should have returned before this");
7536 
7537   case Type::STK_IntegralComplex:
7538     switch (DestTy->getScalarTypeKind()) {
7539     case Type::STK_FloatingComplex:
7540       return CK_IntegralComplexToFloatingComplex;
7541     case Type::STK_IntegralComplex:
7542       return CK_IntegralComplexCast;
7543     case Type::STK_Integral: {
7544       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7545       if (Context.hasSameType(ET, DestTy))
7546         return CK_IntegralComplexToReal;
7547       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7548       return CK_IntegralCast;
7549     }
7550     case Type::STK_Bool:
7551       return CK_IntegralComplexToBoolean;
7552     case Type::STK_Floating:
7553       Src = ImpCastExprToType(Src.get(),
7554                               SrcTy->castAs<ComplexType>()->getElementType(),
7555                               CK_IntegralComplexToReal);
7556       return CK_IntegralToFloating;
7557     case Type::STK_CPointer:
7558     case Type::STK_ObjCObjectPointer:
7559     case Type::STK_BlockPointer:
7560       llvm_unreachable("valid complex int->pointer cast?");
7561     case Type::STK_MemberPointer:
7562       llvm_unreachable("member pointer type in C");
7563     case Type::STK_FixedPoint:
7564       Diag(Src.get()->getExprLoc(),
7565            diag::err_unimplemented_conversion_with_fixed_point_type)
7566           << SrcTy;
7567       return CK_IntegralCast;
7568     }
7569     llvm_unreachable("Should have returned before this");
7570   }
7571 
7572   llvm_unreachable("Unhandled scalar cast");
7573 }
7574 
7575 static bool breakDownVectorType(QualType type, uint64_t &len,
7576                                 QualType &eltType) {
7577   // Vectors are simple.
7578   if (const VectorType *vecType = type->getAs<VectorType>()) {
7579     len = vecType->getNumElements();
7580     eltType = vecType->getElementType();
7581     assert(eltType->isScalarType());
7582     return true;
7583   }
7584 
7585   // We allow lax conversion to and from non-vector types, but only if
7586   // they're real types (i.e. non-complex, non-pointer scalar types).
7587   if (!type->isRealType()) return false;
7588 
7589   len = 1;
7590   eltType = type;
7591   return true;
7592 }
7593 
7594 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7595 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7596 /// allowed?
7597 ///
7598 /// This will also return false if the two given types do not make sense from
7599 /// the perspective of SVE bitcasts.
7600 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7601   assert(srcTy->isVectorType() || destTy->isVectorType());
7602 
7603   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7604     if (!FirstType->isSizelessBuiltinType())
7605       return false;
7606 
7607     const auto *VecTy = SecondType->getAs<VectorType>();
7608     return VecTy &&
7609            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7610   };
7611 
7612   return ValidScalableConversion(srcTy, destTy) ||
7613          ValidScalableConversion(destTy, srcTy);
7614 }
7615 
7616 /// Are the two types matrix types and do they have the same dimensions i.e.
7617 /// do they have the same number of rows and the same number of columns?
7618 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7619   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7620     return false;
7621 
7622   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7623   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7624 
7625   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7626          matSrcType->getNumColumns() == matDestType->getNumColumns();
7627 }
7628 
7629 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7630   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7631 
7632   uint64_t SrcLen, DestLen;
7633   QualType SrcEltTy, DestEltTy;
7634   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7635     return false;
7636   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7637     return false;
7638 
7639   // ASTContext::getTypeSize will return the size rounded up to a
7640   // power of 2, so instead of using that, we need to use the raw
7641   // element size multiplied by the element count.
7642   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7643   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7644 
7645   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7646 }
7647 
7648 /// Are the two types lax-compatible vector types?  That is, given
7649 /// that one of them is a vector, do they have equal storage sizes,
7650 /// where the storage size is the number of elements times the element
7651 /// size?
7652 ///
7653 /// This will also return false if either of the types is neither a
7654 /// vector nor a real type.
7655 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7656   assert(destTy->isVectorType() || srcTy->isVectorType());
7657 
7658   // Disallow lax conversions between scalars and ExtVectors (these
7659   // conversions are allowed for other vector types because common headers
7660   // depend on them).  Most scalar OP ExtVector cases are handled by the
7661   // splat path anyway, which does what we want (convert, not bitcast).
7662   // What this rules out for ExtVectors is crazy things like char4*float.
7663   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7664   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7665 
7666   return areVectorTypesSameSize(srcTy, destTy);
7667 }
7668 
7669 /// Is this a legal conversion between two types, one of which is
7670 /// known to be a vector type?
7671 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7672   assert(destTy->isVectorType() || srcTy->isVectorType());
7673 
7674   switch (Context.getLangOpts().getLaxVectorConversions()) {
7675   case LangOptions::LaxVectorConversionKind::None:
7676     return false;
7677 
7678   case LangOptions::LaxVectorConversionKind::Integer:
7679     if (!srcTy->isIntegralOrEnumerationType()) {
7680       auto *Vec = srcTy->getAs<VectorType>();
7681       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7682         return false;
7683     }
7684     if (!destTy->isIntegralOrEnumerationType()) {
7685       auto *Vec = destTy->getAs<VectorType>();
7686       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7687         return false;
7688     }
7689     // OK, integer (vector) -> integer (vector) bitcast.
7690     break;
7691 
7692     case LangOptions::LaxVectorConversionKind::All:
7693     break;
7694   }
7695 
7696   return areLaxCompatibleVectorTypes(srcTy, destTy);
7697 }
7698 
7699 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7700                            CastKind &Kind) {
7701   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7702     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7703       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7704              << DestTy << SrcTy << R;
7705     }
7706   } else if (SrcTy->isMatrixType()) {
7707     return Diag(R.getBegin(),
7708                 diag::err_invalid_conversion_between_matrix_and_type)
7709            << SrcTy << DestTy << R;
7710   } else if (DestTy->isMatrixType()) {
7711     return Diag(R.getBegin(),
7712                 diag::err_invalid_conversion_between_matrix_and_type)
7713            << DestTy << SrcTy << R;
7714   }
7715 
7716   Kind = CK_MatrixCast;
7717   return false;
7718 }
7719 
7720 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7721                            CastKind &Kind) {
7722   assert(VectorTy->isVectorType() && "Not a vector type!");
7723 
7724   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7725     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7726       return Diag(R.getBegin(),
7727                   Ty->isVectorType() ?
7728                   diag::err_invalid_conversion_between_vectors :
7729                   diag::err_invalid_conversion_between_vector_and_integer)
7730         << VectorTy << Ty << R;
7731   } else
7732     return Diag(R.getBegin(),
7733                 diag::err_invalid_conversion_between_vector_and_scalar)
7734       << VectorTy << Ty << R;
7735 
7736   Kind = CK_BitCast;
7737   return false;
7738 }
7739 
7740 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7741   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7742 
7743   if (DestElemTy == SplattedExpr->getType())
7744     return SplattedExpr;
7745 
7746   assert(DestElemTy->isFloatingType() ||
7747          DestElemTy->isIntegralOrEnumerationType());
7748 
7749   CastKind CK;
7750   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7751     // OpenCL requires that we convert `true` boolean expressions to -1, but
7752     // only when splatting vectors.
7753     if (DestElemTy->isFloatingType()) {
7754       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7755       // in two steps: boolean to signed integral, then to floating.
7756       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7757                                                  CK_BooleanToSignedIntegral);
7758       SplattedExpr = CastExprRes.get();
7759       CK = CK_IntegralToFloating;
7760     } else {
7761       CK = CK_BooleanToSignedIntegral;
7762     }
7763   } else {
7764     ExprResult CastExprRes = SplattedExpr;
7765     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7766     if (CastExprRes.isInvalid())
7767       return ExprError();
7768     SplattedExpr = CastExprRes.get();
7769   }
7770   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7771 }
7772 
7773 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7774                                     Expr *CastExpr, CastKind &Kind) {
7775   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7776 
7777   QualType SrcTy = CastExpr->getType();
7778 
7779   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7780   // an ExtVectorType.
7781   // In OpenCL, casts between vectors of different types are not allowed.
7782   // (See OpenCL 6.2).
7783   if (SrcTy->isVectorType()) {
7784     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7785         (getLangOpts().OpenCL &&
7786          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7787       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7788         << DestTy << SrcTy << R;
7789       return ExprError();
7790     }
7791     Kind = CK_BitCast;
7792     return CastExpr;
7793   }
7794 
7795   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7796   // conversion will take place first from scalar to elt type, and then
7797   // splat from elt type to vector.
7798   if (SrcTy->isPointerType())
7799     return Diag(R.getBegin(),
7800                 diag::err_invalid_conversion_between_vector_and_scalar)
7801       << DestTy << SrcTy << R;
7802 
7803   Kind = CK_VectorSplat;
7804   return prepareVectorSplat(DestTy, CastExpr);
7805 }
7806 
7807 ExprResult
7808 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7809                     Declarator &D, ParsedType &Ty,
7810                     SourceLocation RParenLoc, Expr *CastExpr) {
7811   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7812          "ActOnCastExpr(): missing type or expr");
7813 
7814   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7815   if (D.isInvalidType())
7816     return ExprError();
7817 
7818   if (getLangOpts().CPlusPlus) {
7819     // Check that there are no default arguments (C++ only).
7820     CheckExtraCXXDefaultArguments(D);
7821   } else {
7822     // Make sure any TypoExprs have been dealt with.
7823     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7824     if (!Res.isUsable())
7825       return ExprError();
7826     CastExpr = Res.get();
7827   }
7828 
7829   checkUnusedDeclAttributes(D);
7830 
7831   QualType castType = castTInfo->getType();
7832   Ty = CreateParsedType(castType, castTInfo);
7833 
7834   bool isVectorLiteral = false;
7835 
7836   // Check for an altivec or OpenCL literal,
7837   // i.e. all the elements are integer constants.
7838   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7839   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7840   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7841        && castType->isVectorType() && (PE || PLE)) {
7842     if (PLE && PLE->getNumExprs() == 0) {
7843       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7844       return ExprError();
7845     }
7846     if (PE || PLE->getNumExprs() == 1) {
7847       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7848       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7849         isVectorLiteral = true;
7850     }
7851     else
7852       isVectorLiteral = true;
7853   }
7854 
7855   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7856   // then handle it as such.
7857   if (isVectorLiteral)
7858     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7859 
7860   // If the Expr being casted is a ParenListExpr, handle it specially.
7861   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7862   // sequence of BinOp comma operators.
7863   if (isa<ParenListExpr>(CastExpr)) {
7864     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7865     if (Result.isInvalid()) return ExprError();
7866     CastExpr = Result.get();
7867   }
7868 
7869   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7870     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7871 
7872   CheckTollFreeBridgeCast(castType, CastExpr);
7873 
7874   CheckObjCBridgeRelatedCast(castType, CastExpr);
7875 
7876   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7877 
7878   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7879 }
7880 
7881 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7882                                     SourceLocation RParenLoc, Expr *E,
7883                                     TypeSourceInfo *TInfo) {
7884   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7885          "Expected paren or paren list expression");
7886 
7887   Expr **exprs;
7888   unsigned numExprs;
7889   Expr *subExpr;
7890   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7891   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7892     LiteralLParenLoc = PE->getLParenLoc();
7893     LiteralRParenLoc = PE->getRParenLoc();
7894     exprs = PE->getExprs();
7895     numExprs = PE->getNumExprs();
7896   } else { // isa<ParenExpr> by assertion at function entrance
7897     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7898     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7899     subExpr = cast<ParenExpr>(E)->getSubExpr();
7900     exprs = &subExpr;
7901     numExprs = 1;
7902   }
7903 
7904   QualType Ty = TInfo->getType();
7905   assert(Ty->isVectorType() && "Expected vector type");
7906 
7907   SmallVector<Expr *, 8> initExprs;
7908   const VectorType *VTy = Ty->castAs<VectorType>();
7909   unsigned numElems = VTy->getNumElements();
7910 
7911   // '(...)' form of vector initialization in AltiVec: the number of
7912   // initializers must be one or must match the size of the vector.
7913   // If a single value is specified in the initializer then it will be
7914   // replicated to all the components of the vector
7915   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7916                                  VTy->getElementType()))
7917     return ExprError();
7918   if (ShouldSplatAltivecScalarInCast(VTy)) {
7919     // The number of initializers must be one or must match the size of the
7920     // vector. If a single value is specified in the initializer then it will
7921     // be replicated to all the components of the vector
7922     if (numExprs == 1) {
7923       QualType ElemTy = VTy->getElementType();
7924       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7925       if (Literal.isInvalid())
7926         return ExprError();
7927       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7928                                   PrepareScalarCast(Literal, ElemTy));
7929       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7930     }
7931     else if (numExprs < numElems) {
7932       Diag(E->getExprLoc(),
7933            diag::err_incorrect_number_of_vector_initializers);
7934       return ExprError();
7935     }
7936     else
7937       initExprs.append(exprs, exprs + numExprs);
7938   }
7939   else {
7940     // For OpenCL, when the number of initializers is a single value,
7941     // it will be replicated to all components of the vector.
7942     if (getLangOpts().OpenCL &&
7943         VTy->getVectorKind() == VectorType::GenericVector &&
7944         numExprs == 1) {
7945         QualType ElemTy = VTy->getElementType();
7946         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7947         if (Literal.isInvalid())
7948           return ExprError();
7949         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7950                                     PrepareScalarCast(Literal, ElemTy));
7951         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7952     }
7953 
7954     initExprs.append(exprs, exprs + numExprs);
7955   }
7956   // FIXME: This means that pretty-printing the final AST will produce curly
7957   // braces instead of the original commas.
7958   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7959                                                    initExprs, LiteralRParenLoc);
7960   initE->setType(Ty);
7961   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7962 }
7963 
7964 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7965 /// the ParenListExpr into a sequence of comma binary operators.
7966 ExprResult
7967 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7968   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7969   if (!E)
7970     return OrigExpr;
7971 
7972   ExprResult Result(E->getExpr(0));
7973 
7974   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7975     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7976                         E->getExpr(i));
7977 
7978   if (Result.isInvalid()) return ExprError();
7979 
7980   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7981 }
7982 
7983 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7984                                     SourceLocation R,
7985                                     MultiExprArg Val) {
7986   return ParenListExpr::Create(Context, L, Val, R);
7987 }
7988 
7989 /// Emit a specialized diagnostic when one expression is a null pointer
7990 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7991 /// emitted.
7992 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7993                                       SourceLocation QuestionLoc) {
7994   Expr *NullExpr = LHSExpr;
7995   Expr *NonPointerExpr = RHSExpr;
7996   Expr::NullPointerConstantKind NullKind =
7997       NullExpr->isNullPointerConstant(Context,
7998                                       Expr::NPC_ValueDependentIsNotNull);
7999 
8000   if (NullKind == Expr::NPCK_NotNull) {
8001     NullExpr = RHSExpr;
8002     NonPointerExpr = LHSExpr;
8003     NullKind =
8004         NullExpr->isNullPointerConstant(Context,
8005                                         Expr::NPC_ValueDependentIsNotNull);
8006   }
8007 
8008   if (NullKind == Expr::NPCK_NotNull)
8009     return false;
8010 
8011   if (NullKind == Expr::NPCK_ZeroExpression)
8012     return false;
8013 
8014   if (NullKind == Expr::NPCK_ZeroLiteral) {
8015     // In this case, check to make sure that we got here from a "NULL"
8016     // string in the source code.
8017     NullExpr = NullExpr->IgnoreParenImpCasts();
8018     SourceLocation loc = NullExpr->getExprLoc();
8019     if (!findMacroSpelling(loc, "NULL"))
8020       return false;
8021   }
8022 
8023   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8024   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8025       << NonPointerExpr->getType() << DiagType
8026       << NonPointerExpr->getSourceRange();
8027   return true;
8028 }
8029 
8030 /// Return false if the condition expression is valid, true otherwise.
8031 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8032   QualType CondTy = Cond->getType();
8033 
8034   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8035   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8036     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8037       << CondTy << Cond->getSourceRange();
8038     return true;
8039   }
8040 
8041   // C99 6.5.15p2
8042   if (CondTy->isScalarType()) return false;
8043 
8044   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8045     << CondTy << Cond->getSourceRange();
8046   return true;
8047 }
8048 
8049 /// Handle when one or both operands are void type.
8050 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8051                                          ExprResult &RHS) {
8052     Expr *LHSExpr = LHS.get();
8053     Expr *RHSExpr = RHS.get();
8054 
8055     if (!LHSExpr->getType()->isVoidType())
8056       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8057           << RHSExpr->getSourceRange();
8058     if (!RHSExpr->getType()->isVoidType())
8059       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8060           << LHSExpr->getSourceRange();
8061     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8062     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8063     return S.Context.VoidTy;
8064 }
8065 
8066 /// Return false if the NullExpr can be promoted to PointerTy,
8067 /// true otherwise.
8068 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8069                                         QualType PointerTy) {
8070   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8071       !NullExpr.get()->isNullPointerConstant(S.Context,
8072                                             Expr::NPC_ValueDependentIsNull))
8073     return true;
8074 
8075   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8076   return false;
8077 }
8078 
8079 /// Checks compatibility between two pointers and return the resulting
8080 /// type.
8081 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8082                                                      ExprResult &RHS,
8083                                                      SourceLocation Loc) {
8084   QualType LHSTy = LHS.get()->getType();
8085   QualType RHSTy = RHS.get()->getType();
8086 
8087   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8088     // Two identical pointers types are always compatible.
8089     return LHSTy;
8090   }
8091 
8092   QualType lhptee, rhptee;
8093 
8094   // Get the pointee types.
8095   bool IsBlockPointer = false;
8096   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8097     lhptee = LHSBTy->getPointeeType();
8098     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8099     IsBlockPointer = true;
8100   } else {
8101     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8102     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8103   }
8104 
8105   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8106   // differently qualified versions of compatible types, the result type is
8107   // a pointer to an appropriately qualified version of the composite
8108   // type.
8109 
8110   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8111   // clause doesn't make sense for our extensions. E.g. address space 2 should
8112   // be incompatible with address space 3: they may live on different devices or
8113   // anything.
8114   Qualifiers lhQual = lhptee.getQualifiers();
8115   Qualifiers rhQual = rhptee.getQualifiers();
8116 
8117   LangAS ResultAddrSpace = LangAS::Default;
8118   LangAS LAddrSpace = lhQual.getAddressSpace();
8119   LangAS RAddrSpace = rhQual.getAddressSpace();
8120 
8121   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8122   // spaces is disallowed.
8123   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8124     ResultAddrSpace = LAddrSpace;
8125   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8126     ResultAddrSpace = RAddrSpace;
8127   else {
8128     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8129         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8130         << RHS.get()->getSourceRange();
8131     return QualType();
8132   }
8133 
8134   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8135   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8136   lhQual.removeCVRQualifiers();
8137   rhQual.removeCVRQualifiers();
8138 
8139   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8140   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8141   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8142   // qual types are compatible iff
8143   //  * corresponded types are compatible
8144   //  * CVR qualifiers are equal
8145   //  * address spaces are equal
8146   // Thus for conditional operator we merge CVR and address space unqualified
8147   // pointees and if there is a composite type we return a pointer to it with
8148   // merged qualifiers.
8149   LHSCastKind =
8150       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8151   RHSCastKind =
8152       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8153   lhQual.removeAddressSpace();
8154   rhQual.removeAddressSpace();
8155 
8156   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8157   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8158 
8159   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8160 
8161   if (CompositeTy.isNull()) {
8162     // In this situation, we assume void* type. No especially good
8163     // reason, but this is what gcc does, and we do have to pick
8164     // to get a consistent AST.
8165     QualType incompatTy;
8166     incompatTy = S.Context.getPointerType(
8167         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8168     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8169     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8170 
8171     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8172     // for casts between types with incompatible address space qualifiers.
8173     // For the following code the compiler produces casts between global and
8174     // local address spaces of the corresponded innermost pointees:
8175     // local int *global *a;
8176     // global int *global *b;
8177     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8178     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8179         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8180         << RHS.get()->getSourceRange();
8181 
8182     return incompatTy;
8183   }
8184 
8185   // The pointer types are compatible.
8186   // In case of OpenCL ResultTy should have the address space qualifier
8187   // which is a superset of address spaces of both the 2nd and the 3rd
8188   // operands of the conditional operator.
8189   QualType ResultTy = [&, ResultAddrSpace]() {
8190     if (S.getLangOpts().OpenCL) {
8191       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8192       CompositeQuals.setAddressSpace(ResultAddrSpace);
8193       return S.Context
8194           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8195           .withCVRQualifiers(MergedCVRQual);
8196     }
8197     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8198   }();
8199   if (IsBlockPointer)
8200     ResultTy = S.Context.getBlockPointerType(ResultTy);
8201   else
8202     ResultTy = S.Context.getPointerType(ResultTy);
8203 
8204   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8205   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8206   return ResultTy;
8207 }
8208 
8209 /// Return the resulting type when the operands are both block pointers.
8210 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8211                                                           ExprResult &LHS,
8212                                                           ExprResult &RHS,
8213                                                           SourceLocation Loc) {
8214   QualType LHSTy = LHS.get()->getType();
8215   QualType RHSTy = RHS.get()->getType();
8216 
8217   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8218     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8219       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8220       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8221       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8222       return destType;
8223     }
8224     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8225       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8226       << RHS.get()->getSourceRange();
8227     return QualType();
8228   }
8229 
8230   // We have 2 block pointer types.
8231   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8232 }
8233 
8234 /// Return the resulting type when the operands are both pointers.
8235 static QualType
8236 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8237                                             ExprResult &RHS,
8238                                             SourceLocation Loc) {
8239   // get the pointer types
8240   QualType LHSTy = LHS.get()->getType();
8241   QualType RHSTy = RHS.get()->getType();
8242 
8243   // get the "pointed to" types
8244   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8245   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8246 
8247   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8248   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8249     // Figure out necessary qualifiers (C99 6.5.15p6)
8250     QualType destPointee
8251       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8252     QualType destType = S.Context.getPointerType(destPointee);
8253     // Add qualifiers if necessary.
8254     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8255     // Promote to void*.
8256     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8257     return destType;
8258   }
8259   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8260     QualType destPointee
8261       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8262     QualType destType = S.Context.getPointerType(destPointee);
8263     // Add qualifiers if necessary.
8264     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8265     // Promote to void*.
8266     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8267     return destType;
8268   }
8269 
8270   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8271 }
8272 
8273 /// Return false if the first expression is not an integer and the second
8274 /// expression is not a pointer, true otherwise.
8275 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8276                                         Expr* PointerExpr, SourceLocation Loc,
8277                                         bool IsIntFirstExpr) {
8278   if (!PointerExpr->getType()->isPointerType() ||
8279       !Int.get()->getType()->isIntegerType())
8280     return false;
8281 
8282   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8283   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8284 
8285   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8286     << Expr1->getType() << Expr2->getType()
8287     << Expr1->getSourceRange() << Expr2->getSourceRange();
8288   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8289                             CK_IntegralToPointer);
8290   return true;
8291 }
8292 
8293 /// Simple conversion between integer and floating point types.
8294 ///
8295 /// Used when handling the OpenCL conditional operator where the
8296 /// condition is a vector while the other operands are scalar.
8297 ///
8298 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8299 /// types are either integer or floating type. Between the two
8300 /// operands, the type with the higher rank is defined as the "result
8301 /// type". The other operand needs to be promoted to the same type. No
8302 /// other type promotion is allowed. We cannot use
8303 /// UsualArithmeticConversions() for this purpose, since it always
8304 /// promotes promotable types.
8305 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8306                                             ExprResult &RHS,
8307                                             SourceLocation QuestionLoc) {
8308   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8309   if (LHS.isInvalid())
8310     return QualType();
8311   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8312   if (RHS.isInvalid())
8313     return QualType();
8314 
8315   // For conversion purposes, we ignore any qualifiers.
8316   // For example, "const float" and "float" are equivalent.
8317   QualType LHSType =
8318     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8319   QualType RHSType =
8320     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8321 
8322   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8323     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8324       << LHSType << LHS.get()->getSourceRange();
8325     return QualType();
8326   }
8327 
8328   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8329     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8330       << RHSType << RHS.get()->getSourceRange();
8331     return QualType();
8332   }
8333 
8334   // If both types are identical, no conversion is needed.
8335   if (LHSType == RHSType)
8336     return LHSType;
8337 
8338   // Now handle "real" floating types (i.e. float, double, long double).
8339   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8340     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8341                                  /*IsCompAssign = */ false);
8342 
8343   // Finally, we have two differing integer types.
8344   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8345   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8346 }
8347 
8348 /// Convert scalar operands to a vector that matches the
8349 ///        condition in length.
8350 ///
8351 /// Used when handling the OpenCL conditional operator where the
8352 /// condition is a vector while the other operands are scalar.
8353 ///
8354 /// We first compute the "result type" for the scalar operands
8355 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8356 /// into a vector of that type where the length matches the condition
8357 /// vector type. s6.11.6 requires that the element types of the result
8358 /// and the condition must have the same number of bits.
8359 static QualType
8360 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8361                               QualType CondTy, SourceLocation QuestionLoc) {
8362   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8363   if (ResTy.isNull()) return QualType();
8364 
8365   const VectorType *CV = CondTy->getAs<VectorType>();
8366   assert(CV);
8367 
8368   // Determine the vector result type
8369   unsigned NumElements = CV->getNumElements();
8370   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8371 
8372   // Ensure that all types have the same number of bits
8373   if (S.Context.getTypeSize(CV->getElementType())
8374       != S.Context.getTypeSize(ResTy)) {
8375     // Since VectorTy is created internally, it does not pretty print
8376     // with an OpenCL name. Instead, we just print a description.
8377     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8378     SmallString<64> Str;
8379     llvm::raw_svector_ostream OS(Str);
8380     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8381     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8382       << CondTy << OS.str();
8383     return QualType();
8384   }
8385 
8386   // Convert operands to the vector result type
8387   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8388   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8389 
8390   return VectorTy;
8391 }
8392 
8393 /// Return false if this is a valid OpenCL condition vector
8394 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8395                                        SourceLocation QuestionLoc) {
8396   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8397   // integral type.
8398   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8399   assert(CondTy);
8400   QualType EleTy = CondTy->getElementType();
8401   if (EleTy->isIntegerType()) return false;
8402 
8403   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8404     << Cond->getType() << Cond->getSourceRange();
8405   return true;
8406 }
8407 
8408 /// Return false if the vector condition type and the vector
8409 ///        result type are compatible.
8410 ///
8411 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8412 /// number of elements, and their element types have the same number
8413 /// of bits.
8414 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8415                               SourceLocation QuestionLoc) {
8416   const VectorType *CV = CondTy->getAs<VectorType>();
8417   const VectorType *RV = VecResTy->getAs<VectorType>();
8418   assert(CV && RV);
8419 
8420   if (CV->getNumElements() != RV->getNumElements()) {
8421     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8422       << CondTy << VecResTy;
8423     return true;
8424   }
8425 
8426   QualType CVE = CV->getElementType();
8427   QualType RVE = RV->getElementType();
8428 
8429   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8430     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8431       << CondTy << VecResTy;
8432     return true;
8433   }
8434 
8435   return false;
8436 }
8437 
8438 /// Return the resulting type for the conditional operator in
8439 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8440 ///        s6.3.i) when the condition is a vector type.
8441 static QualType
8442 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8443                              ExprResult &LHS, ExprResult &RHS,
8444                              SourceLocation QuestionLoc) {
8445   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8446   if (Cond.isInvalid())
8447     return QualType();
8448   QualType CondTy = Cond.get()->getType();
8449 
8450   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8451     return QualType();
8452 
8453   // If either operand is a vector then find the vector type of the
8454   // result as specified in OpenCL v1.1 s6.3.i.
8455   if (LHS.get()->getType()->isVectorType() ||
8456       RHS.get()->getType()->isVectorType()) {
8457     bool IsBoolVecLang =
8458         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8459     QualType VecResTy =
8460         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8461                               /*isCompAssign*/ false,
8462                               /*AllowBothBool*/ true,
8463                               /*AllowBoolConversions*/ false,
8464                               /*AllowBooleanOperation*/ IsBoolVecLang,
8465                               /*ReportInvalid*/ true);
8466     if (VecResTy.isNull())
8467       return QualType();
8468     // The result type must match the condition type as specified in
8469     // OpenCL v1.1 s6.11.6.
8470     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8471       return QualType();
8472     return VecResTy;
8473   }
8474 
8475   // Both operands are scalar.
8476   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8477 }
8478 
8479 /// Return true if the Expr is block type
8480 static bool checkBlockType(Sema &S, const Expr *E) {
8481   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8482     QualType Ty = CE->getCallee()->getType();
8483     if (Ty->isBlockPointerType()) {
8484       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8485       return true;
8486     }
8487   }
8488   return false;
8489 }
8490 
8491 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8492 /// In that case, LHS = cond.
8493 /// C99 6.5.15
8494 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8495                                         ExprResult &RHS, ExprValueKind &VK,
8496                                         ExprObjectKind &OK,
8497                                         SourceLocation QuestionLoc) {
8498 
8499   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8500   if (!LHSResult.isUsable()) return QualType();
8501   LHS = LHSResult;
8502 
8503   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8504   if (!RHSResult.isUsable()) return QualType();
8505   RHS = RHSResult;
8506 
8507   // C++ is sufficiently different to merit its own checker.
8508   if (getLangOpts().CPlusPlus)
8509     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8510 
8511   VK = VK_PRValue;
8512   OK = OK_Ordinary;
8513 
8514   if (Context.isDependenceAllowed() &&
8515       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8516        RHS.get()->isTypeDependent())) {
8517     assert(!getLangOpts().CPlusPlus);
8518     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8519             RHS.get()->containsErrors()) &&
8520            "should only occur in error-recovery path.");
8521     return Context.DependentTy;
8522   }
8523 
8524   // The OpenCL operator with a vector condition is sufficiently
8525   // different to merit its own checker.
8526   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8527       Cond.get()->getType()->isExtVectorType())
8528     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8529 
8530   // First, check the condition.
8531   Cond = UsualUnaryConversions(Cond.get());
8532   if (Cond.isInvalid())
8533     return QualType();
8534   if (checkCondition(*this, Cond.get(), QuestionLoc))
8535     return QualType();
8536 
8537   // Now check the two expressions.
8538   if (LHS.get()->getType()->isVectorType() ||
8539       RHS.get()->getType()->isVectorType())
8540     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8541                                /*AllowBothBool*/ true,
8542                                /*AllowBoolConversions*/ false,
8543                                /*AllowBooleanOperation*/ false,
8544                                /*ReportInvalid*/ true);
8545 
8546   QualType ResTy =
8547       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8548   if (LHS.isInvalid() || RHS.isInvalid())
8549     return QualType();
8550 
8551   QualType LHSTy = LHS.get()->getType();
8552   QualType RHSTy = RHS.get()->getType();
8553 
8554   // Diagnose attempts to convert between __ibm128, __float128 and long double
8555   // where such conversions currently can't be handled.
8556   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8557     Diag(QuestionLoc,
8558          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8559       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8560     return QualType();
8561   }
8562 
8563   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8564   // selection operator (?:).
8565   if (getLangOpts().OpenCL &&
8566       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8567     return QualType();
8568   }
8569 
8570   // If both operands have arithmetic type, do the usual arithmetic conversions
8571   // to find a common type: C99 6.5.15p3,5.
8572   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8573     // Disallow invalid arithmetic conversions, such as those between bit-
8574     // precise integers types of different sizes, or between a bit-precise
8575     // integer and another type.
8576     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8577       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8578           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8579           << RHS.get()->getSourceRange();
8580       return QualType();
8581     }
8582 
8583     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8584     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8585 
8586     return ResTy;
8587   }
8588 
8589   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8590   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8591     return LHSTy;
8592   }
8593 
8594   // If both operands are the same structure or union type, the result is that
8595   // type.
8596   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8597     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8598       if (LHSRT->getDecl() == RHSRT->getDecl())
8599         // "If both the operands have structure or union type, the result has
8600         // that type."  This implies that CV qualifiers are dropped.
8601         return LHSTy.getUnqualifiedType();
8602     // FIXME: Type of conditional expression must be complete in C mode.
8603   }
8604 
8605   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8606   // The following || allows only one side to be void (a GCC-ism).
8607   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8608     return checkConditionalVoidType(*this, LHS, RHS);
8609   }
8610 
8611   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8612   // the type of the other operand."
8613   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8614   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8615 
8616   // All objective-c pointer type analysis is done here.
8617   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8618                                                         QuestionLoc);
8619   if (LHS.isInvalid() || RHS.isInvalid())
8620     return QualType();
8621   if (!compositeType.isNull())
8622     return compositeType;
8623 
8624 
8625   // Handle block pointer types.
8626   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8627     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8628                                                      QuestionLoc);
8629 
8630   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8631   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8632     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8633                                                        QuestionLoc);
8634 
8635   // GCC compatibility: soften pointer/integer mismatch.  Note that
8636   // null pointers have been filtered out by this point.
8637   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8638       /*IsIntFirstExpr=*/true))
8639     return RHSTy;
8640   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8641       /*IsIntFirstExpr=*/false))
8642     return LHSTy;
8643 
8644   // Allow ?: operations in which both operands have the same
8645   // built-in sizeless type.
8646   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8647     return LHSTy;
8648 
8649   // Emit a better diagnostic if one of the expressions is a null pointer
8650   // constant and the other is not a pointer type. In this case, the user most
8651   // likely forgot to take the address of the other expression.
8652   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8653     return QualType();
8654 
8655   // Otherwise, the operands are not compatible.
8656   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8657     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8658     << RHS.get()->getSourceRange();
8659   return QualType();
8660 }
8661 
8662 /// FindCompositeObjCPointerType - Helper method to find composite type of
8663 /// two objective-c pointer types of the two input expressions.
8664 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8665                                             SourceLocation QuestionLoc) {
8666   QualType LHSTy = LHS.get()->getType();
8667   QualType RHSTy = RHS.get()->getType();
8668 
8669   // Handle things like Class and struct objc_class*.  Here we case the result
8670   // to the pseudo-builtin, because that will be implicitly cast back to the
8671   // redefinition type if an attempt is made to access its fields.
8672   if (LHSTy->isObjCClassType() &&
8673       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8674     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8675     return LHSTy;
8676   }
8677   if (RHSTy->isObjCClassType() &&
8678       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8679     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8680     return RHSTy;
8681   }
8682   // And the same for struct objc_object* / id
8683   if (LHSTy->isObjCIdType() &&
8684       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8685     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8686     return LHSTy;
8687   }
8688   if (RHSTy->isObjCIdType() &&
8689       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8690     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8691     return RHSTy;
8692   }
8693   // And the same for struct objc_selector* / SEL
8694   if (Context.isObjCSelType(LHSTy) &&
8695       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8696     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8697     return LHSTy;
8698   }
8699   if (Context.isObjCSelType(RHSTy) &&
8700       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8701     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8702     return RHSTy;
8703   }
8704   // Check constraints for Objective-C object pointers types.
8705   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8706 
8707     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8708       // Two identical object pointer types are always compatible.
8709       return LHSTy;
8710     }
8711     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8712     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8713     QualType compositeType = LHSTy;
8714 
8715     // If both operands are interfaces and either operand can be
8716     // assigned to the other, use that type as the composite
8717     // type. This allows
8718     //   xxx ? (A*) a : (B*) b
8719     // where B is a subclass of A.
8720     //
8721     // Additionally, as for assignment, if either type is 'id'
8722     // allow silent coercion. Finally, if the types are
8723     // incompatible then make sure to use 'id' as the composite
8724     // type so the result is acceptable for sending messages to.
8725 
8726     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8727     // It could return the composite type.
8728     if (!(compositeType =
8729           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8730       // Nothing more to do.
8731     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8732       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8733     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8734       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8735     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8736                 RHSOPT->isObjCQualifiedIdType()) &&
8737                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8738                                                          true)) {
8739       // Need to handle "id<xx>" explicitly.
8740       // GCC allows qualified id and any Objective-C type to devolve to
8741       // id. Currently localizing to here until clear this should be
8742       // part of ObjCQualifiedIdTypesAreCompatible.
8743       compositeType = Context.getObjCIdType();
8744     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8745       compositeType = Context.getObjCIdType();
8746     } else {
8747       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8748       << LHSTy << RHSTy
8749       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8750       QualType incompatTy = Context.getObjCIdType();
8751       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8752       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8753       return incompatTy;
8754     }
8755     // The object pointer types are compatible.
8756     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8757     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8758     return compositeType;
8759   }
8760   // Check Objective-C object pointer types and 'void *'
8761   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8762     if (getLangOpts().ObjCAutoRefCount) {
8763       // ARC forbids the implicit conversion of object pointers to 'void *',
8764       // so these types are not compatible.
8765       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8766           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8767       LHS = RHS = true;
8768       return QualType();
8769     }
8770     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8771     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8772     QualType destPointee
8773     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8774     QualType destType = Context.getPointerType(destPointee);
8775     // Add qualifiers if necessary.
8776     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8777     // Promote to void*.
8778     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8779     return destType;
8780   }
8781   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8782     if (getLangOpts().ObjCAutoRefCount) {
8783       // ARC forbids the implicit conversion of object pointers to 'void *',
8784       // so these types are not compatible.
8785       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8786           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8787       LHS = RHS = true;
8788       return QualType();
8789     }
8790     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8791     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8792     QualType destPointee
8793     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8794     QualType destType = Context.getPointerType(destPointee);
8795     // Add qualifiers if necessary.
8796     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8797     // Promote to void*.
8798     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8799     return destType;
8800   }
8801   return QualType();
8802 }
8803 
8804 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8805 /// ParenRange in parentheses.
8806 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8807                                const PartialDiagnostic &Note,
8808                                SourceRange ParenRange) {
8809   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8810   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8811       EndLoc.isValid()) {
8812     Self.Diag(Loc, Note)
8813       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8814       << FixItHint::CreateInsertion(EndLoc, ")");
8815   } else {
8816     // We can't display the parentheses, so just show the bare note.
8817     Self.Diag(Loc, Note) << ParenRange;
8818   }
8819 }
8820 
8821 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8822   return BinaryOperator::isAdditiveOp(Opc) ||
8823          BinaryOperator::isMultiplicativeOp(Opc) ||
8824          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8825   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8826   // not any of the logical operators.  Bitwise-xor is commonly used as a
8827   // logical-xor because there is no logical-xor operator.  The logical
8828   // operators, including uses of xor, have a high false positive rate for
8829   // precedence warnings.
8830 }
8831 
8832 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8833 /// expression, either using a built-in or overloaded operator,
8834 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8835 /// expression.
8836 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8837                                    Expr **RHSExprs) {
8838   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8839   E = E->IgnoreImpCasts();
8840   E = E->IgnoreConversionOperatorSingleStep();
8841   E = E->IgnoreImpCasts();
8842   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8843     E = MTE->getSubExpr();
8844     E = E->IgnoreImpCasts();
8845   }
8846 
8847   // Built-in binary operator.
8848   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8849     if (IsArithmeticOp(OP->getOpcode())) {
8850       *Opcode = OP->getOpcode();
8851       *RHSExprs = OP->getRHS();
8852       return true;
8853     }
8854   }
8855 
8856   // Overloaded operator.
8857   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8858     if (Call->getNumArgs() != 2)
8859       return false;
8860 
8861     // Make sure this is really a binary operator that is safe to pass into
8862     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8863     OverloadedOperatorKind OO = Call->getOperator();
8864     if (OO < OO_Plus || OO > OO_Arrow ||
8865         OO == OO_PlusPlus || OO == OO_MinusMinus)
8866       return false;
8867 
8868     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8869     if (IsArithmeticOp(OpKind)) {
8870       *Opcode = OpKind;
8871       *RHSExprs = Call->getArg(1);
8872       return true;
8873     }
8874   }
8875 
8876   return false;
8877 }
8878 
8879 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8880 /// or is a logical expression such as (x==y) which has int type, but is
8881 /// commonly interpreted as boolean.
8882 static bool ExprLooksBoolean(Expr *E) {
8883   E = E->IgnoreParenImpCasts();
8884 
8885   if (E->getType()->isBooleanType())
8886     return true;
8887   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8888     return OP->isComparisonOp() || OP->isLogicalOp();
8889   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8890     return OP->getOpcode() == UO_LNot;
8891   if (E->getType()->isPointerType())
8892     return true;
8893   // FIXME: What about overloaded operator calls returning "unspecified boolean
8894   // type"s (commonly pointer-to-members)?
8895 
8896   return false;
8897 }
8898 
8899 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8900 /// and binary operator are mixed in a way that suggests the programmer assumed
8901 /// the conditional operator has higher precedence, for example:
8902 /// "int x = a + someBinaryCondition ? 1 : 2".
8903 static void DiagnoseConditionalPrecedence(Sema &Self,
8904                                           SourceLocation OpLoc,
8905                                           Expr *Condition,
8906                                           Expr *LHSExpr,
8907                                           Expr *RHSExpr) {
8908   BinaryOperatorKind CondOpcode;
8909   Expr *CondRHS;
8910 
8911   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8912     return;
8913   if (!ExprLooksBoolean(CondRHS))
8914     return;
8915 
8916   // The condition is an arithmetic binary expression, with a right-
8917   // hand side that looks boolean, so warn.
8918 
8919   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8920                         ? diag::warn_precedence_bitwise_conditional
8921                         : diag::warn_precedence_conditional;
8922 
8923   Self.Diag(OpLoc, DiagID)
8924       << Condition->getSourceRange()
8925       << BinaryOperator::getOpcodeStr(CondOpcode);
8926 
8927   SuggestParentheses(
8928       Self, OpLoc,
8929       Self.PDiag(diag::note_precedence_silence)
8930           << BinaryOperator::getOpcodeStr(CondOpcode),
8931       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8932 
8933   SuggestParentheses(Self, OpLoc,
8934                      Self.PDiag(diag::note_precedence_conditional_first),
8935                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8936 }
8937 
8938 /// Compute the nullability of a conditional expression.
8939 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8940                                               QualType LHSTy, QualType RHSTy,
8941                                               ASTContext &Ctx) {
8942   if (!ResTy->isAnyPointerType())
8943     return ResTy;
8944 
8945   auto GetNullability = [&Ctx](QualType Ty) {
8946     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8947     if (Kind) {
8948       // For our purposes, treat _Nullable_result as _Nullable.
8949       if (*Kind == NullabilityKind::NullableResult)
8950         return NullabilityKind::Nullable;
8951       return *Kind;
8952     }
8953     return NullabilityKind::Unspecified;
8954   };
8955 
8956   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8957   NullabilityKind MergedKind;
8958 
8959   // Compute nullability of a binary conditional expression.
8960   if (IsBin) {
8961     if (LHSKind == NullabilityKind::NonNull)
8962       MergedKind = NullabilityKind::NonNull;
8963     else
8964       MergedKind = RHSKind;
8965   // Compute nullability of a normal conditional expression.
8966   } else {
8967     if (LHSKind == NullabilityKind::Nullable ||
8968         RHSKind == NullabilityKind::Nullable)
8969       MergedKind = NullabilityKind::Nullable;
8970     else if (LHSKind == NullabilityKind::NonNull)
8971       MergedKind = RHSKind;
8972     else if (RHSKind == NullabilityKind::NonNull)
8973       MergedKind = LHSKind;
8974     else
8975       MergedKind = NullabilityKind::Unspecified;
8976   }
8977 
8978   // Return if ResTy already has the correct nullability.
8979   if (GetNullability(ResTy) == MergedKind)
8980     return ResTy;
8981 
8982   // Strip all nullability from ResTy.
8983   while (ResTy->getNullability(Ctx))
8984     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8985 
8986   // Create a new AttributedType with the new nullability kind.
8987   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8988   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8989 }
8990 
8991 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8992 /// in the case of a the GNU conditional expr extension.
8993 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8994                                     SourceLocation ColonLoc,
8995                                     Expr *CondExpr, Expr *LHSExpr,
8996                                     Expr *RHSExpr) {
8997   if (!Context.isDependenceAllowed()) {
8998     // C cannot handle TypoExpr nodes in the condition because it
8999     // doesn't handle dependent types properly, so make sure any TypoExprs have
9000     // been dealt with before checking the operands.
9001     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9002     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9003     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9004 
9005     if (!CondResult.isUsable())
9006       return ExprError();
9007 
9008     if (LHSExpr) {
9009       if (!LHSResult.isUsable())
9010         return ExprError();
9011     }
9012 
9013     if (!RHSResult.isUsable())
9014       return ExprError();
9015 
9016     CondExpr = CondResult.get();
9017     LHSExpr = LHSResult.get();
9018     RHSExpr = RHSResult.get();
9019   }
9020 
9021   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9022   // was the condition.
9023   OpaqueValueExpr *opaqueValue = nullptr;
9024   Expr *commonExpr = nullptr;
9025   if (!LHSExpr) {
9026     commonExpr = CondExpr;
9027     // Lower out placeholder types first.  This is important so that we don't
9028     // try to capture a placeholder. This happens in few cases in C++; such
9029     // as Objective-C++'s dictionary subscripting syntax.
9030     if (commonExpr->hasPlaceholderType()) {
9031       ExprResult result = CheckPlaceholderExpr(commonExpr);
9032       if (!result.isUsable()) return ExprError();
9033       commonExpr = result.get();
9034     }
9035     // We usually want to apply unary conversions *before* saving, except
9036     // in the special case of a C++ l-value conditional.
9037     if (!(getLangOpts().CPlusPlus
9038           && !commonExpr->isTypeDependent()
9039           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9040           && commonExpr->isGLValue()
9041           && commonExpr->isOrdinaryOrBitFieldObject()
9042           && RHSExpr->isOrdinaryOrBitFieldObject()
9043           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9044       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9045       if (commonRes.isInvalid())
9046         return ExprError();
9047       commonExpr = commonRes.get();
9048     }
9049 
9050     // If the common expression is a class or array prvalue, materialize it
9051     // so that we can safely refer to it multiple times.
9052     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9053                                     commonExpr->getType()->isArrayType())) {
9054       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9055       if (MatExpr.isInvalid())
9056         return ExprError();
9057       commonExpr = MatExpr.get();
9058     }
9059 
9060     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9061                                                 commonExpr->getType(),
9062                                                 commonExpr->getValueKind(),
9063                                                 commonExpr->getObjectKind(),
9064                                                 commonExpr);
9065     LHSExpr = CondExpr = opaqueValue;
9066   }
9067 
9068   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9069   ExprValueKind VK = VK_PRValue;
9070   ExprObjectKind OK = OK_Ordinary;
9071   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9072   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9073                                              VK, OK, QuestionLoc);
9074   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9075       RHS.isInvalid())
9076     return ExprError();
9077 
9078   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9079                                 RHS.get());
9080 
9081   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9082 
9083   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9084                                          Context);
9085 
9086   if (!commonExpr)
9087     return new (Context)
9088         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9089                             RHS.get(), result, VK, OK);
9090 
9091   return new (Context) BinaryConditionalOperator(
9092       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9093       ColonLoc, result, VK, OK);
9094 }
9095 
9096 // Check if we have a conversion between incompatible cmse function pointer
9097 // types, that is, a conversion between a function pointer with the
9098 // cmse_nonsecure_call attribute and one without.
9099 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9100                                           QualType ToType) {
9101   if (const auto *ToFn =
9102           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9103     if (const auto *FromFn =
9104             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9105       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9106       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9107 
9108       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9109     }
9110   }
9111   return false;
9112 }
9113 
9114 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9115 // being closely modeled after the C99 spec:-). The odd characteristic of this
9116 // routine is it effectively iqnores the qualifiers on the top level pointee.
9117 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9118 // FIXME: add a couple examples in this comment.
9119 static Sema::AssignConvertType
9120 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9121   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9122   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9123 
9124   // get the "pointed to" type (ignoring qualifiers at the top level)
9125   const Type *lhptee, *rhptee;
9126   Qualifiers lhq, rhq;
9127   std::tie(lhptee, lhq) =
9128       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9129   std::tie(rhptee, rhq) =
9130       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9131 
9132   Sema::AssignConvertType ConvTy = Sema::Compatible;
9133 
9134   // C99 6.5.16.1p1: This following citation is common to constraints
9135   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9136   // qualifiers of the type *pointed to* by the right;
9137 
9138   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9139   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9140       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9141     // Ignore lifetime for further calculation.
9142     lhq.removeObjCLifetime();
9143     rhq.removeObjCLifetime();
9144   }
9145 
9146   if (!lhq.compatiblyIncludes(rhq)) {
9147     // Treat address-space mismatches as fatal.
9148     if (!lhq.isAddressSpaceSupersetOf(rhq))
9149       return Sema::IncompatiblePointerDiscardsQualifiers;
9150 
9151     // It's okay to add or remove GC or lifetime qualifiers when converting to
9152     // and from void*.
9153     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9154                         .compatiblyIncludes(
9155                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9156              && (lhptee->isVoidType() || rhptee->isVoidType()))
9157       ; // keep old
9158 
9159     // Treat lifetime mismatches as fatal.
9160     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9161       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9162 
9163     // For GCC/MS compatibility, other qualifier mismatches are treated
9164     // as still compatible in C.
9165     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9166   }
9167 
9168   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9169   // incomplete type and the other is a pointer to a qualified or unqualified
9170   // version of void...
9171   if (lhptee->isVoidType()) {
9172     if (rhptee->isIncompleteOrObjectType())
9173       return ConvTy;
9174 
9175     // As an extension, we allow cast to/from void* to function pointer.
9176     assert(rhptee->isFunctionType());
9177     return Sema::FunctionVoidPointer;
9178   }
9179 
9180   if (rhptee->isVoidType()) {
9181     if (lhptee->isIncompleteOrObjectType())
9182       return ConvTy;
9183 
9184     // As an extension, we allow cast to/from void* to function pointer.
9185     assert(lhptee->isFunctionType());
9186     return Sema::FunctionVoidPointer;
9187   }
9188 
9189   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9190   // unqualified versions of compatible types, ...
9191   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9192   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9193     // Check if the pointee types are compatible ignoring the sign.
9194     // We explicitly check for char so that we catch "char" vs
9195     // "unsigned char" on systems where "char" is unsigned.
9196     if (lhptee->isCharType())
9197       ltrans = S.Context.UnsignedCharTy;
9198     else if (lhptee->hasSignedIntegerRepresentation())
9199       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9200 
9201     if (rhptee->isCharType())
9202       rtrans = S.Context.UnsignedCharTy;
9203     else if (rhptee->hasSignedIntegerRepresentation())
9204       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9205 
9206     if (ltrans == rtrans) {
9207       // Types are compatible ignoring the sign. Qualifier incompatibility
9208       // takes priority over sign incompatibility because the sign
9209       // warning can be disabled.
9210       if (ConvTy != Sema::Compatible)
9211         return ConvTy;
9212 
9213       return Sema::IncompatiblePointerSign;
9214     }
9215 
9216     // If we are a multi-level pointer, it's possible that our issue is simply
9217     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9218     // the eventual target type is the same and the pointers have the same
9219     // level of indirection, this must be the issue.
9220     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9221       do {
9222         std::tie(lhptee, lhq) =
9223           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9224         std::tie(rhptee, rhq) =
9225           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9226 
9227         // Inconsistent address spaces at this point is invalid, even if the
9228         // address spaces would be compatible.
9229         // FIXME: This doesn't catch address space mismatches for pointers of
9230         // different nesting levels, like:
9231         //   __local int *** a;
9232         //   int ** b = a;
9233         // It's not clear how to actually determine when such pointers are
9234         // invalidly incompatible.
9235         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9236           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9237 
9238       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9239 
9240       if (lhptee == rhptee)
9241         return Sema::IncompatibleNestedPointerQualifiers;
9242     }
9243 
9244     // General pointer incompatibility takes priority over qualifiers.
9245     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9246       return Sema::IncompatibleFunctionPointer;
9247     return Sema::IncompatiblePointer;
9248   }
9249   if (!S.getLangOpts().CPlusPlus &&
9250       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9251     return Sema::IncompatibleFunctionPointer;
9252   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9253     return Sema::IncompatibleFunctionPointer;
9254   return ConvTy;
9255 }
9256 
9257 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9258 /// block pointer types are compatible or whether a block and normal pointer
9259 /// are compatible. It is more restrict than comparing two function pointer
9260 // types.
9261 static Sema::AssignConvertType
9262 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9263                                     QualType RHSType) {
9264   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9265   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9266 
9267   QualType lhptee, rhptee;
9268 
9269   // get the "pointed to" type (ignoring qualifiers at the top level)
9270   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9271   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9272 
9273   // In C++, the types have to match exactly.
9274   if (S.getLangOpts().CPlusPlus)
9275     return Sema::IncompatibleBlockPointer;
9276 
9277   Sema::AssignConvertType ConvTy = Sema::Compatible;
9278 
9279   // For blocks we enforce that qualifiers are identical.
9280   Qualifiers LQuals = lhptee.getLocalQualifiers();
9281   Qualifiers RQuals = rhptee.getLocalQualifiers();
9282   if (S.getLangOpts().OpenCL) {
9283     LQuals.removeAddressSpace();
9284     RQuals.removeAddressSpace();
9285   }
9286   if (LQuals != RQuals)
9287     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9288 
9289   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9290   // assignment.
9291   // The current behavior is similar to C++ lambdas. A block might be
9292   // assigned to a variable iff its return type and parameters are compatible
9293   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9294   // an assignment. Presumably it should behave in way that a function pointer
9295   // assignment does in C, so for each parameter and return type:
9296   //  * CVR and address space of LHS should be a superset of CVR and address
9297   //  space of RHS.
9298   //  * unqualified types should be compatible.
9299   if (S.getLangOpts().OpenCL) {
9300     if (!S.Context.typesAreBlockPointerCompatible(
9301             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9302             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9303       return Sema::IncompatibleBlockPointer;
9304   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9305     return Sema::IncompatibleBlockPointer;
9306 
9307   return ConvTy;
9308 }
9309 
9310 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9311 /// for assignment compatibility.
9312 static Sema::AssignConvertType
9313 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9314                                    QualType RHSType) {
9315   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9316   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9317 
9318   if (LHSType->isObjCBuiltinType()) {
9319     // Class is not compatible with ObjC object pointers.
9320     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9321         !RHSType->isObjCQualifiedClassType())
9322       return Sema::IncompatiblePointer;
9323     return Sema::Compatible;
9324   }
9325   if (RHSType->isObjCBuiltinType()) {
9326     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9327         !LHSType->isObjCQualifiedClassType())
9328       return Sema::IncompatiblePointer;
9329     return Sema::Compatible;
9330   }
9331   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9332   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9333 
9334   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9335       // make an exception for id<P>
9336       !LHSType->isObjCQualifiedIdType())
9337     return Sema::CompatiblePointerDiscardsQualifiers;
9338 
9339   if (S.Context.typesAreCompatible(LHSType, RHSType))
9340     return Sema::Compatible;
9341   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9342     return Sema::IncompatibleObjCQualifiedId;
9343   return Sema::IncompatiblePointer;
9344 }
9345 
9346 Sema::AssignConvertType
9347 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9348                                  QualType LHSType, QualType RHSType) {
9349   // Fake up an opaque expression.  We don't actually care about what
9350   // cast operations are required, so if CheckAssignmentConstraints
9351   // adds casts to this they'll be wasted, but fortunately that doesn't
9352   // usually happen on valid code.
9353   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9354   ExprResult RHSPtr = &RHSExpr;
9355   CastKind K;
9356 
9357   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9358 }
9359 
9360 /// This helper function returns true if QT is a vector type that has element
9361 /// type ElementType.
9362 static bool isVector(QualType QT, QualType ElementType) {
9363   if (const VectorType *VT = QT->getAs<VectorType>())
9364     return VT->getElementType().getCanonicalType() == ElementType;
9365   return false;
9366 }
9367 
9368 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9369 /// has code to accommodate several GCC extensions when type checking
9370 /// pointers. Here are some objectionable examples that GCC considers warnings:
9371 ///
9372 ///  int a, *pint;
9373 ///  short *pshort;
9374 ///  struct foo *pfoo;
9375 ///
9376 ///  pint = pshort; // warning: assignment from incompatible pointer type
9377 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9378 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9379 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9380 ///
9381 /// As a result, the code for dealing with pointers is more complex than the
9382 /// C99 spec dictates.
9383 ///
9384 /// Sets 'Kind' for any result kind except Incompatible.
9385 Sema::AssignConvertType
9386 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9387                                  CastKind &Kind, bool ConvertRHS) {
9388   QualType RHSType = RHS.get()->getType();
9389   QualType OrigLHSType = LHSType;
9390 
9391   // Get canonical types.  We're not formatting these types, just comparing
9392   // them.
9393   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9394   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9395 
9396   // Common case: no conversion required.
9397   if (LHSType == RHSType) {
9398     Kind = CK_NoOp;
9399     return Compatible;
9400   }
9401 
9402   // If the LHS has an __auto_type, there are no additional type constraints
9403   // to be worried about.
9404   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9405     if (AT->isGNUAutoType()) {
9406       Kind = CK_NoOp;
9407       return Compatible;
9408     }
9409   }
9410 
9411   // If we have an atomic type, try a non-atomic assignment, then just add an
9412   // atomic qualification step.
9413   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9414     Sema::AssignConvertType result =
9415       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9416     if (result != Compatible)
9417       return result;
9418     if (Kind != CK_NoOp && ConvertRHS)
9419       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9420     Kind = CK_NonAtomicToAtomic;
9421     return Compatible;
9422   }
9423 
9424   // If the left-hand side is a reference type, then we are in a
9425   // (rare!) case where we've allowed the use of references in C,
9426   // e.g., as a parameter type in a built-in function. In this case,
9427   // just make sure that the type referenced is compatible with the
9428   // right-hand side type. The caller is responsible for adjusting
9429   // LHSType so that the resulting expression does not have reference
9430   // type.
9431   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9432     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9433       Kind = CK_LValueBitCast;
9434       return Compatible;
9435     }
9436     return Incompatible;
9437   }
9438 
9439   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9440   // to the same ExtVector type.
9441   if (LHSType->isExtVectorType()) {
9442     if (RHSType->isExtVectorType())
9443       return Incompatible;
9444     if (RHSType->isArithmeticType()) {
9445       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9446       if (ConvertRHS)
9447         RHS = prepareVectorSplat(LHSType, RHS.get());
9448       Kind = CK_VectorSplat;
9449       return Compatible;
9450     }
9451   }
9452 
9453   // Conversions to or from vector type.
9454   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9455     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9456       // Allow assignments of an AltiVec vector type to an equivalent GCC
9457       // vector type and vice versa
9458       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9459         Kind = CK_BitCast;
9460         return Compatible;
9461       }
9462 
9463       // If we are allowing lax vector conversions, and LHS and RHS are both
9464       // vectors, the total size only needs to be the same. This is a bitcast;
9465       // no bits are changed but the result type is different.
9466       if (isLaxVectorConversion(RHSType, LHSType)) {
9467         Kind = CK_BitCast;
9468         return IncompatibleVectors;
9469       }
9470     }
9471 
9472     // When the RHS comes from another lax conversion (e.g. binops between
9473     // scalars and vectors) the result is canonicalized as a vector. When the
9474     // LHS is also a vector, the lax is allowed by the condition above. Handle
9475     // the case where LHS is a scalar.
9476     if (LHSType->isScalarType()) {
9477       const VectorType *VecType = RHSType->getAs<VectorType>();
9478       if (VecType && VecType->getNumElements() == 1 &&
9479           isLaxVectorConversion(RHSType, LHSType)) {
9480         ExprResult *VecExpr = &RHS;
9481         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9482         Kind = CK_BitCast;
9483         return Compatible;
9484       }
9485     }
9486 
9487     // Allow assignments between fixed-length and sizeless SVE vectors.
9488     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9489         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9490       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9491           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9492         Kind = CK_BitCast;
9493         return Compatible;
9494       }
9495 
9496     return Incompatible;
9497   }
9498 
9499   // Diagnose attempts to convert between __ibm128, __float128 and long double
9500   // where such conversions currently can't be handled.
9501   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9502     return Incompatible;
9503 
9504   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9505   // discards the imaginary part.
9506   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9507       !LHSType->getAs<ComplexType>())
9508     return Incompatible;
9509 
9510   // Arithmetic conversions.
9511   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9512       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9513     if (ConvertRHS)
9514       Kind = PrepareScalarCast(RHS, LHSType);
9515     return Compatible;
9516   }
9517 
9518   // Conversions to normal pointers.
9519   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9520     // U* -> T*
9521     if (isa<PointerType>(RHSType)) {
9522       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9523       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9524       if (AddrSpaceL != AddrSpaceR)
9525         Kind = CK_AddressSpaceConversion;
9526       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9527         Kind = CK_NoOp;
9528       else
9529         Kind = CK_BitCast;
9530       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9531     }
9532 
9533     // int -> T*
9534     if (RHSType->isIntegerType()) {
9535       Kind = CK_IntegralToPointer; // FIXME: null?
9536       return IntToPointer;
9537     }
9538 
9539     // C pointers are not compatible with ObjC object pointers,
9540     // with two exceptions:
9541     if (isa<ObjCObjectPointerType>(RHSType)) {
9542       //  - conversions to void*
9543       if (LHSPointer->getPointeeType()->isVoidType()) {
9544         Kind = CK_BitCast;
9545         return Compatible;
9546       }
9547 
9548       //  - conversions from 'Class' to the redefinition type
9549       if (RHSType->isObjCClassType() &&
9550           Context.hasSameType(LHSType,
9551                               Context.getObjCClassRedefinitionType())) {
9552         Kind = CK_BitCast;
9553         return Compatible;
9554       }
9555 
9556       Kind = CK_BitCast;
9557       return IncompatiblePointer;
9558     }
9559 
9560     // U^ -> void*
9561     if (RHSType->getAs<BlockPointerType>()) {
9562       if (LHSPointer->getPointeeType()->isVoidType()) {
9563         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9564         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9565                                 ->getPointeeType()
9566                                 .getAddressSpace();
9567         Kind =
9568             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9569         return Compatible;
9570       }
9571     }
9572 
9573     return Incompatible;
9574   }
9575 
9576   // Conversions to block pointers.
9577   if (isa<BlockPointerType>(LHSType)) {
9578     // U^ -> T^
9579     if (RHSType->isBlockPointerType()) {
9580       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9581                               ->getPointeeType()
9582                               .getAddressSpace();
9583       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9584                               ->getPointeeType()
9585                               .getAddressSpace();
9586       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9587       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9588     }
9589 
9590     // int or null -> T^
9591     if (RHSType->isIntegerType()) {
9592       Kind = CK_IntegralToPointer; // FIXME: null
9593       return IntToBlockPointer;
9594     }
9595 
9596     // id -> T^
9597     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9598       Kind = CK_AnyPointerToBlockPointerCast;
9599       return Compatible;
9600     }
9601 
9602     // void* -> T^
9603     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9604       if (RHSPT->getPointeeType()->isVoidType()) {
9605         Kind = CK_AnyPointerToBlockPointerCast;
9606         return Compatible;
9607       }
9608 
9609     return Incompatible;
9610   }
9611 
9612   // Conversions to Objective-C pointers.
9613   if (isa<ObjCObjectPointerType>(LHSType)) {
9614     // A* -> B*
9615     if (RHSType->isObjCObjectPointerType()) {
9616       Kind = CK_BitCast;
9617       Sema::AssignConvertType result =
9618         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9619       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9620           result == Compatible &&
9621           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9622         result = IncompatibleObjCWeakRef;
9623       return result;
9624     }
9625 
9626     // int or null -> A*
9627     if (RHSType->isIntegerType()) {
9628       Kind = CK_IntegralToPointer; // FIXME: null
9629       return IntToPointer;
9630     }
9631 
9632     // In general, C pointers are not compatible with ObjC object pointers,
9633     // with two exceptions:
9634     if (isa<PointerType>(RHSType)) {
9635       Kind = CK_CPointerToObjCPointerCast;
9636 
9637       //  - conversions from 'void*'
9638       if (RHSType->isVoidPointerType()) {
9639         return Compatible;
9640       }
9641 
9642       //  - conversions to 'Class' from its redefinition type
9643       if (LHSType->isObjCClassType() &&
9644           Context.hasSameType(RHSType,
9645                               Context.getObjCClassRedefinitionType())) {
9646         return Compatible;
9647       }
9648 
9649       return IncompatiblePointer;
9650     }
9651 
9652     // Only under strict condition T^ is compatible with an Objective-C pointer.
9653     if (RHSType->isBlockPointerType() &&
9654         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9655       if (ConvertRHS)
9656         maybeExtendBlockObject(RHS);
9657       Kind = CK_BlockPointerToObjCPointerCast;
9658       return Compatible;
9659     }
9660 
9661     return Incompatible;
9662   }
9663 
9664   // Conversions from pointers that are not covered by the above.
9665   if (isa<PointerType>(RHSType)) {
9666     // T* -> _Bool
9667     if (LHSType == Context.BoolTy) {
9668       Kind = CK_PointerToBoolean;
9669       return Compatible;
9670     }
9671 
9672     // T* -> int
9673     if (LHSType->isIntegerType()) {
9674       Kind = CK_PointerToIntegral;
9675       return PointerToInt;
9676     }
9677 
9678     return Incompatible;
9679   }
9680 
9681   // Conversions from Objective-C pointers that are not covered by the above.
9682   if (isa<ObjCObjectPointerType>(RHSType)) {
9683     // T* -> _Bool
9684     if (LHSType == Context.BoolTy) {
9685       Kind = CK_PointerToBoolean;
9686       return Compatible;
9687     }
9688 
9689     // T* -> int
9690     if (LHSType->isIntegerType()) {
9691       Kind = CK_PointerToIntegral;
9692       return PointerToInt;
9693     }
9694 
9695     return Incompatible;
9696   }
9697 
9698   // struct A -> struct B
9699   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9700     if (Context.typesAreCompatible(LHSType, RHSType)) {
9701       Kind = CK_NoOp;
9702       return Compatible;
9703     }
9704   }
9705 
9706   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9707     Kind = CK_IntToOCLSampler;
9708     return Compatible;
9709   }
9710 
9711   return Incompatible;
9712 }
9713 
9714 /// Constructs a transparent union from an expression that is
9715 /// used to initialize the transparent union.
9716 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9717                                       ExprResult &EResult, QualType UnionType,
9718                                       FieldDecl *Field) {
9719   // Build an initializer list that designates the appropriate member
9720   // of the transparent union.
9721   Expr *E = EResult.get();
9722   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9723                                                    E, SourceLocation());
9724   Initializer->setType(UnionType);
9725   Initializer->setInitializedFieldInUnion(Field);
9726 
9727   // Build a compound literal constructing a value of the transparent
9728   // union type from this initializer list.
9729   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9730   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9731                                         VK_PRValue, Initializer, false);
9732 }
9733 
9734 Sema::AssignConvertType
9735 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9736                                                ExprResult &RHS) {
9737   QualType RHSType = RHS.get()->getType();
9738 
9739   // If the ArgType is a Union type, we want to handle a potential
9740   // transparent_union GCC extension.
9741   const RecordType *UT = ArgType->getAsUnionType();
9742   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9743     return Incompatible;
9744 
9745   // The field to initialize within the transparent union.
9746   RecordDecl *UD = UT->getDecl();
9747   FieldDecl *InitField = nullptr;
9748   // It's compatible if the expression matches any of the fields.
9749   for (auto *it : UD->fields()) {
9750     if (it->getType()->isPointerType()) {
9751       // If the transparent union contains a pointer type, we allow:
9752       // 1) void pointer
9753       // 2) null pointer constant
9754       if (RHSType->isPointerType())
9755         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9756           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9757           InitField = it;
9758           break;
9759         }
9760 
9761       if (RHS.get()->isNullPointerConstant(Context,
9762                                            Expr::NPC_ValueDependentIsNull)) {
9763         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9764                                 CK_NullToPointer);
9765         InitField = it;
9766         break;
9767       }
9768     }
9769 
9770     CastKind Kind;
9771     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9772           == Compatible) {
9773       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9774       InitField = it;
9775       break;
9776     }
9777   }
9778 
9779   if (!InitField)
9780     return Incompatible;
9781 
9782   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9783   return Compatible;
9784 }
9785 
9786 Sema::AssignConvertType
9787 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9788                                        bool Diagnose,
9789                                        bool DiagnoseCFAudited,
9790                                        bool ConvertRHS) {
9791   // We need to be able to tell the caller whether we diagnosed a problem, if
9792   // they ask us to issue diagnostics.
9793   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9794 
9795   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9796   // we can't avoid *all* modifications at the moment, so we need some somewhere
9797   // to put the updated value.
9798   ExprResult LocalRHS = CallerRHS;
9799   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9800 
9801   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9802     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9803       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9804           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9805         Diag(RHS.get()->getExprLoc(),
9806              diag::warn_noderef_to_dereferenceable_pointer)
9807             << RHS.get()->getSourceRange();
9808       }
9809     }
9810   }
9811 
9812   if (getLangOpts().CPlusPlus) {
9813     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9814       // C++ 5.17p3: If the left operand is not of class type, the
9815       // expression is implicitly converted (C++ 4) to the
9816       // cv-unqualified type of the left operand.
9817       QualType RHSType = RHS.get()->getType();
9818       if (Diagnose) {
9819         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9820                                         AA_Assigning);
9821       } else {
9822         ImplicitConversionSequence ICS =
9823             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9824                                   /*SuppressUserConversions=*/false,
9825                                   AllowedExplicit::None,
9826                                   /*InOverloadResolution=*/false,
9827                                   /*CStyle=*/false,
9828                                   /*AllowObjCWritebackConversion=*/false);
9829         if (ICS.isFailure())
9830           return Incompatible;
9831         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9832                                         ICS, AA_Assigning);
9833       }
9834       if (RHS.isInvalid())
9835         return Incompatible;
9836       Sema::AssignConvertType result = Compatible;
9837       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9838           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9839         result = IncompatibleObjCWeakRef;
9840       return result;
9841     }
9842 
9843     // FIXME: Currently, we fall through and treat C++ classes like C
9844     // structures.
9845     // FIXME: We also fall through for atomics; not sure what should
9846     // happen there, though.
9847   } else if (RHS.get()->getType() == Context.OverloadTy) {
9848     // As a set of extensions to C, we support overloading on functions. These
9849     // functions need to be resolved here.
9850     DeclAccessPair DAP;
9851     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9852             RHS.get(), LHSType, /*Complain=*/false, DAP))
9853       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9854     else
9855       return Incompatible;
9856   }
9857 
9858   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9859   // a null pointer constant.
9860   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9861        LHSType->isBlockPointerType()) &&
9862       RHS.get()->isNullPointerConstant(Context,
9863                                        Expr::NPC_ValueDependentIsNull)) {
9864     if (Diagnose || ConvertRHS) {
9865       CastKind Kind;
9866       CXXCastPath Path;
9867       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9868                              /*IgnoreBaseAccess=*/false, Diagnose);
9869       if (ConvertRHS)
9870         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9871     }
9872     return Compatible;
9873   }
9874 
9875   // OpenCL queue_t type assignment.
9876   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9877                                  Context, Expr::NPC_ValueDependentIsNull)) {
9878     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9879     return Compatible;
9880   }
9881 
9882   // This check seems unnatural, however it is necessary to ensure the proper
9883   // conversion of functions/arrays. If the conversion were done for all
9884   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9885   // expressions that suppress this implicit conversion (&, sizeof).
9886   //
9887   // Suppress this for references: C++ 8.5.3p5.
9888   if (!LHSType->isReferenceType()) {
9889     // FIXME: We potentially allocate here even if ConvertRHS is false.
9890     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9891     if (RHS.isInvalid())
9892       return Incompatible;
9893   }
9894   CastKind Kind;
9895   Sema::AssignConvertType result =
9896     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9897 
9898   // C99 6.5.16.1p2: The value of the right operand is converted to the
9899   // type of the assignment expression.
9900   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9901   // so that we can use references in built-in functions even in C.
9902   // The getNonReferenceType() call makes sure that the resulting expression
9903   // does not have reference type.
9904   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9905     QualType Ty = LHSType.getNonLValueExprType(Context);
9906     Expr *E = RHS.get();
9907 
9908     // Check for various Objective-C errors. If we are not reporting
9909     // diagnostics and just checking for errors, e.g., during overload
9910     // resolution, return Incompatible to indicate the failure.
9911     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9912         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9913                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9914       if (!Diagnose)
9915         return Incompatible;
9916     }
9917     if (getLangOpts().ObjC &&
9918         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9919                                            E->getType(), E, Diagnose) ||
9920          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9921       if (!Diagnose)
9922         return Incompatible;
9923       // Replace the expression with a corrected version and continue so we
9924       // can find further errors.
9925       RHS = E;
9926       return Compatible;
9927     }
9928 
9929     if (ConvertRHS)
9930       RHS = ImpCastExprToType(E, Ty, Kind);
9931   }
9932 
9933   return result;
9934 }
9935 
9936 namespace {
9937 /// The original operand to an operator, prior to the application of the usual
9938 /// arithmetic conversions and converting the arguments of a builtin operator
9939 /// candidate.
9940 struct OriginalOperand {
9941   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9942     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9943       Op = MTE->getSubExpr();
9944     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9945       Op = BTE->getSubExpr();
9946     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9947       Orig = ICE->getSubExprAsWritten();
9948       Conversion = ICE->getConversionFunction();
9949     }
9950   }
9951 
9952   QualType getType() const { return Orig->getType(); }
9953 
9954   Expr *Orig;
9955   NamedDecl *Conversion;
9956 };
9957 }
9958 
9959 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9960                                ExprResult &RHS) {
9961   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9962 
9963   Diag(Loc, diag::err_typecheck_invalid_operands)
9964     << OrigLHS.getType() << OrigRHS.getType()
9965     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9966 
9967   // If a user-defined conversion was applied to either of the operands prior
9968   // to applying the built-in operator rules, tell the user about it.
9969   if (OrigLHS.Conversion) {
9970     Diag(OrigLHS.Conversion->getLocation(),
9971          diag::note_typecheck_invalid_operands_converted)
9972       << 0 << LHS.get()->getType();
9973   }
9974   if (OrigRHS.Conversion) {
9975     Diag(OrigRHS.Conversion->getLocation(),
9976          diag::note_typecheck_invalid_operands_converted)
9977       << 1 << RHS.get()->getType();
9978   }
9979 
9980   return QualType();
9981 }
9982 
9983 // Diagnose cases where a scalar was implicitly converted to a vector and
9984 // diagnose the underlying types. Otherwise, diagnose the error
9985 // as invalid vector logical operands for non-C++ cases.
9986 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9987                                             ExprResult &RHS) {
9988   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9989   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9990 
9991   bool LHSNatVec = LHSType->isVectorType();
9992   bool RHSNatVec = RHSType->isVectorType();
9993 
9994   if (!(LHSNatVec && RHSNatVec)) {
9995     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9996     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9997     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9998         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9999         << Vector->getSourceRange();
10000     return QualType();
10001   }
10002 
10003   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10004       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10005       << RHS.get()->getSourceRange();
10006 
10007   return QualType();
10008 }
10009 
10010 /// Try to convert a value of non-vector type to a vector type by converting
10011 /// the type to the element type of the vector and then performing a splat.
10012 /// If the language is OpenCL, we only use conversions that promote scalar
10013 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10014 /// for float->int.
10015 ///
10016 /// OpenCL V2.0 6.2.6.p2:
10017 /// An error shall occur if any scalar operand type has greater rank
10018 /// than the type of the vector element.
10019 ///
10020 /// \param scalar - if non-null, actually perform the conversions
10021 /// \return true if the operation fails (but without diagnosing the failure)
10022 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10023                                      QualType scalarTy,
10024                                      QualType vectorEltTy,
10025                                      QualType vectorTy,
10026                                      unsigned &DiagID) {
10027   // The conversion to apply to the scalar before splatting it,
10028   // if necessary.
10029   CastKind scalarCast = CK_NoOp;
10030 
10031   if (vectorEltTy->isIntegralType(S.Context)) {
10032     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10033         (scalarTy->isIntegerType() &&
10034          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10035       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10036       return true;
10037     }
10038     if (!scalarTy->isIntegralType(S.Context))
10039       return true;
10040     scalarCast = CK_IntegralCast;
10041   } else if (vectorEltTy->isRealFloatingType()) {
10042     if (scalarTy->isRealFloatingType()) {
10043       if (S.getLangOpts().OpenCL &&
10044           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10045         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10046         return true;
10047       }
10048       scalarCast = CK_FloatingCast;
10049     }
10050     else if (scalarTy->isIntegralType(S.Context))
10051       scalarCast = CK_IntegralToFloating;
10052     else
10053       return true;
10054   } else {
10055     return true;
10056   }
10057 
10058   // Adjust scalar if desired.
10059   if (scalar) {
10060     if (scalarCast != CK_NoOp)
10061       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10062     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10063   }
10064   return false;
10065 }
10066 
10067 /// Convert vector E to a vector with the same number of elements but different
10068 /// element type.
10069 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10070   const auto *VecTy = E->getType()->getAs<VectorType>();
10071   assert(VecTy && "Expression E must be a vector");
10072   QualType NewVecTy = S.Context.getVectorType(ElementType,
10073                                               VecTy->getNumElements(),
10074                                               VecTy->getVectorKind());
10075 
10076   // Look through the implicit cast. Return the subexpression if its type is
10077   // NewVecTy.
10078   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10079     if (ICE->getSubExpr()->getType() == NewVecTy)
10080       return ICE->getSubExpr();
10081 
10082   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10083   return S.ImpCastExprToType(E, NewVecTy, Cast);
10084 }
10085 
10086 /// Test if a (constant) integer Int can be casted to another integer type
10087 /// IntTy without losing precision.
10088 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10089                                       QualType OtherIntTy) {
10090   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10091 
10092   // Reject cases where the value of the Int is unknown as that would
10093   // possibly cause truncation, but accept cases where the scalar can be
10094   // demoted without loss of precision.
10095   Expr::EvalResult EVResult;
10096   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10097   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10098   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10099   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10100 
10101   if (CstInt) {
10102     // If the scalar is constant and is of a higher order and has more active
10103     // bits that the vector element type, reject it.
10104     llvm::APSInt Result = EVResult.Val.getInt();
10105     unsigned NumBits = IntSigned
10106                            ? (Result.isNegative() ? Result.getMinSignedBits()
10107                                                   : Result.getActiveBits())
10108                            : Result.getActiveBits();
10109     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10110       return true;
10111 
10112     // If the signedness of the scalar type and the vector element type
10113     // differs and the number of bits is greater than that of the vector
10114     // element reject it.
10115     return (IntSigned != OtherIntSigned &&
10116             NumBits > S.Context.getIntWidth(OtherIntTy));
10117   }
10118 
10119   // Reject cases where the value of the scalar is not constant and it's
10120   // order is greater than that of the vector element type.
10121   return (Order < 0);
10122 }
10123 
10124 /// Test if a (constant) integer Int can be casted to floating point type
10125 /// FloatTy without losing precision.
10126 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10127                                      QualType FloatTy) {
10128   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10129 
10130   // Determine if the integer constant can be expressed as a floating point
10131   // number of the appropriate type.
10132   Expr::EvalResult EVResult;
10133   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10134 
10135   uint64_t Bits = 0;
10136   if (CstInt) {
10137     // Reject constants that would be truncated if they were converted to
10138     // the floating point type. Test by simple to/from conversion.
10139     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10140     //        could be avoided if there was a convertFromAPInt method
10141     //        which could signal back if implicit truncation occurred.
10142     llvm::APSInt Result = EVResult.Val.getInt();
10143     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10144     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10145                            llvm::APFloat::rmTowardZero);
10146     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10147                              !IntTy->hasSignedIntegerRepresentation());
10148     bool Ignored = false;
10149     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10150                            &Ignored);
10151     if (Result != ConvertBack)
10152       return true;
10153   } else {
10154     // Reject types that cannot be fully encoded into the mantissa of
10155     // the float.
10156     Bits = S.Context.getTypeSize(IntTy);
10157     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10158         S.Context.getFloatTypeSemantics(FloatTy));
10159     if (Bits > FloatPrec)
10160       return true;
10161   }
10162 
10163   return false;
10164 }
10165 
10166 /// Attempt to convert and splat Scalar into a vector whose types matches
10167 /// Vector following GCC conversion rules. The rule is that implicit
10168 /// conversion can occur when Scalar can be casted to match Vector's element
10169 /// type without causing truncation of Scalar.
10170 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10171                                         ExprResult *Vector) {
10172   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10173   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10174   const auto *VT = VectorTy->castAs<VectorType>();
10175 
10176   assert(!isa<ExtVectorType>(VT) &&
10177          "ExtVectorTypes should not be handled here!");
10178 
10179   QualType VectorEltTy = VT->getElementType();
10180 
10181   // Reject cases where the vector element type or the scalar element type are
10182   // not integral or floating point types.
10183   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10184     return true;
10185 
10186   // The conversion to apply to the scalar before splatting it,
10187   // if necessary.
10188   CastKind ScalarCast = CK_NoOp;
10189 
10190   // Accept cases where the vector elements are integers and the scalar is
10191   // an integer.
10192   // FIXME: Notionally if the scalar was a floating point value with a precise
10193   //        integral representation, we could cast it to an appropriate integer
10194   //        type and then perform the rest of the checks here. GCC will perform
10195   //        this conversion in some cases as determined by the input language.
10196   //        We should accept it on a language independent basis.
10197   if (VectorEltTy->isIntegralType(S.Context) &&
10198       ScalarTy->isIntegralType(S.Context) &&
10199       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10200 
10201     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10202       return true;
10203 
10204     ScalarCast = CK_IntegralCast;
10205   } else if (VectorEltTy->isIntegralType(S.Context) &&
10206              ScalarTy->isRealFloatingType()) {
10207     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10208       ScalarCast = CK_FloatingToIntegral;
10209     else
10210       return true;
10211   } else if (VectorEltTy->isRealFloatingType()) {
10212     if (ScalarTy->isRealFloatingType()) {
10213 
10214       // Reject cases where the scalar type is not a constant and has a higher
10215       // Order than the vector element type.
10216       llvm::APFloat Result(0.0);
10217 
10218       // Determine whether this is a constant scalar. In the event that the
10219       // value is dependent (and thus cannot be evaluated by the constant
10220       // evaluator), skip the evaluation. This will then diagnose once the
10221       // expression is instantiated.
10222       bool CstScalar = Scalar->get()->isValueDependent() ||
10223                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10224       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10225       if (!CstScalar && Order < 0)
10226         return true;
10227 
10228       // If the scalar cannot be safely casted to the vector element type,
10229       // reject it.
10230       if (CstScalar) {
10231         bool Truncated = false;
10232         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10233                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10234         if (Truncated)
10235           return true;
10236       }
10237 
10238       ScalarCast = CK_FloatingCast;
10239     } else if (ScalarTy->isIntegralType(S.Context)) {
10240       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10241         return true;
10242 
10243       ScalarCast = CK_IntegralToFloating;
10244     } else
10245       return true;
10246   } else if (ScalarTy->isEnumeralType())
10247     return true;
10248 
10249   // Adjust scalar if desired.
10250   if (Scalar) {
10251     if (ScalarCast != CK_NoOp)
10252       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10253     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10254   }
10255   return false;
10256 }
10257 
10258 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10259                                    SourceLocation Loc, bool IsCompAssign,
10260                                    bool AllowBothBool,
10261                                    bool AllowBoolConversions,
10262                                    bool AllowBoolOperation,
10263                                    bool ReportInvalid) {
10264   if (!IsCompAssign) {
10265     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10266     if (LHS.isInvalid())
10267       return QualType();
10268   }
10269   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10270   if (RHS.isInvalid())
10271     return QualType();
10272 
10273   // For conversion purposes, we ignore any qualifiers.
10274   // For example, "const float" and "float" are equivalent.
10275   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10276   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10277 
10278   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10279   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10280   assert(LHSVecType || RHSVecType);
10281 
10282   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10283       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10284     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10285 
10286   // AltiVec-style "vector bool op vector bool" combinations are allowed
10287   // for some operators but not others.
10288   if (!AllowBothBool &&
10289       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10290       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10291     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10292 
10293   // This operation may not be performed on boolean vectors.
10294   if (!AllowBoolOperation &&
10295       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10296     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10297 
10298   // If the vector types are identical, return.
10299   if (Context.hasSameType(LHSType, RHSType))
10300     return LHSType;
10301 
10302   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10303   if (LHSVecType && RHSVecType &&
10304       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10305     if (isa<ExtVectorType>(LHSVecType)) {
10306       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10307       return LHSType;
10308     }
10309 
10310     if (!IsCompAssign)
10311       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10312     return RHSType;
10313   }
10314 
10315   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10316   // can be mixed, with the result being the non-bool type.  The non-bool
10317   // operand must have integer element type.
10318   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10319       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10320       (Context.getTypeSize(LHSVecType->getElementType()) ==
10321        Context.getTypeSize(RHSVecType->getElementType()))) {
10322     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10323         LHSVecType->getElementType()->isIntegerType() &&
10324         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10325       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10326       return LHSType;
10327     }
10328     if (!IsCompAssign &&
10329         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10330         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10331         RHSVecType->getElementType()->isIntegerType()) {
10332       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10333       return RHSType;
10334     }
10335   }
10336 
10337   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10338   // since the ambiguity can affect the ABI.
10339   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10340     const VectorType *VecType = SecondType->getAs<VectorType>();
10341     return FirstType->isSizelessBuiltinType() && VecType &&
10342            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10343             VecType->getVectorKind() ==
10344                 VectorType::SveFixedLengthPredicateVector);
10345   };
10346 
10347   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10348     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10349     return QualType();
10350   }
10351 
10352   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10353   // since the ambiguity can affect the ABI.
10354   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10355     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10356     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10357 
10358     if (FirstVecType && SecondVecType)
10359       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10360              (SecondVecType->getVectorKind() ==
10361                   VectorType::SveFixedLengthDataVector ||
10362               SecondVecType->getVectorKind() ==
10363                   VectorType::SveFixedLengthPredicateVector);
10364 
10365     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10366            SecondVecType->getVectorKind() == VectorType::GenericVector;
10367   };
10368 
10369   if (IsSveGnuConversion(LHSType, RHSType) ||
10370       IsSveGnuConversion(RHSType, LHSType)) {
10371     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10372     return QualType();
10373   }
10374 
10375   // If there's a vector type and a scalar, try to convert the scalar to
10376   // the vector element type and splat.
10377   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10378   if (!RHSVecType) {
10379     if (isa<ExtVectorType>(LHSVecType)) {
10380       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10381                                     LHSVecType->getElementType(), LHSType,
10382                                     DiagID))
10383         return LHSType;
10384     } else {
10385       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10386         return LHSType;
10387     }
10388   }
10389   if (!LHSVecType) {
10390     if (isa<ExtVectorType>(RHSVecType)) {
10391       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10392                                     LHSType, RHSVecType->getElementType(),
10393                                     RHSType, DiagID))
10394         return RHSType;
10395     } else {
10396       if (LHS.get()->isLValue() ||
10397           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10398         return RHSType;
10399     }
10400   }
10401 
10402   // FIXME: The code below also handles conversion between vectors and
10403   // non-scalars, we should break this down into fine grained specific checks
10404   // and emit proper diagnostics.
10405   QualType VecType = LHSVecType ? LHSType : RHSType;
10406   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10407   QualType OtherType = LHSVecType ? RHSType : LHSType;
10408   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10409   if (isLaxVectorConversion(OtherType, VecType)) {
10410     // If we're allowing lax vector conversions, only the total (data) size
10411     // needs to be the same. For non compound assignment, if one of the types is
10412     // scalar, the result is always the vector type.
10413     if (!IsCompAssign) {
10414       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10415       return VecType;
10416     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10417     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10418     // type. Note that this is already done by non-compound assignments in
10419     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10420     // <1 x T> -> T. The result is also a vector type.
10421     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10422                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10423       ExprResult *RHSExpr = &RHS;
10424       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10425       return VecType;
10426     }
10427   }
10428 
10429   // Okay, the expression is invalid.
10430 
10431   // If there's a non-vector, non-real operand, diagnose that.
10432   if ((!RHSVecType && !RHSType->isRealType()) ||
10433       (!LHSVecType && !LHSType->isRealType())) {
10434     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10435       << LHSType << RHSType
10436       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10437     return QualType();
10438   }
10439 
10440   // OpenCL V1.1 6.2.6.p1:
10441   // If the operands are of more than one vector type, then an error shall
10442   // occur. Implicit conversions between vector types are not permitted, per
10443   // section 6.2.1.
10444   if (getLangOpts().OpenCL &&
10445       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10446       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10447     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10448                                                            << RHSType;
10449     return QualType();
10450   }
10451 
10452 
10453   // If there is a vector type that is not a ExtVector and a scalar, we reach
10454   // this point if scalar could not be converted to the vector's element type
10455   // without truncation.
10456   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10457       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10458     QualType Scalar = LHSVecType ? RHSType : LHSType;
10459     QualType Vector = LHSVecType ? LHSType : RHSType;
10460     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10461     Diag(Loc,
10462          diag::err_typecheck_vector_not_convertable_implict_truncation)
10463         << ScalarOrVector << Scalar << Vector;
10464 
10465     return QualType();
10466   }
10467 
10468   // Otherwise, use the generic diagnostic.
10469   Diag(Loc, DiagID)
10470     << LHSType << RHSType
10471     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10472   return QualType();
10473 }
10474 
10475 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10476                                            SourceLocation Loc,
10477                                            bool IsCompAssign,
10478                                            ArithConvKind OperationKind) {
10479   if (!IsCompAssign) {
10480     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10481     if (LHS.isInvalid())
10482       return QualType();
10483   }
10484   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10485   if (RHS.isInvalid())
10486     return QualType();
10487 
10488   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10489   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10490 
10491   const BuiltinType *LHSVecType = LHSType->getAs<BuiltinType>();
10492   const BuiltinType *RHSVecType = RHSType->getAs<BuiltinType>();
10493 
10494   unsigned DiagID = diag::err_typecheck_invalid_operands;
10495   if ((OperationKind == ACK_Arithmetic) &&
10496       (LHSVecType->isSVEBool() || RHSVecType->isSVEBool())) {
10497     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10498                       << RHS.get()->getSourceRange();
10499     return QualType();
10500   }
10501 
10502   if (Context.hasSameType(LHSType, RHSType))
10503     return LHSType;
10504 
10505   auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10506                                          QualType DestType) {
10507     const QualType DestBaseType = DestType->getSveEltType(Context);
10508     if (DestBaseType->getUnqualifiedDesugaredType() ==
10509         SrcType->getUnqualifiedDesugaredType()) {
10510       unsigned DiagID = diag::err_typecheck_invalid_operands;
10511       if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10512                                     DiagID))
10513         return DestType;
10514     }
10515     return QualType();
10516   };
10517 
10518   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10519     auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10520     if (DestType == QualType())
10521       return InvalidOperands(Loc, LHS, RHS);
10522     return DestType;
10523   }
10524 
10525   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10526     auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10527                                              LHSType, RHSType);
10528     if (DestType == QualType())
10529       return InvalidOperands(Loc, LHS, RHS);
10530     return DestType;
10531   }
10532 
10533   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10534                     << RHS.get()->getSourceRange();
10535   return QualType();
10536 }
10537 
10538 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10539 // expression.  These are mainly cases where the null pointer is used as an
10540 // integer instead of a pointer.
10541 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10542                                 SourceLocation Loc, bool IsCompare) {
10543   // The canonical way to check for a GNU null is with isNullPointerConstant,
10544   // but we use a bit of a hack here for speed; this is a relatively
10545   // hot path, and isNullPointerConstant is slow.
10546   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10547   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10548 
10549   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10550 
10551   // Avoid analyzing cases where the result will either be invalid (and
10552   // diagnosed as such) or entirely valid and not something to warn about.
10553   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10554       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10555     return;
10556 
10557   // Comparison operations would not make sense with a null pointer no matter
10558   // what the other expression is.
10559   if (!IsCompare) {
10560     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10561         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10562         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10563     return;
10564   }
10565 
10566   // The rest of the operations only make sense with a null pointer
10567   // if the other expression is a pointer.
10568   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10569       NonNullType->canDecayToPointerType())
10570     return;
10571 
10572   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10573       << LHSNull /* LHS is NULL */ << NonNullType
10574       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10575 }
10576 
10577 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10578                                           SourceLocation Loc) {
10579   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10580   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10581   if (!LUE || !RUE)
10582     return;
10583   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10584       RUE->getKind() != UETT_SizeOf)
10585     return;
10586 
10587   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10588   QualType LHSTy = LHSArg->getType();
10589   QualType RHSTy;
10590 
10591   if (RUE->isArgumentType())
10592     RHSTy = RUE->getArgumentType().getNonReferenceType();
10593   else
10594     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10595 
10596   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10597     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10598       return;
10599 
10600     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10601     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10602       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10603         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10604             << LHSArgDecl;
10605     }
10606   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10607     QualType ArrayElemTy = ArrayTy->getElementType();
10608     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10609         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10610         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10611         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10612       return;
10613     S.Diag(Loc, diag::warn_division_sizeof_array)
10614         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10615     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10616       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10617         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10618             << LHSArgDecl;
10619     }
10620 
10621     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10622   }
10623 }
10624 
10625 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10626                                                ExprResult &RHS,
10627                                                SourceLocation Loc, bool IsDiv) {
10628   // Check for division/remainder by zero.
10629   Expr::EvalResult RHSValue;
10630   if (!RHS.get()->isValueDependent() &&
10631       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10632       RHSValue.Val.getInt() == 0)
10633     S.DiagRuntimeBehavior(Loc, RHS.get(),
10634                           S.PDiag(diag::warn_remainder_division_by_zero)
10635                             << IsDiv << RHS.get()->getSourceRange());
10636 }
10637 
10638 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10639                                            SourceLocation Loc,
10640                                            bool IsCompAssign, bool IsDiv) {
10641   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10642 
10643   QualType LHSTy = LHS.get()->getType();
10644   QualType RHSTy = RHS.get()->getType();
10645   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10646     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10647                                /*AllowBothBool*/ getLangOpts().AltiVec,
10648                                /*AllowBoolConversions*/ false,
10649                                /*AllowBooleanOperation*/ false,
10650                                /*ReportInvalid*/ true);
10651   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10652     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10653                                        ACK_Arithmetic);
10654   if (!IsDiv &&
10655       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10656     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10657   // For division, only matrix-by-scalar is supported. Other combinations with
10658   // matrix types are invalid.
10659   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10660     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10661 
10662   QualType compType = UsualArithmeticConversions(
10663       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10664   if (LHS.isInvalid() || RHS.isInvalid())
10665     return QualType();
10666 
10667 
10668   if (compType.isNull() || !compType->isArithmeticType())
10669     return InvalidOperands(Loc, LHS, RHS);
10670   if (IsDiv) {
10671     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10672     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10673   }
10674   return compType;
10675 }
10676 
10677 QualType Sema::CheckRemainderOperands(
10678   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10679   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10680 
10681   if (LHS.get()->getType()->isVectorType() ||
10682       RHS.get()->getType()->isVectorType()) {
10683     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10684         RHS.get()->getType()->hasIntegerRepresentation())
10685       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10686                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10687                                  /*AllowBoolConversions*/ false,
10688                                  /*AllowBooleanOperation*/ false,
10689                                  /*ReportInvalid*/ true);
10690     return InvalidOperands(Loc, LHS, RHS);
10691   }
10692 
10693   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10694       RHS.get()->getType()->isVLSTBuiltinType()) {
10695     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10696         RHS.get()->getType()->hasIntegerRepresentation())
10697       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10698                                          ACK_Arithmetic);
10699 
10700     return InvalidOperands(Loc, LHS, RHS);
10701   }
10702 
10703   QualType compType = UsualArithmeticConversions(
10704       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10705   if (LHS.isInvalid() || RHS.isInvalid())
10706     return QualType();
10707 
10708   if (compType.isNull() || !compType->isIntegerType())
10709     return InvalidOperands(Loc, LHS, RHS);
10710   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10711   return compType;
10712 }
10713 
10714 /// Diagnose invalid arithmetic on two void pointers.
10715 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10716                                                 Expr *LHSExpr, Expr *RHSExpr) {
10717   S.Diag(Loc, S.getLangOpts().CPlusPlus
10718                 ? diag::err_typecheck_pointer_arith_void_type
10719                 : diag::ext_gnu_void_ptr)
10720     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10721                             << RHSExpr->getSourceRange();
10722 }
10723 
10724 /// Diagnose invalid arithmetic on a void pointer.
10725 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10726                                             Expr *Pointer) {
10727   S.Diag(Loc, S.getLangOpts().CPlusPlus
10728                 ? diag::err_typecheck_pointer_arith_void_type
10729                 : diag::ext_gnu_void_ptr)
10730     << 0 /* one pointer */ << Pointer->getSourceRange();
10731 }
10732 
10733 /// Diagnose invalid arithmetic on a null pointer.
10734 ///
10735 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10736 /// idiom, which we recognize as a GNU extension.
10737 ///
10738 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10739                                             Expr *Pointer, bool IsGNUIdiom) {
10740   if (IsGNUIdiom)
10741     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10742       << Pointer->getSourceRange();
10743   else
10744     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10745       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10746 }
10747 
10748 /// Diagnose invalid subraction on a null pointer.
10749 ///
10750 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10751                                              Expr *Pointer, bool BothNull) {
10752   // Null - null is valid in C++ [expr.add]p7
10753   if (BothNull && S.getLangOpts().CPlusPlus)
10754     return;
10755 
10756   // Is this s a macro from a system header?
10757   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10758     return;
10759 
10760   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10761       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10762 }
10763 
10764 /// Diagnose invalid arithmetic on two function pointers.
10765 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10766                                                     Expr *LHS, Expr *RHS) {
10767   assert(LHS->getType()->isAnyPointerType());
10768   assert(RHS->getType()->isAnyPointerType());
10769   S.Diag(Loc, S.getLangOpts().CPlusPlus
10770                 ? diag::err_typecheck_pointer_arith_function_type
10771                 : diag::ext_gnu_ptr_func_arith)
10772     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10773     // We only show the second type if it differs from the first.
10774     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10775                                                    RHS->getType())
10776     << RHS->getType()->getPointeeType()
10777     << LHS->getSourceRange() << RHS->getSourceRange();
10778 }
10779 
10780 /// Diagnose invalid arithmetic on a function pointer.
10781 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10782                                                 Expr *Pointer) {
10783   assert(Pointer->getType()->isAnyPointerType());
10784   S.Diag(Loc, S.getLangOpts().CPlusPlus
10785                 ? diag::err_typecheck_pointer_arith_function_type
10786                 : diag::ext_gnu_ptr_func_arith)
10787     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10788     << 0 /* one pointer, so only one type */
10789     << Pointer->getSourceRange();
10790 }
10791 
10792 /// Emit error if Operand is incomplete pointer type
10793 ///
10794 /// \returns True if pointer has incomplete type
10795 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10796                                                  Expr *Operand) {
10797   QualType ResType = Operand->getType();
10798   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10799     ResType = ResAtomicType->getValueType();
10800 
10801   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10802   QualType PointeeTy = ResType->getPointeeType();
10803   return S.RequireCompleteSizedType(
10804       Loc, PointeeTy,
10805       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10806       Operand->getSourceRange());
10807 }
10808 
10809 /// Check the validity of an arithmetic pointer operand.
10810 ///
10811 /// If the operand has pointer type, this code will check for pointer types
10812 /// which are invalid in arithmetic operations. These will be diagnosed
10813 /// appropriately, including whether or not the use is supported as an
10814 /// extension.
10815 ///
10816 /// \returns True when the operand is valid to use (even if as an extension).
10817 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10818                                             Expr *Operand) {
10819   QualType ResType = Operand->getType();
10820   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10821     ResType = ResAtomicType->getValueType();
10822 
10823   if (!ResType->isAnyPointerType()) return true;
10824 
10825   QualType PointeeTy = ResType->getPointeeType();
10826   if (PointeeTy->isVoidType()) {
10827     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10828     return !S.getLangOpts().CPlusPlus;
10829   }
10830   if (PointeeTy->isFunctionType()) {
10831     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10832     return !S.getLangOpts().CPlusPlus;
10833   }
10834 
10835   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10836 
10837   return true;
10838 }
10839 
10840 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10841 /// operands.
10842 ///
10843 /// This routine will diagnose any invalid arithmetic on pointer operands much
10844 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10845 /// for emitting a single diagnostic even for operations where both LHS and RHS
10846 /// are (potentially problematic) pointers.
10847 ///
10848 /// \returns True when the operand is valid to use (even if as an extension).
10849 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10850                                                 Expr *LHSExpr, Expr *RHSExpr) {
10851   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10852   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10853   if (!isLHSPointer && !isRHSPointer) return true;
10854 
10855   QualType LHSPointeeTy, RHSPointeeTy;
10856   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10857   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10858 
10859   // if both are pointers check if operation is valid wrt address spaces
10860   if (isLHSPointer && isRHSPointer) {
10861     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10862       S.Diag(Loc,
10863              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10864           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10865           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10866       return false;
10867     }
10868   }
10869 
10870   // Check for arithmetic on pointers to incomplete types.
10871   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10872   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10873   if (isLHSVoidPtr || isRHSVoidPtr) {
10874     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10875     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10876     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10877 
10878     return !S.getLangOpts().CPlusPlus;
10879   }
10880 
10881   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10882   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10883   if (isLHSFuncPtr || isRHSFuncPtr) {
10884     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10885     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10886                                                                 RHSExpr);
10887     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10888 
10889     return !S.getLangOpts().CPlusPlus;
10890   }
10891 
10892   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10893     return false;
10894   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10895     return false;
10896 
10897   return true;
10898 }
10899 
10900 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10901 /// literal.
10902 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10903                                   Expr *LHSExpr, Expr *RHSExpr) {
10904   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10905   Expr* IndexExpr = RHSExpr;
10906   if (!StrExpr) {
10907     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10908     IndexExpr = LHSExpr;
10909   }
10910 
10911   bool IsStringPlusInt = StrExpr &&
10912       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10913   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10914     return;
10915 
10916   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10917   Self.Diag(OpLoc, diag::warn_string_plus_int)
10918       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10919 
10920   // Only print a fixit for "str" + int, not for int + "str".
10921   if (IndexExpr == RHSExpr) {
10922     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10923     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10924         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10925         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10926         << FixItHint::CreateInsertion(EndLoc, "]");
10927   } else
10928     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10929 }
10930 
10931 /// Emit a warning when adding a char literal to a string.
10932 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10933                                    Expr *LHSExpr, Expr *RHSExpr) {
10934   const Expr *StringRefExpr = LHSExpr;
10935   const CharacterLiteral *CharExpr =
10936       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10937 
10938   if (!CharExpr) {
10939     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10940     StringRefExpr = RHSExpr;
10941   }
10942 
10943   if (!CharExpr || !StringRefExpr)
10944     return;
10945 
10946   const QualType StringType = StringRefExpr->getType();
10947 
10948   // Return if not a PointerType.
10949   if (!StringType->isAnyPointerType())
10950     return;
10951 
10952   // Return if not a CharacterType.
10953   if (!StringType->getPointeeType()->isAnyCharacterType())
10954     return;
10955 
10956   ASTContext &Ctx = Self.getASTContext();
10957   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10958 
10959   const QualType CharType = CharExpr->getType();
10960   if (!CharType->isAnyCharacterType() &&
10961       CharType->isIntegerType() &&
10962       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10963     Self.Diag(OpLoc, diag::warn_string_plus_char)
10964         << DiagRange << Ctx.CharTy;
10965   } else {
10966     Self.Diag(OpLoc, diag::warn_string_plus_char)
10967         << DiagRange << CharExpr->getType();
10968   }
10969 
10970   // Only print a fixit for str + char, not for char + str.
10971   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10972     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10973     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10974         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10975         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10976         << FixItHint::CreateInsertion(EndLoc, "]");
10977   } else {
10978     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10979   }
10980 }
10981 
10982 /// Emit error when two pointers are incompatible.
10983 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10984                                            Expr *LHSExpr, Expr *RHSExpr) {
10985   assert(LHSExpr->getType()->isAnyPointerType());
10986   assert(RHSExpr->getType()->isAnyPointerType());
10987   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10988     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10989     << RHSExpr->getSourceRange();
10990 }
10991 
10992 // C99 6.5.6
10993 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10994                                      SourceLocation Loc, BinaryOperatorKind Opc,
10995                                      QualType* CompLHSTy) {
10996   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10997 
10998   if (LHS.get()->getType()->isVectorType() ||
10999       RHS.get()->getType()->isVectorType()) {
11000     QualType compType =
11001         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11002                             /*AllowBothBool*/ getLangOpts().AltiVec,
11003                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11004                             /*AllowBooleanOperation*/ false,
11005                             /*ReportInvalid*/ true);
11006     if (CompLHSTy) *CompLHSTy = compType;
11007     return compType;
11008   }
11009 
11010   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11011       RHS.get()->getType()->isVLSTBuiltinType()) {
11012     QualType compType =
11013         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11014     if (CompLHSTy)
11015       *CompLHSTy = compType;
11016     return compType;
11017   }
11018 
11019   if (LHS.get()->getType()->isConstantMatrixType() ||
11020       RHS.get()->getType()->isConstantMatrixType()) {
11021     QualType compType =
11022         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11023     if (CompLHSTy)
11024       *CompLHSTy = compType;
11025     return compType;
11026   }
11027 
11028   QualType compType = UsualArithmeticConversions(
11029       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11030   if (LHS.isInvalid() || RHS.isInvalid())
11031     return QualType();
11032 
11033   // Diagnose "string literal" '+' int and string '+' "char literal".
11034   if (Opc == BO_Add) {
11035     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11036     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11037   }
11038 
11039   // handle the common case first (both operands are arithmetic).
11040   if (!compType.isNull() && compType->isArithmeticType()) {
11041     if (CompLHSTy) *CompLHSTy = compType;
11042     return compType;
11043   }
11044 
11045   // Type-checking.  Ultimately the pointer's going to be in PExp;
11046   // note that we bias towards the LHS being the pointer.
11047   Expr *PExp = LHS.get(), *IExp = RHS.get();
11048 
11049   bool isObjCPointer;
11050   if (PExp->getType()->isPointerType()) {
11051     isObjCPointer = false;
11052   } else if (PExp->getType()->isObjCObjectPointerType()) {
11053     isObjCPointer = true;
11054   } else {
11055     std::swap(PExp, IExp);
11056     if (PExp->getType()->isPointerType()) {
11057       isObjCPointer = false;
11058     } else if (PExp->getType()->isObjCObjectPointerType()) {
11059       isObjCPointer = true;
11060     } else {
11061       return InvalidOperands(Loc, LHS, RHS);
11062     }
11063   }
11064   assert(PExp->getType()->isAnyPointerType());
11065 
11066   if (!IExp->getType()->isIntegerType())
11067     return InvalidOperands(Loc, LHS, RHS);
11068 
11069   // Adding to a null pointer results in undefined behavior.
11070   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11071           Context, Expr::NPC_ValueDependentIsNotNull)) {
11072     // In C++ adding zero to a null pointer is defined.
11073     Expr::EvalResult KnownVal;
11074     if (!getLangOpts().CPlusPlus ||
11075         (!IExp->isValueDependent() &&
11076          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11077           KnownVal.Val.getInt() != 0))) {
11078       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11079       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11080           Context, BO_Add, PExp, IExp);
11081       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11082     }
11083   }
11084 
11085   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11086     return QualType();
11087 
11088   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11089     return QualType();
11090 
11091   // Check array bounds for pointer arithemtic
11092   CheckArrayAccess(PExp, IExp);
11093 
11094   if (CompLHSTy) {
11095     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11096     if (LHSTy.isNull()) {
11097       LHSTy = LHS.get()->getType();
11098       if (LHSTy->isPromotableIntegerType())
11099         LHSTy = Context.getPromotedIntegerType(LHSTy);
11100     }
11101     *CompLHSTy = LHSTy;
11102   }
11103 
11104   return PExp->getType();
11105 }
11106 
11107 // C99 6.5.6
11108 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11109                                         SourceLocation Loc,
11110                                         QualType* CompLHSTy) {
11111   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11112 
11113   if (LHS.get()->getType()->isVectorType() ||
11114       RHS.get()->getType()->isVectorType()) {
11115     QualType compType =
11116         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11117                             /*AllowBothBool*/ getLangOpts().AltiVec,
11118                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11119                             /*AllowBooleanOperation*/ false,
11120                             /*ReportInvalid*/ true);
11121     if (CompLHSTy) *CompLHSTy = compType;
11122     return compType;
11123   }
11124 
11125   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11126       RHS.get()->getType()->isVLSTBuiltinType()) {
11127     QualType compType =
11128         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11129     if (CompLHSTy)
11130       *CompLHSTy = compType;
11131     return compType;
11132   }
11133 
11134   if (LHS.get()->getType()->isConstantMatrixType() ||
11135       RHS.get()->getType()->isConstantMatrixType()) {
11136     QualType compType =
11137         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11138     if (CompLHSTy)
11139       *CompLHSTy = compType;
11140     return compType;
11141   }
11142 
11143   QualType compType = UsualArithmeticConversions(
11144       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11145   if (LHS.isInvalid() || RHS.isInvalid())
11146     return QualType();
11147 
11148   // Enforce type constraints: C99 6.5.6p3.
11149 
11150   // Handle the common case first (both operands are arithmetic).
11151   if (!compType.isNull() && compType->isArithmeticType()) {
11152     if (CompLHSTy) *CompLHSTy = compType;
11153     return compType;
11154   }
11155 
11156   // Either ptr - int   or   ptr - ptr.
11157   if (LHS.get()->getType()->isAnyPointerType()) {
11158     QualType lpointee = LHS.get()->getType()->getPointeeType();
11159 
11160     // Diagnose bad cases where we step over interface counts.
11161     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11162         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11163       return QualType();
11164 
11165     // The result type of a pointer-int computation is the pointer type.
11166     if (RHS.get()->getType()->isIntegerType()) {
11167       // Subtracting from a null pointer should produce a warning.
11168       // The last argument to the diagnose call says this doesn't match the
11169       // GNU int-to-pointer idiom.
11170       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11171                                            Expr::NPC_ValueDependentIsNotNull)) {
11172         // In C++ adding zero to a null pointer is defined.
11173         Expr::EvalResult KnownVal;
11174         if (!getLangOpts().CPlusPlus ||
11175             (!RHS.get()->isValueDependent() &&
11176              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11177               KnownVal.Val.getInt() != 0))) {
11178           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11179         }
11180       }
11181 
11182       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11183         return QualType();
11184 
11185       // Check array bounds for pointer arithemtic
11186       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11187                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11188 
11189       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11190       return LHS.get()->getType();
11191     }
11192 
11193     // Handle pointer-pointer subtractions.
11194     if (const PointerType *RHSPTy
11195           = RHS.get()->getType()->getAs<PointerType>()) {
11196       QualType rpointee = RHSPTy->getPointeeType();
11197 
11198       if (getLangOpts().CPlusPlus) {
11199         // Pointee types must be the same: C++ [expr.add]
11200         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11201           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11202         }
11203       } else {
11204         // Pointee types must be compatible C99 6.5.6p3
11205         if (!Context.typesAreCompatible(
11206                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11207                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11208           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11209           return QualType();
11210         }
11211       }
11212 
11213       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11214                                                LHS.get(), RHS.get()))
11215         return QualType();
11216 
11217       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11218           Context, Expr::NPC_ValueDependentIsNotNull);
11219       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11220           Context, Expr::NPC_ValueDependentIsNotNull);
11221 
11222       // Subtracting nullptr or from nullptr is suspect
11223       if (LHSIsNullPtr)
11224         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11225       if (RHSIsNullPtr)
11226         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11227 
11228       // The pointee type may have zero size.  As an extension, a structure or
11229       // union may have zero size or an array may have zero length.  In this
11230       // case subtraction does not make sense.
11231       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11232         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11233         if (ElementSize.isZero()) {
11234           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11235             << rpointee.getUnqualifiedType()
11236             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11237         }
11238       }
11239 
11240       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11241       return Context.getPointerDiffType();
11242     }
11243   }
11244 
11245   return InvalidOperands(Loc, LHS, RHS);
11246 }
11247 
11248 static bool isScopedEnumerationType(QualType T) {
11249   if (const EnumType *ET = T->getAs<EnumType>())
11250     return ET->getDecl()->isScoped();
11251   return false;
11252 }
11253 
11254 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11255                                    SourceLocation Loc, BinaryOperatorKind Opc,
11256                                    QualType LHSType) {
11257   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11258   // so skip remaining warnings as we don't want to modify values within Sema.
11259   if (S.getLangOpts().OpenCL)
11260     return;
11261 
11262   // Check right/shifter operand
11263   Expr::EvalResult RHSResult;
11264   if (RHS.get()->isValueDependent() ||
11265       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11266     return;
11267   llvm::APSInt Right = RHSResult.Val.getInt();
11268 
11269   if (Right.isNegative()) {
11270     S.DiagRuntimeBehavior(Loc, RHS.get(),
11271                           S.PDiag(diag::warn_shift_negative)
11272                             << RHS.get()->getSourceRange());
11273     return;
11274   }
11275 
11276   QualType LHSExprType = LHS.get()->getType();
11277   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11278   if (LHSExprType->isBitIntType())
11279     LeftSize = S.Context.getIntWidth(LHSExprType);
11280   else if (LHSExprType->isFixedPointType()) {
11281     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11282     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11283   }
11284   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11285   if (Right.uge(LeftBits)) {
11286     S.DiagRuntimeBehavior(Loc, RHS.get(),
11287                           S.PDiag(diag::warn_shift_gt_typewidth)
11288                             << RHS.get()->getSourceRange());
11289     return;
11290   }
11291 
11292   // FIXME: We probably need to handle fixed point types specially here.
11293   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11294     return;
11295 
11296   // When left shifting an ICE which is signed, we can check for overflow which
11297   // according to C++ standards prior to C++2a has undefined behavior
11298   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11299   // more than the maximum value representable in the result type, so never
11300   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11301   // expression is still probably a bug.)
11302   Expr::EvalResult LHSResult;
11303   if (LHS.get()->isValueDependent() ||
11304       LHSType->hasUnsignedIntegerRepresentation() ||
11305       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11306     return;
11307   llvm::APSInt Left = LHSResult.Val.getInt();
11308 
11309   // If LHS does not have a signed type and non-negative value
11310   // then, the behavior is undefined before C++2a. Warn about it.
11311   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11312       !S.getLangOpts().CPlusPlus20) {
11313     S.DiagRuntimeBehavior(Loc, LHS.get(),
11314                           S.PDiag(diag::warn_shift_lhs_negative)
11315                             << LHS.get()->getSourceRange());
11316     return;
11317   }
11318 
11319   llvm::APInt ResultBits =
11320       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11321   if (LeftBits.uge(ResultBits))
11322     return;
11323   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11324   Result = Result.shl(Right);
11325 
11326   // Print the bit representation of the signed integer as an unsigned
11327   // hexadecimal number.
11328   SmallString<40> HexResult;
11329   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11330 
11331   // If we are only missing a sign bit, this is less likely to result in actual
11332   // bugs -- if the result is cast back to an unsigned type, it will have the
11333   // expected value. Thus we place this behind a different warning that can be
11334   // turned off separately if needed.
11335   if (LeftBits == ResultBits - 1) {
11336     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11337         << HexResult << LHSType
11338         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11339     return;
11340   }
11341 
11342   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11343     << HexResult.str() << Result.getMinSignedBits() << LHSType
11344     << Left.getBitWidth() << LHS.get()->getSourceRange()
11345     << RHS.get()->getSourceRange();
11346 }
11347 
11348 /// Return the resulting type when a vector is shifted
11349 ///        by a scalar or vector shift amount.
11350 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11351                                  SourceLocation Loc, bool IsCompAssign) {
11352   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11353   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11354       !LHS.get()->getType()->isVectorType()) {
11355     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11356       << RHS.get()->getType() << LHS.get()->getType()
11357       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11358     return QualType();
11359   }
11360 
11361   if (!IsCompAssign) {
11362     LHS = S.UsualUnaryConversions(LHS.get());
11363     if (LHS.isInvalid()) return QualType();
11364   }
11365 
11366   RHS = S.UsualUnaryConversions(RHS.get());
11367   if (RHS.isInvalid()) return QualType();
11368 
11369   QualType LHSType = LHS.get()->getType();
11370   // Note that LHS might be a scalar because the routine calls not only in
11371   // OpenCL case.
11372   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11373   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11374 
11375   // Note that RHS might not be a vector.
11376   QualType RHSType = RHS.get()->getType();
11377   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11378   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11379 
11380   // Do not allow shifts for boolean vectors.
11381   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11382       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11383     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11384         << LHS.get()->getType() << RHS.get()->getType()
11385         << LHS.get()->getSourceRange();
11386     return QualType();
11387   }
11388 
11389   // The operands need to be integers.
11390   if (!LHSEleType->isIntegerType()) {
11391     S.Diag(Loc, diag::err_typecheck_expect_int)
11392       << LHS.get()->getType() << LHS.get()->getSourceRange();
11393     return QualType();
11394   }
11395 
11396   if (!RHSEleType->isIntegerType()) {
11397     S.Diag(Loc, diag::err_typecheck_expect_int)
11398       << RHS.get()->getType() << RHS.get()->getSourceRange();
11399     return QualType();
11400   }
11401 
11402   if (!LHSVecTy) {
11403     assert(RHSVecTy);
11404     if (IsCompAssign)
11405       return RHSType;
11406     if (LHSEleType != RHSEleType) {
11407       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11408       LHSEleType = RHSEleType;
11409     }
11410     QualType VecTy =
11411         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11412     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11413     LHSType = VecTy;
11414   } else if (RHSVecTy) {
11415     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11416     // are applied component-wise. So if RHS is a vector, then ensure
11417     // that the number of elements is the same as LHS...
11418     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11419       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11420         << LHS.get()->getType() << RHS.get()->getType()
11421         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11422       return QualType();
11423     }
11424     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11425       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11426       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11427       if (LHSBT != RHSBT &&
11428           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11429         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11430             << LHS.get()->getType() << RHS.get()->getType()
11431             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11432       }
11433     }
11434   } else {
11435     // ...else expand RHS to match the number of elements in LHS.
11436     QualType VecTy =
11437       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11438     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11439   }
11440 
11441   return LHSType;
11442 }
11443 
11444 // C99 6.5.7
11445 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11446                                   SourceLocation Loc, BinaryOperatorKind Opc,
11447                                   bool IsCompAssign) {
11448   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11449 
11450   // Vector shifts promote their scalar inputs to vector type.
11451   if (LHS.get()->getType()->isVectorType() ||
11452       RHS.get()->getType()->isVectorType()) {
11453     if (LangOpts.ZVector) {
11454       // The shift operators for the z vector extensions work basically
11455       // like general shifts, except that neither the LHS nor the RHS is
11456       // allowed to be a "vector bool".
11457       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11458         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11459           return InvalidOperands(Loc, LHS, RHS);
11460       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11461         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11462           return InvalidOperands(Loc, LHS, RHS);
11463     }
11464     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11465   }
11466 
11467   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11468       RHS.get()->getType()->isVLSTBuiltinType())
11469     return InvalidOperands(Loc, LHS, RHS);
11470 
11471   // Shifts don't perform usual arithmetic conversions, they just do integer
11472   // promotions on each operand. C99 6.5.7p3
11473 
11474   // For the LHS, do usual unary conversions, but then reset them away
11475   // if this is a compound assignment.
11476   ExprResult OldLHS = LHS;
11477   LHS = UsualUnaryConversions(LHS.get());
11478   if (LHS.isInvalid())
11479     return QualType();
11480   QualType LHSType = LHS.get()->getType();
11481   if (IsCompAssign) LHS = OldLHS;
11482 
11483   // The RHS is simpler.
11484   RHS = UsualUnaryConversions(RHS.get());
11485   if (RHS.isInvalid())
11486     return QualType();
11487   QualType RHSType = RHS.get()->getType();
11488 
11489   // C99 6.5.7p2: Each of the operands shall have integer type.
11490   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11491   if ((!LHSType->isFixedPointOrIntegerType() &&
11492        !LHSType->hasIntegerRepresentation()) ||
11493       !RHSType->hasIntegerRepresentation())
11494     return InvalidOperands(Loc, LHS, RHS);
11495 
11496   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11497   // hasIntegerRepresentation() above instead of this.
11498   if (isScopedEnumerationType(LHSType) ||
11499       isScopedEnumerationType(RHSType)) {
11500     return InvalidOperands(Loc, LHS, RHS);
11501   }
11502   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11503 
11504   // "The type of the result is that of the promoted left operand."
11505   return LHSType;
11506 }
11507 
11508 /// Diagnose bad pointer comparisons.
11509 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11510                                               ExprResult &LHS, ExprResult &RHS,
11511                                               bool IsError) {
11512   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11513                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11514     << LHS.get()->getType() << RHS.get()->getType()
11515     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11516 }
11517 
11518 /// Returns false if the pointers are converted to a composite type,
11519 /// true otherwise.
11520 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11521                                            ExprResult &LHS, ExprResult &RHS) {
11522   // C++ [expr.rel]p2:
11523   //   [...] Pointer conversions (4.10) and qualification
11524   //   conversions (4.4) are performed on pointer operands (or on
11525   //   a pointer operand and a null pointer constant) to bring
11526   //   them to their composite pointer type. [...]
11527   //
11528   // C++ [expr.eq]p1 uses the same notion for (in)equality
11529   // comparisons of pointers.
11530 
11531   QualType LHSType = LHS.get()->getType();
11532   QualType RHSType = RHS.get()->getType();
11533   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11534          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11535 
11536   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11537   if (T.isNull()) {
11538     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11539         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11540       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11541     else
11542       S.InvalidOperands(Loc, LHS, RHS);
11543     return true;
11544   }
11545 
11546   return false;
11547 }
11548 
11549 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11550                                                     ExprResult &LHS,
11551                                                     ExprResult &RHS,
11552                                                     bool IsError) {
11553   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11554                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11555     << LHS.get()->getType() << RHS.get()->getType()
11556     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11557 }
11558 
11559 static bool isObjCObjectLiteral(ExprResult &E) {
11560   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11561   case Stmt::ObjCArrayLiteralClass:
11562   case Stmt::ObjCDictionaryLiteralClass:
11563   case Stmt::ObjCStringLiteralClass:
11564   case Stmt::ObjCBoxedExprClass:
11565     return true;
11566   default:
11567     // Note that ObjCBoolLiteral is NOT an object literal!
11568     return false;
11569   }
11570 }
11571 
11572 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11573   const ObjCObjectPointerType *Type =
11574     LHS->getType()->getAs<ObjCObjectPointerType>();
11575 
11576   // If this is not actually an Objective-C object, bail out.
11577   if (!Type)
11578     return false;
11579 
11580   // Get the LHS object's interface type.
11581   QualType InterfaceType = Type->getPointeeType();
11582 
11583   // If the RHS isn't an Objective-C object, bail out.
11584   if (!RHS->getType()->isObjCObjectPointerType())
11585     return false;
11586 
11587   // Try to find the -isEqual: method.
11588   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11589   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11590                                                       InterfaceType,
11591                                                       /*IsInstance=*/true);
11592   if (!Method) {
11593     if (Type->isObjCIdType()) {
11594       // For 'id', just check the global pool.
11595       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11596                                                   /*receiverId=*/true);
11597     } else {
11598       // Check protocols.
11599       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11600                                              /*IsInstance=*/true);
11601     }
11602   }
11603 
11604   if (!Method)
11605     return false;
11606 
11607   QualType T = Method->parameters()[0]->getType();
11608   if (!T->isObjCObjectPointerType())
11609     return false;
11610 
11611   QualType R = Method->getReturnType();
11612   if (!R->isScalarType())
11613     return false;
11614 
11615   return true;
11616 }
11617 
11618 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11619   FromE = FromE->IgnoreParenImpCasts();
11620   switch (FromE->getStmtClass()) {
11621     default:
11622       break;
11623     case Stmt::ObjCStringLiteralClass:
11624       // "string literal"
11625       return LK_String;
11626     case Stmt::ObjCArrayLiteralClass:
11627       // "array literal"
11628       return LK_Array;
11629     case Stmt::ObjCDictionaryLiteralClass:
11630       // "dictionary literal"
11631       return LK_Dictionary;
11632     case Stmt::BlockExprClass:
11633       return LK_Block;
11634     case Stmt::ObjCBoxedExprClass: {
11635       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11636       switch (Inner->getStmtClass()) {
11637         case Stmt::IntegerLiteralClass:
11638         case Stmt::FloatingLiteralClass:
11639         case Stmt::CharacterLiteralClass:
11640         case Stmt::ObjCBoolLiteralExprClass:
11641         case Stmt::CXXBoolLiteralExprClass:
11642           // "numeric literal"
11643           return LK_Numeric;
11644         case Stmt::ImplicitCastExprClass: {
11645           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11646           // Boolean literals can be represented by implicit casts.
11647           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11648             return LK_Numeric;
11649           break;
11650         }
11651         default:
11652           break;
11653       }
11654       return LK_Boxed;
11655     }
11656   }
11657   return LK_None;
11658 }
11659 
11660 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11661                                           ExprResult &LHS, ExprResult &RHS,
11662                                           BinaryOperator::Opcode Opc){
11663   Expr *Literal;
11664   Expr *Other;
11665   if (isObjCObjectLiteral(LHS)) {
11666     Literal = LHS.get();
11667     Other = RHS.get();
11668   } else {
11669     Literal = RHS.get();
11670     Other = LHS.get();
11671   }
11672 
11673   // Don't warn on comparisons against nil.
11674   Other = Other->IgnoreParenCasts();
11675   if (Other->isNullPointerConstant(S.getASTContext(),
11676                                    Expr::NPC_ValueDependentIsNotNull))
11677     return;
11678 
11679   // This should be kept in sync with warn_objc_literal_comparison.
11680   // LK_String should always be after the other literals, since it has its own
11681   // warning flag.
11682   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11683   assert(LiteralKind != Sema::LK_Block);
11684   if (LiteralKind == Sema::LK_None) {
11685     llvm_unreachable("Unknown Objective-C object literal kind");
11686   }
11687 
11688   if (LiteralKind == Sema::LK_String)
11689     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11690       << Literal->getSourceRange();
11691   else
11692     S.Diag(Loc, diag::warn_objc_literal_comparison)
11693       << LiteralKind << Literal->getSourceRange();
11694 
11695   if (BinaryOperator::isEqualityOp(Opc) &&
11696       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11697     SourceLocation Start = LHS.get()->getBeginLoc();
11698     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11699     CharSourceRange OpRange =
11700       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11701 
11702     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11703       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11704       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11705       << FixItHint::CreateInsertion(End, "]");
11706   }
11707 }
11708 
11709 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11710 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11711                                            ExprResult &RHS, SourceLocation Loc,
11712                                            BinaryOperatorKind Opc) {
11713   // Check that left hand side is !something.
11714   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11715   if (!UO || UO->getOpcode() != UO_LNot) return;
11716 
11717   // Only check if the right hand side is non-bool arithmetic type.
11718   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11719 
11720   // Make sure that the something in !something is not bool.
11721   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11722   if (SubExpr->isKnownToHaveBooleanValue()) return;
11723 
11724   // Emit warning.
11725   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11726   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11727       << Loc << IsBitwiseOp;
11728 
11729   // First note suggest !(x < y)
11730   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11731   SourceLocation FirstClose = RHS.get()->getEndLoc();
11732   FirstClose = S.getLocForEndOfToken(FirstClose);
11733   if (FirstClose.isInvalid())
11734     FirstOpen = SourceLocation();
11735   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11736       << IsBitwiseOp
11737       << FixItHint::CreateInsertion(FirstOpen, "(")
11738       << FixItHint::CreateInsertion(FirstClose, ")");
11739 
11740   // Second note suggests (!x) < y
11741   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11742   SourceLocation SecondClose = LHS.get()->getEndLoc();
11743   SecondClose = S.getLocForEndOfToken(SecondClose);
11744   if (SecondClose.isInvalid())
11745     SecondOpen = SourceLocation();
11746   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11747       << FixItHint::CreateInsertion(SecondOpen, "(")
11748       << FixItHint::CreateInsertion(SecondClose, ")");
11749 }
11750 
11751 // Returns true if E refers to a non-weak array.
11752 static bool checkForArray(const Expr *E) {
11753   const ValueDecl *D = nullptr;
11754   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11755     D = DR->getDecl();
11756   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11757     if (Mem->isImplicitAccess())
11758       D = Mem->getMemberDecl();
11759   }
11760   if (!D)
11761     return false;
11762   return D->getType()->isArrayType() && !D->isWeak();
11763 }
11764 
11765 /// Diagnose some forms of syntactically-obvious tautological comparison.
11766 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11767                                            Expr *LHS, Expr *RHS,
11768                                            BinaryOperatorKind Opc) {
11769   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11770   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11771 
11772   QualType LHSType = LHS->getType();
11773   QualType RHSType = RHS->getType();
11774   if (LHSType->hasFloatingRepresentation() ||
11775       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11776       S.inTemplateInstantiation())
11777     return;
11778 
11779   // Comparisons between two array types are ill-formed for operator<=>, so
11780   // we shouldn't emit any additional warnings about it.
11781   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11782     return;
11783 
11784   // For non-floating point types, check for self-comparisons of the form
11785   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11786   // often indicate logic errors in the program.
11787   //
11788   // NOTE: Don't warn about comparison expressions resulting from macro
11789   // expansion. Also don't warn about comparisons which are only self
11790   // comparisons within a template instantiation. The warnings should catch
11791   // obvious cases in the definition of the template anyways. The idea is to
11792   // warn when the typed comparison operator will always evaluate to the same
11793   // result.
11794 
11795   // Used for indexing into %select in warn_comparison_always
11796   enum {
11797     AlwaysConstant,
11798     AlwaysTrue,
11799     AlwaysFalse,
11800     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11801   };
11802 
11803   // C++2a [depr.array.comp]:
11804   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11805   //   operands of array type are deprecated.
11806   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11807       RHSStripped->getType()->isArrayType()) {
11808     S.Diag(Loc, diag::warn_depr_array_comparison)
11809         << LHS->getSourceRange() << RHS->getSourceRange()
11810         << LHSStripped->getType() << RHSStripped->getType();
11811     // Carry on to produce the tautological comparison warning, if this
11812     // expression is potentially-evaluated, we can resolve the array to a
11813     // non-weak declaration, and so on.
11814   }
11815 
11816   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11817     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11818       unsigned Result;
11819       switch (Opc) {
11820       case BO_EQ:
11821       case BO_LE:
11822       case BO_GE:
11823         Result = AlwaysTrue;
11824         break;
11825       case BO_NE:
11826       case BO_LT:
11827       case BO_GT:
11828         Result = AlwaysFalse;
11829         break;
11830       case BO_Cmp:
11831         Result = AlwaysEqual;
11832         break;
11833       default:
11834         Result = AlwaysConstant;
11835         break;
11836       }
11837       S.DiagRuntimeBehavior(Loc, nullptr,
11838                             S.PDiag(diag::warn_comparison_always)
11839                                 << 0 /*self-comparison*/
11840                                 << Result);
11841     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11842       // What is it always going to evaluate to?
11843       unsigned Result;
11844       switch (Opc) {
11845       case BO_EQ: // e.g. array1 == array2
11846         Result = AlwaysFalse;
11847         break;
11848       case BO_NE: // e.g. array1 != array2
11849         Result = AlwaysTrue;
11850         break;
11851       default: // e.g. array1 <= array2
11852         // The best we can say is 'a constant'
11853         Result = AlwaysConstant;
11854         break;
11855       }
11856       S.DiagRuntimeBehavior(Loc, nullptr,
11857                             S.PDiag(diag::warn_comparison_always)
11858                                 << 1 /*array comparison*/
11859                                 << Result);
11860     }
11861   }
11862 
11863   if (isa<CastExpr>(LHSStripped))
11864     LHSStripped = LHSStripped->IgnoreParenCasts();
11865   if (isa<CastExpr>(RHSStripped))
11866     RHSStripped = RHSStripped->IgnoreParenCasts();
11867 
11868   // Warn about comparisons against a string constant (unless the other
11869   // operand is null); the user probably wants string comparison function.
11870   Expr *LiteralString = nullptr;
11871   Expr *LiteralStringStripped = nullptr;
11872   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11873       !RHSStripped->isNullPointerConstant(S.Context,
11874                                           Expr::NPC_ValueDependentIsNull)) {
11875     LiteralString = LHS;
11876     LiteralStringStripped = LHSStripped;
11877   } else if ((isa<StringLiteral>(RHSStripped) ||
11878               isa<ObjCEncodeExpr>(RHSStripped)) &&
11879              !LHSStripped->isNullPointerConstant(S.Context,
11880                                           Expr::NPC_ValueDependentIsNull)) {
11881     LiteralString = RHS;
11882     LiteralStringStripped = RHSStripped;
11883   }
11884 
11885   if (LiteralString) {
11886     S.DiagRuntimeBehavior(Loc, nullptr,
11887                           S.PDiag(diag::warn_stringcompare)
11888                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11889                               << LiteralString->getSourceRange());
11890   }
11891 }
11892 
11893 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11894   switch (CK) {
11895   default: {
11896 #ifndef NDEBUG
11897     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11898                  << "\n";
11899 #endif
11900     llvm_unreachable("unhandled cast kind");
11901   }
11902   case CK_UserDefinedConversion:
11903     return ICK_Identity;
11904   case CK_LValueToRValue:
11905     return ICK_Lvalue_To_Rvalue;
11906   case CK_ArrayToPointerDecay:
11907     return ICK_Array_To_Pointer;
11908   case CK_FunctionToPointerDecay:
11909     return ICK_Function_To_Pointer;
11910   case CK_IntegralCast:
11911     return ICK_Integral_Conversion;
11912   case CK_FloatingCast:
11913     return ICK_Floating_Conversion;
11914   case CK_IntegralToFloating:
11915   case CK_FloatingToIntegral:
11916     return ICK_Floating_Integral;
11917   case CK_IntegralComplexCast:
11918   case CK_FloatingComplexCast:
11919   case CK_FloatingComplexToIntegralComplex:
11920   case CK_IntegralComplexToFloatingComplex:
11921     return ICK_Complex_Conversion;
11922   case CK_FloatingComplexToReal:
11923   case CK_FloatingRealToComplex:
11924   case CK_IntegralComplexToReal:
11925   case CK_IntegralRealToComplex:
11926     return ICK_Complex_Real;
11927   }
11928 }
11929 
11930 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11931                                              QualType FromType,
11932                                              SourceLocation Loc) {
11933   // Check for a narrowing implicit conversion.
11934   StandardConversionSequence SCS;
11935   SCS.setAsIdentityConversion();
11936   SCS.setToType(0, FromType);
11937   SCS.setToType(1, ToType);
11938   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11939     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11940 
11941   APValue PreNarrowingValue;
11942   QualType PreNarrowingType;
11943   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11944                                PreNarrowingType,
11945                                /*IgnoreFloatToIntegralConversion*/ true)) {
11946   case NK_Dependent_Narrowing:
11947     // Implicit conversion to a narrower type, but the expression is
11948     // value-dependent so we can't tell whether it's actually narrowing.
11949   case NK_Not_Narrowing:
11950     return false;
11951 
11952   case NK_Constant_Narrowing:
11953     // Implicit conversion to a narrower type, and the value is not a constant
11954     // expression.
11955     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11956         << /*Constant*/ 1
11957         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11958     return true;
11959 
11960   case NK_Variable_Narrowing:
11961     // Implicit conversion to a narrower type, and the value is not a constant
11962     // expression.
11963   case NK_Type_Narrowing:
11964     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11965         << /*Constant*/ 0 << FromType << ToType;
11966     // TODO: It's not a constant expression, but what if the user intended it
11967     // to be? Can we produce notes to help them figure out why it isn't?
11968     return true;
11969   }
11970   llvm_unreachable("unhandled case in switch");
11971 }
11972 
11973 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11974                                                          ExprResult &LHS,
11975                                                          ExprResult &RHS,
11976                                                          SourceLocation Loc) {
11977   QualType LHSType = LHS.get()->getType();
11978   QualType RHSType = RHS.get()->getType();
11979   // Dig out the original argument type and expression before implicit casts
11980   // were applied. These are the types/expressions we need to check the
11981   // [expr.spaceship] requirements against.
11982   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11983   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11984   QualType LHSStrippedType = LHSStripped.get()->getType();
11985   QualType RHSStrippedType = RHSStripped.get()->getType();
11986 
11987   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11988   // other is not, the program is ill-formed.
11989   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11990     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11991     return QualType();
11992   }
11993 
11994   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11995   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11996                     RHSStrippedType->isEnumeralType();
11997   if (NumEnumArgs == 1) {
11998     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11999     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12000     if (OtherTy->hasFloatingRepresentation()) {
12001       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12002       return QualType();
12003     }
12004   }
12005   if (NumEnumArgs == 2) {
12006     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12007     // type E, the operator yields the result of converting the operands
12008     // to the underlying type of E and applying <=> to the converted operands.
12009     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12010       S.InvalidOperands(Loc, LHS, RHS);
12011       return QualType();
12012     }
12013     QualType IntType =
12014         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12015     assert(IntType->isArithmeticType());
12016 
12017     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12018     // promote the boolean type, and all other promotable integer types, to
12019     // avoid this.
12020     if (IntType->isPromotableIntegerType())
12021       IntType = S.Context.getPromotedIntegerType(IntType);
12022 
12023     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12024     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12025     LHSType = RHSType = IntType;
12026   }
12027 
12028   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12029   // usual arithmetic conversions are applied to the operands.
12030   QualType Type =
12031       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12032   if (LHS.isInvalid() || RHS.isInvalid())
12033     return QualType();
12034   if (Type.isNull())
12035     return S.InvalidOperands(Loc, LHS, RHS);
12036 
12037   Optional<ComparisonCategoryType> CCT =
12038       getComparisonCategoryForBuiltinCmp(Type);
12039   if (!CCT)
12040     return S.InvalidOperands(Loc, LHS, RHS);
12041 
12042   bool HasNarrowing = checkThreeWayNarrowingConversion(
12043       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12044   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12045                                                    RHS.get()->getBeginLoc());
12046   if (HasNarrowing)
12047     return QualType();
12048 
12049   assert(!Type.isNull() && "composite type for <=> has not been set");
12050 
12051   return S.CheckComparisonCategoryType(
12052       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12053 }
12054 
12055 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12056                                                  ExprResult &RHS,
12057                                                  SourceLocation Loc,
12058                                                  BinaryOperatorKind Opc) {
12059   if (Opc == BO_Cmp)
12060     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12061 
12062   // C99 6.5.8p3 / C99 6.5.9p4
12063   QualType Type =
12064       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12065   if (LHS.isInvalid() || RHS.isInvalid())
12066     return QualType();
12067   if (Type.isNull())
12068     return S.InvalidOperands(Loc, LHS, RHS);
12069   assert(Type->isArithmeticType() || Type->isEnumeralType());
12070 
12071   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12072     return S.InvalidOperands(Loc, LHS, RHS);
12073 
12074   // Check for comparisons of floating point operands using != and ==.
12075   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12076     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12077 
12078   // The result of comparisons is 'bool' in C++, 'int' in C.
12079   return S.Context.getLogicalOperationType();
12080 }
12081 
12082 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12083   if (!NullE.get()->getType()->isAnyPointerType())
12084     return;
12085   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12086   if (!E.get()->getType()->isAnyPointerType() &&
12087       E.get()->isNullPointerConstant(Context,
12088                                      Expr::NPC_ValueDependentIsNotNull) ==
12089         Expr::NPCK_ZeroExpression) {
12090     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12091       if (CL->getValue() == 0)
12092         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12093             << NullValue
12094             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12095                                             NullValue ? "NULL" : "(void *)0");
12096     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12097         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12098         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12099         if (T == Context.CharTy)
12100           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12101               << NullValue
12102               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12103                                               NullValue ? "NULL" : "(void *)0");
12104       }
12105   }
12106 }
12107 
12108 // C99 6.5.8, C++ [expr.rel]
12109 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12110                                     SourceLocation Loc,
12111                                     BinaryOperatorKind Opc) {
12112   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12113   bool IsThreeWay = Opc == BO_Cmp;
12114   bool IsOrdered = IsRelational || IsThreeWay;
12115   auto IsAnyPointerType = [](ExprResult E) {
12116     QualType Ty = E.get()->getType();
12117     return Ty->isPointerType() || Ty->isMemberPointerType();
12118   };
12119 
12120   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12121   // type, array-to-pointer, ..., conversions are performed on both operands to
12122   // bring them to their composite type.
12123   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12124   // any type-related checks.
12125   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12126     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12127     if (LHS.isInvalid())
12128       return QualType();
12129     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12130     if (RHS.isInvalid())
12131       return QualType();
12132   } else {
12133     LHS = DefaultLvalueConversion(LHS.get());
12134     if (LHS.isInvalid())
12135       return QualType();
12136     RHS = DefaultLvalueConversion(RHS.get());
12137     if (RHS.isInvalid())
12138       return QualType();
12139   }
12140 
12141   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12142   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12143     CheckPtrComparisonWithNullChar(LHS, RHS);
12144     CheckPtrComparisonWithNullChar(RHS, LHS);
12145   }
12146 
12147   // Handle vector comparisons separately.
12148   if (LHS.get()->getType()->isVectorType() ||
12149       RHS.get()->getType()->isVectorType())
12150     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12151 
12152   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12153   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12154 
12155   QualType LHSType = LHS.get()->getType();
12156   QualType RHSType = RHS.get()->getType();
12157   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12158       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12159     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12160 
12161   const Expr::NullPointerConstantKind LHSNullKind =
12162       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12163   const Expr::NullPointerConstantKind RHSNullKind =
12164       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12165   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12166   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12167 
12168   auto computeResultTy = [&]() {
12169     if (Opc != BO_Cmp)
12170       return Context.getLogicalOperationType();
12171     assert(getLangOpts().CPlusPlus);
12172     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12173 
12174     QualType CompositeTy = LHS.get()->getType();
12175     assert(!CompositeTy->isReferenceType());
12176 
12177     Optional<ComparisonCategoryType> CCT =
12178         getComparisonCategoryForBuiltinCmp(CompositeTy);
12179     if (!CCT)
12180       return InvalidOperands(Loc, LHS, RHS);
12181 
12182     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12183       // P0946R0: Comparisons between a null pointer constant and an object
12184       // pointer result in std::strong_equality, which is ill-formed under
12185       // P1959R0.
12186       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12187           << (LHSIsNull ? LHS.get()->getSourceRange()
12188                         : RHS.get()->getSourceRange());
12189       return QualType();
12190     }
12191 
12192     return CheckComparisonCategoryType(
12193         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12194   };
12195 
12196   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12197     bool IsEquality = Opc == BO_EQ;
12198     if (RHSIsNull)
12199       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12200                                    RHS.get()->getSourceRange());
12201     else
12202       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12203                                    LHS.get()->getSourceRange());
12204   }
12205 
12206   if (IsOrdered && LHSType->isFunctionPointerType() &&
12207       RHSType->isFunctionPointerType()) {
12208     // Valid unless a relational comparison of function pointers
12209     bool IsError = Opc == BO_Cmp;
12210     auto DiagID =
12211         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12212         : getLangOpts().CPlusPlus
12213             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12214             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12215     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12216                       << RHS.get()->getSourceRange();
12217     if (IsError)
12218       return QualType();
12219   }
12220 
12221   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12222       (RHSType->isIntegerType() && !RHSIsNull)) {
12223     // Skip normal pointer conversion checks in this case; we have better
12224     // diagnostics for this below.
12225   } else if (getLangOpts().CPlusPlus) {
12226     // Equality comparison of a function pointer to a void pointer is invalid,
12227     // but we allow it as an extension.
12228     // FIXME: If we really want to allow this, should it be part of composite
12229     // pointer type computation so it works in conditionals too?
12230     if (!IsOrdered &&
12231         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12232          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12233       // This is a gcc extension compatibility comparison.
12234       // In a SFINAE context, we treat this as a hard error to maintain
12235       // conformance with the C++ standard.
12236       diagnoseFunctionPointerToVoidComparison(
12237           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12238 
12239       if (isSFINAEContext())
12240         return QualType();
12241 
12242       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12243       return computeResultTy();
12244     }
12245 
12246     // C++ [expr.eq]p2:
12247     //   If at least one operand is a pointer [...] bring them to their
12248     //   composite pointer type.
12249     // C++ [expr.spaceship]p6
12250     //  If at least one of the operands is of pointer type, [...] bring them
12251     //  to their composite pointer type.
12252     // C++ [expr.rel]p2:
12253     //   If both operands are pointers, [...] bring them to their composite
12254     //   pointer type.
12255     // For <=>, the only valid non-pointer types are arrays and functions, and
12256     // we already decayed those, so this is really the same as the relational
12257     // comparison rule.
12258     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12259             (IsOrdered ? 2 : 1) &&
12260         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12261                                          RHSType->isObjCObjectPointerType()))) {
12262       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12263         return QualType();
12264       return computeResultTy();
12265     }
12266   } else if (LHSType->isPointerType() &&
12267              RHSType->isPointerType()) { // C99 6.5.8p2
12268     // All of the following pointer-related warnings are GCC extensions, except
12269     // when handling null pointer constants.
12270     QualType LCanPointeeTy =
12271       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12272     QualType RCanPointeeTy =
12273       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12274 
12275     // C99 6.5.9p2 and C99 6.5.8p2
12276     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12277                                    RCanPointeeTy.getUnqualifiedType())) {
12278       if (IsRelational) {
12279         // Pointers both need to point to complete or incomplete types
12280         if ((LCanPointeeTy->isIncompleteType() !=
12281              RCanPointeeTy->isIncompleteType()) &&
12282             !getLangOpts().C11) {
12283           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12284               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12285               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12286               << RCanPointeeTy->isIncompleteType();
12287         }
12288       }
12289     } else if (!IsRelational &&
12290                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12291       // Valid unless comparison between non-null pointer and function pointer
12292       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12293           && !LHSIsNull && !RHSIsNull)
12294         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12295                                                 /*isError*/false);
12296     } else {
12297       // Invalid
12298       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12299     }
12300     if (LCanPointeeTy != RCanPointeeTy) {
12301       // Treat NULL constant as a special case in OpenCL.
12302       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12303         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12304           Diag(Loc,
12305                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12306               << LHSType << RHSType << 0 /* comparison */
12307               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12308         }
12309       }
12310       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12311       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12312       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12313                                                : CK_BitCast;
12314       if (LHSIsNull && !RHSIsNull)
12315         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12316       else
12317         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12318     }
12319     return computeResultTy();
12320   }
12321 
12322   if (getLangOpts().CPlusPlus) {
12323     // C++ [expr.eq]p4:
12324     //   Two operands of type std::nullptr_t or one operand of type
12325     //   std::nullptr_t and the other a null pointer constant compare equal.
12326     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12327       if (LHSType->isNullPtrType()) {
12328         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12329         return computeResultTy();
12330       }
12331       if (RHSType->isNullPtrType()) {
12332         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12333         return computeResultTy();
12334       }
12335     }
12336 
12337     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12338     // These aren't covered by the composite pointer type rules.
12339     if (!IsOrdered && RHSType->isNullPtrType() &&
12340         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12341       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12342       return computeResultTy();
12343     }
12344     if (!IsOrdered && LHSType->isNullPtrType() &&
12345         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12346       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12347       return computeResultTy();
12348     }
12349 
12350     if (IsRelational &&
12351         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12352          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12353       // HACK: Relational comparison of nullptr_t against a pointer type is
12354       // invalid per DR583, but we allow it within std::less<> and friends,
12355       // since otherwise common uses of it break.
12356       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12357       // friends to have std::nullptr_t overload candidates.
12358       DeclContext *DC = CurContext;
12359       if (isa<FunctionDecl>(DC))
12360         DC = DC->getParent();
12361       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12362         if (CTSD->isInStdNamespace() &&
12363             llvm::StringSwitch<bool>(CTSD->getName())
12364                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12365                 .Default(false)) {
12366           if (RHSType->isNullPtrType())
12367             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12368           else
12369             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12370           return computeResultTy();
12371         }
12372       }
12373     }
12374 
12375     // C++ [expr.eq]p2:
12376     //   If at least one operand is a pointer to member, [...] bring them to
12377     //   their composite pointer type.
12378     if (!IsOrdered &&
12379         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12380       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12381         return QualType();
12382       else
12383         return computeResultTy();
12384     }
12385   }
12386 
12387   // Handle block pointer types.
12388   if (!IsOrdered && LHSType->isBlockPointerType() &&
12389       RHSType->isBlockPointerType()) {
12390     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12391     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12392 
12393     if (!LHSIsNull && !RHSIsNull &&
12394         !Context.typesAreCompatible(lpointee, rpointee)) {
12395       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12396         << LHSType << RHSType << LHS.get()->getSourceRange()
12397         << RHS.get()->getSourceRange();
12398     }
12399     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12400     return computeResultTy();
12401   }
12402 
12403   // Allow block pointers to be compared with null pointer constants.
12404   if (!IsOrdered
12405       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12406           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12407     if (!LHSIsNull && !RHSIsNull) {
12408       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12409              ->getPointeeType()->isVoidType())
12410             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12411                 ->getPointeeType()->isVoidType())))
12412         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12413           << LHSType << RHSType << LHS.get()->getSourceRange()
12414           << RHS.get()->getSourceRange();
12415     }
12416     if (LHSIsNull && !RHSIsNull)
12417       LHS = ImpCastExprToType(LHS.get(), RHSType,
12418                               RHSType->isPointerType() ? CK_BitCast
12419                                 : CK_AnyPointerToBlockPointerCast);
12420     else
12421       RHS = ImpCastExprToType(RHS.get(), LHSType,
12422                               LHSType->isPointerType() ? CK_BitCast
12423                                 : CK_AnyPointerToBlockPointerCast);
12424     return computeResultTy();
12425   }
12426 
12427   if (LHSType->isObjCObjectPointerType() ||
12428       RHSType->isObjCObjectPointerType()) {
12429     const PointerType *LPT = LHSType->getAs<PointerType>();
12430     const PointerType *RPT = RHSType->getAs<PointerType>();
12431     if (LPT || RPT) {
12432       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12433       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12434 
12435       if (!LPtrToVoid && !RPtrToVoid &&
12436           !Context.typesAreCompatible(LHSType, RHSType)) {
12437         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12438                                           /*isError*/false);
12439       }
12440       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12441       // the RHS, but we have test coverage for this behavior.
12442       // FIXME: Consider using convertPointersToCompositeType in C++.
12443       if (LHSIsNull && !RHSIsNull) {
12444         Expr *E = LHS.get();
12445         if (getLangOpts().ObjCAutoRefCount)
12446           CheckObjCConversion(SourceRange(), RHSType, E,
12447                               CCK_ImplicitConversion);
12448         LHS = ImpCastExprToType(E, RHSType,
12449                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12450       }
12451       else {
12452         Expr *E = RHS.get();
12453         if (getLangOpts().ObjCAutoRefCount)
12454           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12455                               /*Diagnose=*/true,
12456                               /*DiagnoseCFAudited=*/false, Opc);
12457         RHS = ImpCastExprToType(E, LHSType,
12458                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12459       }
12460       return computeResultTy();
12461     }
12462     if (LHSType->isObjCObjectPointerType() &&
12463         RHSType->isObjCObjectPointerType()) {
12464       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12465         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12466                                           /*isError*/false);
12467       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12468         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12469 
12470       if (LHSIsNull && !RHSIsNull)
12471         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12472       else
12473         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12474       return computeResultTy();
12475     }
12476 
12477     if (!IsOrdered && LHSType->isBlockPointerType() &&
12478         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12479       LHS = ImpCastExprToType(LHS.get(), RHSType,
12480                               CK_BlockPointerToObjCPointerCast);
12481       return computeResultTy();
12482     } else if (!IsOrdered &&
12483                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12484                RHSType->isBlockPointerType()) {
12485       RHS = ImpCastExprToType(RHS.get(), LHSType,
12486                               CK_BlockPointerToObjCPointerCast);
12487       return computeResultTy();
12488     }
12489   }
12490   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12491       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12492     unsigned DiagID = 0;
12493     bool isError = false;
12494     if (LangOpts.DebuggerSupport) {
12495       // Under a debugger, allow the comparison of pointers to integers,
12496       // since users tend to want to compare addresses.
12497     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12498                (RHSIsNull && RHSType->isIntegerType())) {
12499       if (IsOrdered) {
12500         isError = getLangOpts().CPlusPlus;
12501         DiagID =
12502           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12503                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12504       }
12505     } else if (getLangOpts().CPlusPlus) {
12506       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12507       isError = true;
12508     } else if (IsOrdered)
12509       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12510     else
12511       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12512 
12513     if (DiagID) {
12514       Diag(Loc, DiagID)
12515         << LHSType << RHSType << LHS.get()->getSourceRange()
12516         << RHS.get()->getSourceRange();
12517       if (isError)
12518         return QualType();
12519     }
12520 
12521     if (LHSType->isIntegerType())
12522       LHS = ImpCastExprToType(LHS.get(), RHSType,
12523                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12524     else
12525       RHS = ImpCastExprToType(RHS.get(), LHSType,
12526                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12527     return computeResultTy();
12528   }
12529 
12530   // Handle block pointers.
12531   if (!IsOrdered && RHSIsNull
12532       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12533     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12534     return computeResultTy();
12535   }
12536   if (!IsOrdered && LHSIsNull
12537       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12538     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12539     return computeResultTy();
12540   }
12541 
12542   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12543     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12544       return computeResultTy();
12545     }
12546 
12547     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12548       return computeResultTy();
12549     }
12550 
12551     if (LHSIsNull && RHSType->isQueueT()) {
12552       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12553       return computeResultTy();
12554     }
12555 
12556     if (LHSType->isQueueT() && RHSIsNull) {
12557       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12558       return computeResultTy();
12559     }
12560   }
12561 
12562   return InvalidOperands(Loc, LHS, RHS);
12563 }
12564 
12565 // Return a signed ext_vector_type that is of identical size and number of
12566 // elements. For floating point vectors, return an integer type of identical
12567 // size and number of elements. In the non ext_vector_type case, search from
12568 // the largest type to the smallest type to avoid cases where long long == long,
12569 // where long gets picked over long long.
12570 QualType Sema::GetSignedVectorType(QualType V) {
12571   const VectorType *VTy = V->castAs<VectorType>();
12572   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12573 
12574   if (isa<ExtVectorType>(VTy)) {
12575     if (VTy->isExtVectorBoolType())
12576       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12577     if (TypeSize == Context.getTypeSize(Context.CharTy))
12578       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12579     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12580       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12581     if (TypeSize == Context.getTypeSize(Context.IntTy))
12582       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12583     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12584       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12585     if (TypeSize == Context.getTypeSize(Context.LongTy))
12586       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12587     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12588            "Unhandled vector element size in vector compare");
12589     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12590   }
12591 
12592   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12593     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12594                                  VectorType::GenericVector);
12595   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12596     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12597                                  VectorType::GenericVector);
12598   if (TypeSize == Context.getTypeSize(Context.LongTy))
12599     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12600                                  VectorType::GenericVector);
12601   if (TypeSize == Context.getTypeSize(Context.IntTy))
12602     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12603                                  VectorType::GenericVector);
12604   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12605     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12606                                  VectorType::GenericVector);
12607   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12608          "Unhandled vector element size in vector compare");
12609   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12610                                VectorType::GenericVector);
12611 }
12612 
12613 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12614 /// operates on extended vector types.  Instead of producing an IntTy result,
12615 /// like a scalar comparison, a vector comparison produces a vector of integer
12616 /// types.
12617 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12618                                           SourceLocation Loc,
12619                                           BinaryOperatorKind Opc) {
12620   if (Opc == BO_Cmp) {
12621     Diag(Loc, diag::err_three_way_vector_comparison);
12622     return QualType();
12623   }
12624 
12625   // Check to make sure we're operating on vectors of the same type and width,
12626   // Allowing one side to be a scalar of element type.
12627   QualType vType =
12628       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12629                           /*AllowBothBool*/ true,
12630                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12631                           /*AllowBooleanOperation*/ true,
12632                           /*ReportInvalid*/ true);
12633   if (vType.isNull())
12634     return vType;
12635 
12636   QualType LHSType = LHS.get()->getType();
12637 
12638   // Determine the return type of a vector compare. By default clang will return
12639   // a scalar for all vector compares except vector bool and vector pixel.
12640   // With the gcc compiler we will always return a vector type and with the xl
12641   // compiler we will always return a scalar type. This switch allows choosing
12642   // which behavior is prefered.
12643   if (getLangOpts().AltiVec) {
12644     switch (getLangOpts().getAltivecSrcCompat()) {
12645     case LangOptions::AltivecSrcCompatKind::Mixed:
12646       // If AltiVec, the comparison results in a numeric type, i.e.
12647       // bool for C++, int for C
12648       if (vType->castAs<VectorType>()->getVectorKind() ==
12649           VectorType::AltiVecVector)
12650         return Context.getLogicalOperationType();
12651       else
12652         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12653       break;
12654     case LangOptions::AltivecSrcCompatKind::GCC:
12655       // For GCC we always return the vector type.
12656       break;
12657     case LangOptions::AltivecSrcCompatKind::XL:
12658       return Context.getLogicalOperationType();
12659       break;
12660     }
12661   }
12662 
12663   // For non-floating point types, check for self-comparisons of the form
12664   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12665   // often indicate logic errors in the program.
12666   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12667 
12668   // Check for comparisons of floating point operands using != and ==.
12669   if (BinaryOperator::isEqualityOp(Opc) &&
12670       LHSType->hasFloatingRepresentation()) {
12671     assert(RHS.get()->getType()->hasFloatingRepresentation());
12672     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12673   }
12674 
12675   // Return a signed type for the vector.
12676   return GetSignedVectorType(vType);
12677 }
12678 
12679 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12680                                     const ExprResult &XorRHS,
12681                                     const SourceLocation Loc) {
12682   // Do not diagnose macros.
12683   if (Loc.isMacroID())
12684     return;
12685 
12686   // Do not diagnose if both LHS and RHS are macros.
12687   if (XorLHS.get()->getExprLoc().isMacroID() &&
12688       XorRHS.get()->getExprLoc().isMacroID())
12689     return;
12690 
12691   bool Negative = false;
12692   bool ExplicitPlus = false;
12693   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12694   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12695 
12696   if (!LHSInt)
12697     return;
12698   if (!RHSInt) {
12699     // Check negative literals.
12700     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12701       UnaryOperatorKind Opc = UO->getOpcode();
12702       if (Opc != UO_Minus && Opc != UO_Plus)
12703         return;
12704       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12705       if (!RHSInt)
12706         return;
12707       Negative = (Opc == UO_Minus);
12708       ExplicitPlus = !Negative;
12709     } else {
12710       return;
12711     }
12712   }
12713 
12714   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12715   llvm::APInt RightSideValue = RHSInt->getValue();
12716   if (LeftSideValue != 2 && LeftSideValue != 10)
12717     return;
12718 
12719   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12720     return;
12721 
12722   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12723       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12724   llvm::StringRef ExprStr =
12725       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12726 
12727   CharSourceRange XorRange =
12728       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12729   llvm::StringRef XorStr =
12730       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12731   // Do not diagnose if xor keyword/macro is used.
12732   if (XorStr == "xor")
12733     return;
12734 
12735   std::string LHSStr = std::string(Lexer::getSourceText(
12736       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12737       S.getSourceManager(), S.getLangOpts()));
12738   std::string RHSStr = std::string(Lexer::getSourceText(
12739       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12740       S.getSourceManager(), S.getLangOpts()));
12741 
12742   if (Negative) {
12743     RightSideValue = -RightSideValue;
12744     RHSStr = "-" + RHSStr;
12745   } else if (ExplicitPlus) {
12746     RHSStr = "+" + RHSStr;
12747   }
12748 
12749   StringRef LHSStrRef = LHSStr;
12750   StringRef RHSStrRef = RHSStr;
12751   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12752   // literals.
12753   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12754       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12755       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12756       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12757       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12758       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12759       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12760     return;
12761 
12762   bool SuggestXor =
12763       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12764   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12765   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12766   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12767     std::string SuggestedExpr = "1 << " + RHSStr;
12768     bool Overflow = false;
12769     llvm::APInt One = (LeftSideValue - 1);
12770     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12771     if (Overflow) {
12772       if (RightSideIntValue < 64)
12773         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12774             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12775             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12776       else if (RightSideIntValue == 64)
12777         S.Diag(Loc, diag::warn_xor_used_as_pow)
12778             << ExprStr << toString(XorValue, 10, true);
12779       else
12780         return;
12781     } else {
12782       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12783           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12784           << toString(PowValue, 10, true)
12785           << FixItHint::CreateReplacement(
12786                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12787     }
12788 
12789     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12790         << ("0x2 ^ " + RHSStr) << SuggestXor;
12791   } else if (LeftSideValue == 10) {
12792     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12793     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12794         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12795         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12796     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12797         << ("0xA ^ " + RHSStr) << SuggestXor;
12798   }
12799 }
12800 
12801 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12802                                           SourceLocation Loc) {
12803   // Ensure that either both operands are of the same vector type, or
12804   // one operand is of a vector type and the other is of its element type.
12805   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12806                                        /*AllowBothBool*/ true,
12807                                        /*AllowBoolConversions*/ false,
12808                                        /*AllowBooleanOperation*/ false,
12809                                        /*ReportInvalid*/ false);
12810   if (vType.isNull())
12811     return InvalidOperands(Loc, LHS, RHS);
12812   if (getLangOpts().OpenCL &&
12813       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12814       vType->hasFloatingRepresentation())
12815     return InvalidOperands(Loc, LHS, RHS);
12816   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12817   //        usage of the logical operators && and || with vectors in C. This
12818   //        check could be notionally dropped.
12819   if (!getLangOpts().CPlusPlus &&
12820       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12821     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12822 
12823   return GetSignedVectorType(LHS.get()->getType());
12824 }
12825 
12826 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12827                                               SourceLocation Loc,
12828                                               bool IsCompAssign) {
12829   if (!IsCompAssign) {
12830     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12831     if (LHS.isInvalid())
12832       return QualType();
12833   }
12834   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12835   if (RHS.isInvalid())
12836     return QualType();
12837 
12838   // For conversion purposes, we ignore any qualifiers.
12839   // For example, "const float" and "float" are equivalent.
12840   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12841   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12842 
12843   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12844   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12845   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12846 
12847   if (Context.hasSameType(LHSType, RHSType))
12848     return LHSType;
12849 
12850   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12851   // case we have to return InvalidOperands.
12852   ExprResult OriginalLHS = LHS;
12853   ExprResult OriginalRHS = RHS;
12854   if (LHSMatType && !RHSMatType) {
12855     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12856     if (!RHS.isInvalid())
12857       return LHSType;
12858 
12859     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12860   }
12861 
12862   if (!LHSMatType && RHSMatType) {
12863     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12864     if (!LHS.isInvalid())
12865       return RHSType;
12866     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12867   }
12868 
12869   return InvalidOperands(Loc, LHS, RHS);
12870 }
12871 
12872 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12873                                            SourceLocation Loc,
12874                                            bool IsCompAssign) {
12875   if (!IsCompAssign) {
12876     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12877     if (LHS.isInvalid())
12878       return QualType();
12879   }
12880   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12881   if (RHS.isInvalid())
12882     return QualType();
12883 
12884   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12885   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12886   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12887 
12888   if (LHSMatType && RHSMatType) {
12889     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12890       return InvalidOperands(Loc, LHS, RHS);
12891 
12892     if (!Context.hasSameType(LHSMatType->getElementType(),
12893                              RHSMatType->getElementType()))
12894       return InvalidOperands(Loc, LHS, RHS);
12895 
12896     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12897                                          LHSMatType->getNumRows(),
12898                                          RHSMatType->getNumColumns());
12899   }
12900   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12901 }
12902 
12903 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
12904   switch (Opc) {
12905   default:
12906     return false;
12907   case BO_And:
12908   case BO_AndAssign:
12909   case BO_Or:
12910   case BO_OrAssign:
12911   case BO_Xor:
12912   case BO_XorAssign:
12913     return true;
12914   }
12915 }
12916 
12917 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12918                                            SourceLocation Loc,
12919                                            BinaryOperatorKind Opc) {
12920   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12921 
12922   bool IsCompAssign =
12923       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12924 
12925   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12926 
12927   if (LHS.get()->getType()->isVectorType() ||
12928       RHS.get()->getType()->isVectorType()) {
12929     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12930         RHS.get()->getType()->hasIntegerRepresentation())
12931       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12932                                  /*AllowBothBool*/ true,
12933                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
12934                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
12935                                  /*ReportInvalid*/ true);
12936     return InvalidOperands(Loc, LHS, RHS);
12937   }
12938 
12939   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12940       RHS.get()->getType()->isVLSTBuiltinType()) {
12941     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12942         RHS.get()->getType()->hasIntegerRepresentation())
12943       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12944                                          ACK_BitwiseOp);
12945     return InvalidOperands(Loc, LHS, RHS);
12946   }
12947 
12948   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12949       RHS.get()->getType()->isVLSTBuiltinType()) {
12950     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12951         RHS.get()->getType()->hasIntegerRepresentation())
12952       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12953                                          ACK_BitwiseOp);
12954     return InvalidOperands(Loc, LHS, RHS);
12955   }
12956 
12957   if (Opc == BO_And)
12958     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12959 
12960   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12961       RHS.get()->getType()->hasFloatingRepresentation())
12962     return InvalidOperands(Loc, LHS, RHS);
12963 
12964   ExprResult LHSResult = LHS, RHSResult = RHS;
12965   QualType compType = UsualArithmeticConversions(
12966       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12967   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12968     return QualType();
12969   LHS = LHSResult.get();
12970   RHS = RHSResult.get();
12971 
12972   if (Opc == BO_Xor)
12973     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12974 
12975   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12976     return compType;
12977   return InvalidOperands(Loc, LHS, RHS);
12978 }
12979 
12980 // C99 6.5.[13,14]
12981 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12982                                            SourceLocation Loc,
12983                                            BinaryOperatorKind Opc) {
12984   // Check vector operands differently.
12985   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12986     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12987 
12988   bool EnumConstantInBoolContext = false;
12989   for (const ExprResult &HS : {LHS, RHS}) {
12990     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12991       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12992       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12993         EnumConstantInBoolContext = true;
12994     }
12995   }
12996 
12997   if (EnumConstantInBoolContext)
12998     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12999 
13000   // Diagnose cases where the user write a logical and/or but probably meant a
13001   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13002   // is a constant.
13003   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13004       !LHS.get()->getType()->isBooleanType() &&
13005       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13006       // Don't warn in macros or template instantiations.
13007       !Loc.isMacroID() && !inTemplateInstantiation()) {
13008     // If the RHS can be constant folded, and if it constant folds to something
13009     // that isn't 0 or 1 (which indicate a potential logical operation that
13010     // happened to fold to true/false) then warn.
13011     // Parens on the RHS are ignored.
13012     Expr::EvalResult EVResult;
13013     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13014       llvm::APSInt Result = EVResult.Val.getInt();
13015       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13016            !RHS.get()->getExprLoc().isMacroID()) ||
13017           (Result != 0 && Result != 1)) {
13018         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13019           << RHS.get()->getSourceRange()
13020           << (Opc == BO_LAnd ? "&&" : "||");
13021         // Suggest replacing the logical operator with the bitwise version
13022         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13023             << (Opc == BO_LAnd ? "&" : "|")
13024             << FixItHint::CreateReplacement(SourceRange(
13025                                                  Loc, getLocForEndOfToken(Loc)),
13026                                             Opc == BO_LAnd ? "&" : "|");
13027         if (Opc == BO_LAnd)
13028           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13029           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13030               << FixItHint::CreateRemoval(
13031                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13032                                  RHS.get()->getEndLoc()));
13033       }
13034     }
13035   }
13036 
13037   if (!Context.getLangOpts().CPlusPlus) {
13038     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13039     // not operate on the built-in scalar and vector float types.
13040     if (Context.getLangOpts().OpenCL &&
13041         Context.getLangOpts().OpenCLVersion < 120) {
13042       if (LHS.get()->getType()->isFloatingType() ||
13043           RHS.get()->getType()->isFloatingType())
13044         return InvalidOperands(Loc, LHS, RHS);
13045     }
13046 
13047     LHS = UsualUnaryConversions(LHS.get());
13048     if (LHS.isInvalid())
13049       return QualType();
13050 
13051     RHS = UsualUnaryConversions(RHS.get());
13052     if (RHS.isInvalid())
13053       return QualType();
13054 
13055     if (!LHS.get()->getType()->isScalarType() ||
13056         !RHS.get()->getType()->isScalarType())
13057       return InvalidOperands(Loc, LHS, RHS);
13058 
13059     return Context.IntTy;
13060   }
13061 
13062   // The following is safe because we only use this method for
13063   // non-overloadable operands.
13064 
13065   // C++ [expr.log.and]p1
13066   // C++ [expr.log.or]p1
13067   // The operands are both contextually converted to type bool.
13068   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13069   if (LHSRes.isInvalid())
13070     return InvalidOperands(Loc, LHS, RHS);
13071   LHS = LHSRes;
13072 
13073   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13074   if (RHSRes.isInvalid())
13075     return InvalidOperands(Loc, LHS, RHS);
13076   RHS = RHSRes;
13077 
13078   // C++ [expr.log.and]p2
13079   // C++ [expr.log.or]p2
13080   // The result is a bool.
13081   return Context.BoolTy;
13082 }
13083 
13084 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13085   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13086   if (!ME) return false;
13087   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13088   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13089       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13090   if (!Base) return false;
13091   return Base->getMethodDecl() != nullptr;
13092 }
13093 
13094 /// Is the given expression (which must be 'const') a reference to a
13095 /// variable which was originally non-const, but which has become
13096 /// 'const' due to being captured within a block?
13097 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13098 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13099   assert(E->isLValue() && E->getType().isConstQualified());
13100   E = E->IgnoreParens();
13101 
13102   // Must be a reference to a declaration from an enclosing scope.
13103   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13104   if (!DRE) return NCCK_None;
13105   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13106 
13107   // The declaration must be a variable which is not declared 'const'.
13108   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13109   if (!var) return NCCK_None;
13110   if (var->getType().isConstQualified()) return NCCK_None;
13111   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13112 
13113   // Decide whether the first capture was for a block or a lambda.
13114   DeclContext *DC = S.CurContext, *Prev = nullptr;
13115   // Decide whether the first capture was for a block or a lambda.
13116   while (DC) {
13117     // For init-capture, it is possible that the variable belongs to the
13118     // template pattern of the current context.
13119     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13120       if (var->isInitCapture() &&
13121           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13122         break;
13123     if (DC == var->getDeclContext())
13124       break;
13125     Prev = DC;
13126     DC = DC->getParent();
13127   }
13128   // Unless we have an init-capture, we've gone one step too far.
13129   if (!var->isInitCapture())
13130     DC = Prev;
13131   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13132 }
13133 
13134 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13135   Ty = Ty.getNonReferenceType();
13136   if (IsDereference && Ty->isPointerType())
13137     Ty = Ty->getPointeeType();
13138   return !Ty.isConstQualified();
13139 }
13140 
13141 // Update err_typecheck_assign_const and note_typecheck_assign_const
13142 // when this enum is changed.
13143 enum {
13144   ConstFunction,
13145   ConstVariable,
13146   ConstMember,
13147   ConstMethod,
13148   NestedConstMember,
13149   ConstUnknown,  // Keep as last element
13150 };
13151 
13152 /// Emit the "read-only variable not assignable" error and print notes to give
13153 /// more information about why the variable is not assignable, such as pointing
13154 /// to the declaration of a const variable, showing that a method is const, or
13155 /// that the function is returning a const reference.
13156 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13157                                     SourceLocation Loc) {
13158   SourceRange ExprRange = E->getSourceRange();
13159 
13160   // Only emit one error on the first const found.  All other consts will emit
13161   // a note to the error.
13162   bool DiagnosticEmitted = false;
13163 
13164   // Track if the current expression is the result of a dereference, and if the
13165   // next checked expression is the result of a dereference.
13166   bool IsDereference = false;
13167   bool NextIsDereference = false;
13168 
13169   // Loop to process MemberExpr chains.
13170   while (true) {
13171     IsDereference = NextIsDereference;
13172 
13173     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13174     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13175       NextIsDereference = ME->isArrow();
13176       const ValueDecl *VD = ME->getMemberDecl();
13177       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13178         // Mutable fields can be modified even if the class is const.
13179         if (Field->isMutable()) {
13180           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13181           break;
13182         }
13183 
13184         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13185           if (!DiagnosticEmitted) {
13186             S.Diag(Loc, diag::err_typecheck_assign_const)
13187                 << ExprRange << ConstMember << false /*static*/ << Field
13188                 << Field->getType();
13189             DiagnosticEmitted = true;
13190           }
13191           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13192               << ConstMember << false /*static*/ << Field << Field->getType()
13193               << Field->getSourceRange();
13194         }
13195         E = ME->getBase();
13196         continue;
13197       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13198         if (VDecl->getType().isConstQualified()) {
13199           if (!DiagnosticEmitted) {
13200             S.Diag(Loc, diag::err_typecheck_assign_const)
13201                 << ExprRange << ConstMember << true /*static*/ << VDecl
13202                 << VDecl->getType();
13203             DiagnosticEmitted = true;
13204           }
13205           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13206               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13207               << VDecl->getSourceRange();
13208         }
13209         // Static fields do not inherit constness from parents.
13210         break;
13211       }
13212       break; // End MemberExpr
13213     } else if (const ArraySubscriptExpr *ASE =
13214                    dyn_cast<ArraySubscriptExpr>(E)) {
13215       E = ASE->getBase()->IgnoreParenImpCasts();
13216       continue;
13217     } else if (const ExtVectorElementExpr *EVE =
13218                    dyn_cast<ExtVectorElementExpr>(E)) {
13219       E = EVE->getBase()->IgnoreParenImpCasts();
13220       continue;
13221     }
13222     break;
13223   }
13224 
13225   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13226     // Function calls
13227     const FunctionDecl *FD = CE->getDirectCallee();
13228     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13229       if (!DiagnosticEmitted) {
13230         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13231                                                       << ConstFunction << FD;
13232         DiagnosticEmitted = true;
13233       }
13234       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13235              diag::note_typecheck_assign_const)
13236           << ConstFunction << FD << FD->getReturnType()
13237           << FD->getReturnTypeSourceRange();
13238     }
13239   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13240     // Point to variable declaration.
13241     if (const ValueDecl *VD = DRE->getDecl()) {
13242       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13243         if (!DiagnosticEmitted) {
13244           S.Diag(Loc, diag::err_typecheck_assign_const)
13245               << ExprRange << ConstVariable << VD << VD->getType();
13246           DiagnosticEmitted = true;
13247         }
13248         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13249             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13250       }
13251     }
13252   } else if (isa<CXXThisExpr>(E)) {
13253     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13254       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13255         if (MD->isConst()) {
13256           if (!DiagnosticEmitted) {
13257             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13258                                                           << ConstMethod << MD;
13259             DiagnosticEmitted = true;
13260           }
13261           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13262               << ConstMethod << MD << MD->getSourceRange();
13263         }
13264       }
13265     }
13266   }
13267 
13268   if (DiagnosticEmitted)
13269     return;
13270 
13271   // Can't determine a more specific message, so display the generic error.
13272   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13273 }
13274 
13275 enum OriginalExprKind {
13276   OEK_Variable,
13277   OEK_Member,
13278   OEK_LValue
13279 };
13280 
13281 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13282                                          const RecordType *Ty,
13283                                          SourceLocation Loc, SourceRange Range,
13284                                          OriginalExprKind OEK,
13285                                          bool &DiagnosticEmitted) {
13286   std::vector<const RecordType *> RecordTypeList;
13287   RecordTypeList.push_back(Ty);
13288   unsigned NextToCheckIndex = 0;
13289   // We walk the record hierarchy breadth-first to ensure that we print
13290   // diagnostics in field nesting order.
13291   while (RecordTypeList.size() > NextToCheckIndex) {
13292     bool IsNested = NextToCheckIndex > 0;
13293     for (const FieldDecl *Field :
13294          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13295       // First, check every field for constness.
13296       QualType FieldTy = Field->getType();
13297       if (FieldTy.isConstQualified()) {
13298         if (!DiagnosticEmitted) {
13299           S.Diag(Loc, diag::err_typecheck_assign_const)
13300               << Range << NestedConstMember << OEK << VD
13301               << IsNested << Field;
13302           DiagnosticEmitted = true;
13303         }
13304         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13305             << NestedConstMember << IsNested << Field
13306             << FieldTy << Field->getSourceRange();
13307       }
13308 
13309       // Then we append it to the list to check next in order.
13310       FieldTy = FieldTy.getCanonicalType();
13311       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13312         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13313           RecordTypeList.push_back(FieldRecTy);
13314       }
13315     }
13316     ++NextToCheckIndex;
13317   }
13318 }
13319 
13320 /// Emit an error for the case where a record we are trying to assign to has a
13321 /// const-qualified field somewhere in its hierarchy.
13322 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13323                                          SourceLocation Loc) {
13324   QualType Ty = E->getType();
13325   assert(Ty->isRecordType() && "lvalue was not record?");
13326   SourceRange Range = E->getSourceRange();
13327   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13328   bool DiagEmitted = false;
13329 
13330   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13331     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13332             Range, OEK_Member, DiagEmitted);
13333   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13334     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13335             Range, OEK_Variable, DiagEmitted);
13336   else
13337     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13338             Range, OEK_LValue, DiagEmitted);
13339   if (!DiagEmitted)
13340     DiagnoseConstAssignment(S, E, Loc);
13341 }
13342 
13343 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13344 /// emit an error and return true.  If so, return false.
13345 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13346   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13347 
13348   S.CheckShadowingDeclModification(E, Loc);
13349 
13350   SourceLocation OrigLoc = Loc;
13351   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13352                                                               &Loc);
13353   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13354     IsLV = Expr::MLV_InvalidMessageExpression;
13355   if (IsLV == Expr::MLV_Valid)
13356     return false;
13357 
13358   unsigned DiagID = 0;
13359   bool NeedType = false;
13360   switch (IsLV) { // C99 6.5.16p2
13361   case Expr::MLV_ConstQualified:
13362     // Use a specialized diagnostic when we're assigning to an object
13363     // from an enclosing function or block.
13364     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13365       if (NCCK == NCCK_Block)
13366         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13367       else
13368         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13369       break;
13370     }
13371 
13372     // In ARC, use some specialized diagnostics for occasions where we
13373     // infer 'const'.  These are always pseudo-strong variables.
13374     if (S.getLangOpts().ObjCAutoRefCount) {
13375       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13376       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13377         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13378 
13379         // Use the normal diagnostic if it's pseudo-__strong but the
13380         // user actually wrote 'const'.
13381         if (var->isARCPseudoStrong() &&
13382             (!var->getTypeSourceInfo() ||
13383              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13384           // There are three pseudo-strong cases:
13385           //  - self
13386           ObjCMethodDecl *method = S.getCurMethodDecl();
13387           if (method && var == method->getSelfDecl()) {
13388             DiagID = method->isClassMethod()
13389               ? diag::err_typecheck_arc_assign_self_class_method
13390               : diag::err_typecheck_arc_assign_self;
13391 
13392           //  - Objective-C externally_retained attribute.
13393           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13394                      isa<ParmVarDecl>(var)) {
13395             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13396 
13397           //  - fast enumeration variables
13398           } else {
13399             DiagID = diag::err_typecheck_arr_assign_enumeration;
13400           }
13401 
13402           SourceRange Assign;
13403           if (Loc != OrigLoc)
13404             Assign = SourceRange(OrigLoc, OrigLoc);
13405           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13406           // We need to preserve the AST regardless, so migration tool
13407           // can do its job.
13408           return false;
13409         }
13410       }
13411     }
13412 
13413     // If none of the special cases above are triggered, then this is a
13414     // simple const assignment.
13415     if (DiagID == 0) {
13416       DiagnoseConstAssignment(S, E, Loc);
13417       return true;
13418     }
13419 
13420     break;
13421   case Expr::MLV_ConstAddrSpace:
13422     DiagnoseConstAssignment(S, E, Loc);
13423     return true;
13424   case Expr::MLV_ConstQualifiedField:
13425     DiagnoseRecursiveConstFields(S, E, Loc);
13426     return true;
13427   case Expr::MLV_ArrayType:
13428   case Expr::MLV_ArrayTemporary:
13429     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13430     NeedType = true;
13431     break;
13432   case Expr::MLV_NotObjectType:
13433     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13434     NeedType = true;
13435     break;
13436   case Expr::MLV_LValueCast:
13437     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13438     break;
13439   case Expr::MLV_Valid:
13440     llvm_unreachable("did not take early return for MLV_Valid");
13441   case Expr::MLV_InvalidExpression:
13442   case Expr::MLV_MemberFunction:
13443   case Expr::MLV_ClassTemporary:
13444     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13445     break;
13446   case Expr::MLV_IncompleteType:
13447   case Expr::MLV_IncompleteVoidType:
13448     return S.RequireCompleteType(Loc, E->getType(),
13449              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13450   case Expr::MLV_DuplicateVectorComponents:
13451     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13452     break;
13453   case Expr::MLV_NoSetterProperty:
13454     llvm_unreachable("readonly properties should be processed differently");
13455   case Expr::MLV_InvalidMessageExpression:
13456     DiagID = diag::err_readonly_message_assignment;
13457     break;
13458   case Expr::MLV_SubObjCPropertySetting:
13459     DiagID = diag::err_no_subobject_property_setting;
13460     break;
13461   }
13462 
13463   SourceRange Assign;
13464   if (Loc != OrigLoc)
13465     Assign = SourceRange(OrigLoc, OrigLoc);
13466   if (NeedType)
13467     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13468   else
13469     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13470   return true;
13471 }
13472 
13473 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13474                                          SourceLocation Loc,
13475                                          Sema &Sema) {
13476   if (Sema.inTemplateInstantiation())
13477     return;
13478   if (Sema.isUnevaluatedContext())
13479     return;
13480   if (Loc.isInvalid() || Loc.isMacroID())
13481     return;
13482   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13483     return;
13484 
13485   // C / C++ fields
13486   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13487   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13488   if (ML && MR) {
13489     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13490       return;
13491     const ValueDecl *LHSDecl =
13492         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13493     const ValueDecl *RHSDecl =
13494         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13495     if (LHSDecl != RHSDecl)
13496       return;
13497     if (LHSDecl->getType().isVolatileQualified())
13498       return;
13499     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13500       if (RefTy->getPointeeType().isVolatileQualified())
13501         return;
13502 
13503     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13504   }
13505 
13506   // Objective-C instance variables
13507   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13508   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13509   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13510     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13511     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13512     if (RL && RR && RL->getDecl() == RR->getDecl())
13513       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13514   }
13515 }
13516 
13517 // C99 6.5.16.1
13518 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13519                                        SourceLocation Loc,
13520                                        QualType CompoundType) {
13521   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13522 
13523   // Verify that LHS is a modifiable lvalue, and emit error if not.
13524   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13525     return QualType();
13526 
13527   QualType LHSType = LHSExpr->getType();
13528   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13529                                              CompoundType;
13530   // OpenCL v1.2 s6.1.1.1 p2:
13531   // The half data type can only be used to declare a pointer to a buffer that
13532   // contains half values
13533   if (getLangOpts().OpenCL &&
13534       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13535       LHSType->isHalfType()) {
13536     Diag(Loc, diag::err_opencl_half_load_store) << 1
13537         << LHSType.getUnqualifiedType();
13538     return QualType();
13539   }
13540 
13541   AssignConvertType ConvTy;
13542   if (CompoundType.isNull()) {
13543     Expr *RHSCheck = RHS.get();
13544 
13545     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13546 
13547     QualType LHSTy(LHSType);
13548     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13549     if (RHS.isInvalid())
13550       return QualType();
13551     // Special case of NSObject attributes on c-style pointer types.
13552     if (ConvTy == IncompatiblePointer &&
13553         ((Context.isObjCNSObjectType(LHSType) &&
13554           RHSType->isObjCObjectPointerType()) ||
13555          (Context.isObjCNSObjectType(RHSType) &&
13556           LHSType->isObjCObjectPointerType())))
13557       ConvTy = Compatible;
13558 
13559     if (ConvTy == Compatible &&
13560         LHSType->isObjCObjectType())
13561         Diag(Loc, diag::err_objc_object_assignment)
13562           << LHSType;
13563 
13564     // If the RHS is a unary plus or minus, check to see if they = and + are
13565     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13566     // instead of "x += 4".
13567     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13568       RHSCheck = ICE->getSubExpr();
13569     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13570       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13571           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13572           // Only if the two operators are exactly adjacent.
13573           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13574           // And there is a space or other character before the subexpr of the
13575           // unary +/-.  We don't want to warn on "x=-1".
13576           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13577           UO->getSubExpr()->getBeginLoc().isFileID()) {
13578         Diag(Loc, diag::warn_not_compound_assign)
13579           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13580           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13581       }
13582     }
13583 
13584     if (ConvTy == Compatible) {
13585       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13586         // Warn about retain cycles where a block captures the LHS, but
13587         // not if the LHS is a simple variable into which the block is
13588         // being stored...unless that variable can be captured by reference!
13589         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13590         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13591         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13592           checkRetainCycles(LHSExpr, RHS.get());
13593       }
13594 
13595       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13596           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13597         // It is safe to assign a weak reference into a strong variable.
13598         // Although this code can still have problems:
13599         //   id x = self.weakProp;
13600         //   id y = self.weakProp;
13601         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13602         // paths through the function. This should be revisited if
13603         // -Wrepeated-use-of-weak is made flow-sensitive.
13604         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13605         // variable, which will be valid for the current autorelease scope.
13606         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13607                              RHS.get()->getBeginLoc()))
13608           getCurFunction()->markSafeWeakUse(RHS.get());
13609 
13610       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13611         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13612       }
13613     }
13614   } else {
13615     // Compound assignment "x += y"
13616     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13617   }
13618 
13619   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13620                                RHS.get(), AA_Assigning))
13621     return QualType();
13622 
13623   CheckForNullPointerDereference(*this, LHSExpr);
13624 
13625   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13626     if (CompoundType.isNull()) {
13627       // C++2a [expr.ass]p5:
13628       //   A simple-assignment whose left operand is of a volatile-qualified
13629       //   type is deprecated unless the assignment is either a discarded-value
13630       //   expression or an unevaluated operand
13631       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13632     } else {
13633       // C++2a [expr.ass]p6:
13634       //   [Compound-assignment] expressions are deprecated if E1 has
13635       //   volatile-qualified type
13636       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13637     }
13638   }
13639 
13640   // C99 6.5.16p3: The type of an assignment expression is the type of the
13641   // left operand unless the left operand has qualified type, in which case
13642   // it is the unqualified version of the type of the left operand.
13643   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13644   // is converted to the type of the assignment expression (above).
13645   // C++ 5.17p1: the type of the assignment expression is that of its left
13646   // operand.
13647   return (getLangOpts().CPlusPlus
13648           ? LHSType : LHSType.getUnqualifiedType());
13649 }
13650 
13651 // Only ignore explicit casts to void.
13652 static bool IgnoreCommaOperand(const Expr *E) {
13653   E = E->IgnoreParens();
13654 
13655   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13656     if (CE->getCastKind() == CK_ToVoid) {
13657       return true;
13658     }
13659 
13660     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13661     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13662         CE->getSubExpr()->getType()->isDependentType()) {
13663       return true;
13664     }
13665   }
13666 
13667   return false;
13668 }
13669 
13670 // Look for instances where it is likely the comma operator is confused with
13671 // another operator.  There is an explicit list of acceptable expressions for
13672 // the left hand side of the comma operator, otherwise emit a warning.
13673 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13674   // No warnings in macros
13675   if (Loc.isMacroID())
13676     return;
13677 
13678   // Don't warn in template instantiations.
13679   if (inTemplateInstantiation())
13680     return;
13681 
13682   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13683   // instead, skip more than needed, then call back into here with the
13684   // CommaVisitor in SemaStmt.cpp.
13685   // The listed locations are the initialization and increment portions
13686   // of a for loop.  The additional checks are on the condition of
13687   // if statements, do/while loops, and for loops.
13688   // Differences in scope flags for C89 mode requires the extra logic.
13689   const unsigned ForIncrementFlags =
13690       getLangOpts().C99 || getLangOpts().CPlusPlus
13691           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13692           : Scope::ContinueScope | Scope::BreakScope;
13693   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13694   const unsigned ScopeFlags = getCurScope()->getFlags();
13695   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13696       (ScopeFlags & ForInitFlags) == ForInitFlags)
13697     return;
13698 
13699   // If there are multiple comma operators used together, get the RHS of the
13700   // of the comma operator as the LHS.
13701   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13702     if (BO->getOpcode() != BO_Comma)
13703       break;
13704     LHS = BO->getRHS();
13705   }
13706 
13707   // Only allow some expressions on LHS to not warn.
13708   if (IgnoreCommaOperand(LHS))
13709     return;
13710 
13711   Diag(Loc, diag::warn_comma_operator);
13712   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13713       << LHS->getSourceRange()
13714       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13715                                     LangOpts.CPlusPlus ? "static_cast<void>("
13716                                                        : "(void)(")
13717       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13718                                     ")");
13719 }
13720 
13721 // C99 6.5.17
13722 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13723                                    SourceLocation Loc) {
13724   LHS = S.CheckPlaceholderExpr(LHS.get());
13725   RHS = S.CheckPlaceholderExpr(RHS.get());
13726   if (LHS.isInvalid() || RHS.isInvalid())
13727     return QualType();
13728 
13729   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13730   // operands, but not unary promotions.
13731   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13732 
13733   // So we treat the LHS as a ignored value, and in C++ we allow the
13734   // containing site to determine what should be done with the RHS.
13735   LHS = S.IgnoredValueConversions(LHS.get());
13736   if (LHS.isInvalid())
13737     return QualType();
13738 
13739   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13740 
13741   if (!S.getLangOpts().CPlusPlus) {
13742     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13743     if (RHS.isInvalid())
13744       return QualType();
13745     if (!RHS.get()->getType()->isVoidType())
13746       S.RequireCompleteType(Loc, RHS.get()->getType(),
13747                             diag::err_incomplete_type);
13748   }
13749 
13750   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13751     S.DiagnoseCommaOperator(LHS.get(), Loc);
13752 
13753   return RHS.get()->getType();
13754 }
13755 
13756 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13757 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13758 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13759                                                ExprValueKind &VK,
13760                                                ExprObjectKind &OK,
13761                                                SourceLocation OpLoc,
13762                                                bool IsInc, bool IsPrefix) {
13763   if (Op->isTypeDependent())
13764     return S.Context.DependentTy;
13765 
13766   QualType ResType = Op->getType();
13767   // Atomic types can be used for increment / decrement where the non-atomic
13768   // versions can, so ignore the _Atomic() specifier for the purpose of
13769   // checking.
13770   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13771     ResType = ResAtomicType->getValueType();
13772 
13773   assert(!ResType.isNull() && "no type for increment/decrement expression");
13774 
13775   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13776     // Decrement of bool is not allowed.
13777     if (!IsInc) {
13778       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13779       return QualType();
13780     }
13781     // Increment of bool sets it to true, but is deprecated.
13782     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13783                                               : diag::warn_increment_bool)
13784       << Op->getSourceRange();
13785   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13786     // Error on enum increments and decrements in C++ mode
13787     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13788     return QualType();
13789   } else if (ResType->isRealType()) {
13790     // OK!
13791   } else if (ResType->isPointerType()) {
13792     // C99 6.5.2.4p2, 6.5.6p2
13793     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13794       return QualType();
13795   } else if (ResType->isObjCObjectPointerType()) {
13796     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13797     // Otherwise, we just need a complete type.
13798     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13799         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13800       return QualType();
13801   } else if (ResType->isAnyComplexType()) {
13802     // C99 does not support ++/-- on complex types, we allow as an extension.
13803     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13804       << ResType << Op->getSourceRange();
13805   } else if (ResType->isPlaceholderType()) {
13806     ExprResult PR = S.CheckPlaceholderExpr(Op);
13807     if (PR.isInvalid()) return QualType();
13808     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13809                                           IsInc, IsPrefix);
13810   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13811     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13812   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13813              (ResType->castAs<VectorType>()->getVectorKind() !=
13814               VectorType::AltiVecBool)) {
13815     // The z vector extensions allow ++ and -- for non-bool vectors.
13816   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13817             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13818     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13819   } else {
13820     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13821       << ResType << int(IsInc) << Op->getSourceRange();
13822     return QualType();
13823   }
13824   // At this point, we know we have a real, complex or pointer type.
13825   // Now make sure the operand is a modifiable lvalue.
13826   if (CheckForModifiableLvalue(Op, OpLoc, S))
13827     return QualType();
13828   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13829     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13830     //   An operand with volatile-qualified type is deprecated
13831     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13832         << IsInc << ResType;
13833   }
13834   // In C++, a prefix increment is the same type as the operand. Otherwise
13835   // (in C or with postfix), the increment is the unqualified type of the
13836   // operand.
13837   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13838     VK = VK_LValue;
13839     OK = Op->getObjectKind();
13840     return ResType;
13841   } else {
13842     VK = VK_PRValue;
13843     return ResType.getUnqualifiedType();
13844   }
13845 }
13846 
13847 
13848 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13849 /// This routine allows us to typecheck complex/recursive expressions
13850 /// where the declaration is needed for type checking. We only need to
13851 /// handle cases when the expression references a function designator
13852 /// or is an lvalue. Here are some examples:
13853 ///  - &(x) => x
13854 ///  - &*****f => f for f a function designator.
13855 ///  - &s.xx => s
13856 ///  - &s.zz[1].yy -> s, if zz is an array
13857 ///  - *(x + 1) -> x, if x is an array
13858 ///  - &"123"[2] -> 0
13859 ///  - & __real__ x -> x
13860 ///
13861 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13862 /// members.
13863 static ValueDecl *getPrimaryDecl(Expr *E) {
13864   switch (E->getStmtClass()) {
13865   case Stmt::DeclRefExprClass:
13866     return cast<DeclRefExpr>(E)->getDecl();
13867   case Stmt::MemberExprClass:
13868     // If this is an arrow operator, the address is an offset from
13869     // the base's value, so the object the base refers to is
13870     // irrelevant.
13871     if (cast<MemberExpr>(E)->isArrow())
13872       return nullptr;
13873     // Otherwise, the expression refers to a part of the base
13874     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13875   case Stmt::ArraySubscriptExprClass: {
13876     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13877     // promotion of register arrays earlier.
13878     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13879     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13880       if (ICE->getSubExpr()->getType()->isArrayType())
13881         return getPrimaryDecl(ICE->getSubExpr());
13882     }
13883     return nullptr;
13884   }
13885   case Stmt::UnaryOperatorClass: {
13886     UnaryOperator *UO = cast<UnaryOperator>(E);
13887 
13888     switch(UO->getOpcode()) {
13889     case UO_Real:
13890     case UO_Imag:
13891     case UO_Extension:
13892       return getPrimaryDecl(UO->getSubExpr());
13893     default:
13894       return nullptr;
13895     }
13896   }
13897   case Stmt::ParenExprClass:
13898     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13899   case Stmt::ImplicitCastExprClass:
13900     // If the result of an implicit cast is an l-value, we care about
13901     // the sub-expression; otherwise, the result here doesn't matter.
13902     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13903   case Stmt::CXXUuidofExprClass:
13904     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13905   default:
13906     return nullptr;
13907   }
13908 }
13909 
13910 namespace {
13911 enum {
13912   AO_Bit_Field = 0,
13913   AO_Vector_Element = 1,
13914   AO_Property_Expansion = 2,
13915   AO_Register_Variable = 3,
13916   AO_Matrix_Element = 4,
13917   AO_No_Error = 5
13918 };
13919 }
13920 /// Diagnose invalid operand for address of operations.
13921 ///
13922 /// \param Type The type of operand which cannot have its address taken.
13923 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13924                                          Expr *E, unsigned Type) {
13925   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13926 }
13927 
13928 /// CheckAddressOfOperand - The operand of & must be either a function
13929 /// designator or an lvalue designating an object. If it is an lvalue, the
13930 /// object cannot be declared with storage class register or be a bit field.
13931 /// Note: The usual conversions are *not* applied to the operand of the &
13932 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13933 /// In C++, the operand might be an overloaded function name, in which case
13934 /// we allow the '&' but retain the overloaded-function type.
13935 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13936   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13937     if (PTy->getKind() == BuiltinType::Overload) {
13938       Expr *E = OrigOp.get()->IgnoreParens();
13939       if (!isa<OverloadExpr>(E)) {
13940         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13941         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13942           << OrigOp.get()->getSourceRange();
13943         return QualType();
13944       }
13945 
13946       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13947       if (isa<UnresolvedMemberExpr>(Ovl))
13948         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13949           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13950             << OrigOp.get()->getSourceRange();
13951           return QualType();
13952         }
13953 
13954       return Context.OverloadTy;
13955     }
13956 
13957     if (PTy->getKind() == BuiltinType::UnknownAny)
13958       return Context.UnknownAnyTy;
13959 
13960     if (PTy->getKind() == BuiltinType::BoundMember) {
13961       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13962         << OrigOp.get()->getSourceRange();
13963       return QualType();
13964     }
13965 
13966     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13967     if (OrigOp.isInvalid()) return QualType();
13968   }
13969 
13970   if (OrigOp.get()->isTypeDependent())
13971     return Context.DependentTy;
13972 
13973   assert(!OrigOp.get()->hasPlaceholderType());
13974 
13975   // Make sure to ignore parentheses in subsequent checks
13976   Expr *op = OrigOp.get()->IgnoreParens();
13977 
13978   // In OpenCL captures for blocks called as lambda functions
13979   // are located in the private address space. Blocks used in
13980   // enqueue_kernel can be located in a different address space
13981   // depending on a vendor implementation. Thus preventing
13982   // taking an address of the capture to avoid invalid AS casts.
13983   if (LangOpts.OpenCL) {
13984     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13985     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13986       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13987       return QualType();
13988     }
13989   }
13990 
13991   if (getLangOpts().C99) {
13992     // Implement C99-only parts of addressof rules.
13993     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13994       if (uOp->getOpcode() == UO_Deref)
13995         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13996         // (assuming the deref expression is valid).
13997         return uOp->getSubExpr()->getType();
13998     }
13999     // Technically, there should be a check for array subscript
14000     // expressions here, but the result of one is always an lvalue anyway.
14001   }
14002   ValueDecl *dcl = getPrimaryDecl(op);
14003 
14004   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14005     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14006                                            op->getBeginLoc()))
14007       return QualType();
14008 
14009   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14010   unsigned AddressOfError = AO_No_Error;
14011 
14012   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14013     bool sfinae = (bool)isSFINAEContext();
14014     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14015                                   : diag::ext_typecheck_addrof_temporary)
14016       << op->getType() << op->getSourceRange();
14017     if (sfinae)
14018       return QualType();
14019     // Materialize the temporary as an lvalue so that we can take its address.
14020     OrigOp = op =
14021         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14022   } else if (isa<ObjCSelectorExpr>(op)) {
14023     return Context.getPointerType(op->getType());
14024   } else if (lval == Expr::LV_MemberFunction) {
14025     // If it's an instance method, make a member pointer.
14026     // The expression must have exactly the form &A::foo.
14027 
14028     // If the underlying expression isn't a decl ref, give up.
14029     if (!isa<DeclRefExpr>(op)) {
14030       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14031         << OrigOp.get()->getSourceRange();
14032       return QualType();
14033     }
14034     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14035     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14036 
14037     // The id-expression was parenthesized.
14038     if (OrigOp.get() != DRE) {
14039       Diag(OpLoc, diag::err_parens_pointer_member_function)
14040         << OrigOp.get()->getSourceRange();
14041 
14042     // The method was named without a qualifier.
14043     } else if (!DRE->getQualifier()) {
14044       if (MD->getParent()->getName().empty())
14045         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14046           << op->getSourceRange();
14047       else {
14048         SmallString<32> Str;
14049         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14050         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14051           << op->getSourceRange()
14052           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14053       }
14054     }
14055 
14056     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14057     if (isa<CXXDestructorDecl>(MD))
14058       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14059 
14060     QualType MPTy = Context.getMemberPointerType(
14061         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14062     // Under the MS ABI, lock down the inheritance model now.
14063     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14064       (void)isCompleteType(OpLoc, MPTy);
14065     return MPTy;
14066   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14067     // C99 6.5.3.2p1
14068     // The operand must be either an l-value or a function designator
14069     if (!op->getType()->isFunctionType()) {
14070       // Use a special diagnostic for loads from property references.
14071       if (isa<PseudoObjectExpr>(op)) {
14072         AddressOfError = AO_Property_Expansion;
14073       } else {
14074         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14075           << op->getType() << op->getSourceRange();
14076         return QualType();
14077       }
14078     }
14079   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14080     // The operand cannot be a bit-field
14081     AddressOfError = AO_Bit_Field;
14082   } else if (op->getObjectKind() == OK_VectorComponent) {
14083     // The operand cannot be an element of a vector
14084     AddressOfError = AO_Vector_Element;
14085   } else if (op->getObjectKind() == OK_MatrixComponent) {
14086     // The operand cannot be an element of a matrix.
14087     AddressOfError = AO_Matrix_Element;
14088   } else if (dcl) { // C99 6.5.3.2p1
14089     // We have an lvalue with a decl. Make sure the decl is not declared
14090     // with the register storage-class specifier.
14091     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14092       // in C++ it is not error to take address of a register
14093       // variable (c++03 7.1.1P3)
14094       if (vd->getStorageClass() == SC_Register &&
14095           !getLangOpts().CPlusPlus) {
14096         AddressOfError = AO_Register_Variable;
14097       }
14098     } else if (isa<MSPropertyDecl>(dcl)) {
14099       AddressOfError = AO_Property_Expansion;
14100     } else if (isa<FunctionTemplateDecl>(dcl)) {
14101       return Context.OverloadTy;
14102     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14103       // Okay: we can take the address of a field.
14104       // Could be a pointer to member, though, if there is an explicit
14105       // scope qualifier for the class.
14106       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14107         DeclContext *Ctx = dcl->getDeclContext();
14108         if (Ctx && Ctx->isRecord()) {
14109           if (dcl->getType()->isReferenceType()) {
14110             Diag(OpLoc,
14111                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14112               << dcl->getDeclName() << dcl->getType();
14113             return QualType();
14114           }
14115 
14116           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14117             Ctx = Ctx->getParent();
14118 
14119           QualType MPTy = Context.getMemberPointerType(
14120               op->getType(),
14121               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14122           // Under the MS ABI, lock down the inheritance model now.
14123           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14124             (void)isCompleteType(OpLoc, MPTy);
14125           return MPTy;
14126         }
14127       }
14128     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
14129                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
14130       llvm_unreachable("Unknown/unexpected decl type");
14131   }
14132 
14133   if (AddressOfError != AO_No_Error) {
14134     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14135     return QualType();
14136   }
14137 
14138   if (lval == Expr::LV_IncompleteVoidType) {
14139     // Taking the address of a void variable is technically illegal, but we
14140     // allow it in cases which are otherwise valid.
14141     // Example: "extern void x; void* y = &x;".
14142     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14143   }
14144 
14145   // If the operand has type "type", the result has type "pointer to type".
14146   if (op->getType()->isObjCObjectType())
14147     return Context.getObjCObjectPointerType(op->getType());
14148 
14149   CheckAddressOfPackedMember(op);
14150 
14151   return Context.getPointerType(op->getType());
14152 }
14153 
14154 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14155   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14156   if (!DRE)
14157     return;
14158   const Decl *D = DRE->getDecl();
14159   if (!D)
14160     return;
14161   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14162   if (!Param)
14163     return;
14164   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14165     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14166       return;
14167   if (FunctionScopeInfo *FD = S.getCurFunction())
14168     if (!FD->ModifiedNonNullParams.count(Param))
14169       FD->ModifiedNonNullParams.insert(Param);
14170 }
14171 
14172 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14173 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14174                                         SourceLocation OpLoc) {
14175   if (Op->isTypeDependent())
14176     return S.Context.DependentTy;
14177 
14178   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14179   if (ConvResult.isInvalid())
14180     return QualType();
14181   Op = ConvResult.get();
14182   QualType OpTy = Op->getType();
14183   QualType Result;
14184 
14185   if (isa<CXXReinterpretCastExpr>(Op)) {
14186     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14187     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14188                                      Op->getSourceRange());
14189   }
14190 
14191   if (const PointerType *PT = OpTy->getAs<PointerType>())
14192   {
14193     Result = PT->getPointeeType();
14194   }
14195   else if (const ObjCObjectPointerType *OPT =
14196              OpTy->getAs<ObjCObjectPointerType>())
14197     Result = OPT->getPointeeType();
14198   else {
14199     ExprResult PR = S.CheckPlaceholderExpr(Op);
14200     if (PR.isInvalid()) return QualType();
14201     if (PR.get() != Op)
14202       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14203   }
14204 
14205   if (Result.isNull()) {
14206     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14207       << OpTy << Op->getSourceRange();
14208     return QualType();
14209   }
14210 
14211   // Note that per both C89 and C99, indirection is always legal, even if Result
14212   // is an incomplete type or void.  It would be possible to warn about
14213   // dereferencing a void pointer, but it's completely well-defined, and such a
14214   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14215   // for pointers to 'void' but is fine for any other pointer type:
14216   //
14217   // C++ [expr.unary.op]p1:
14218   //   [...] the expression to which [the unary * operator] is applied shall
14219   //   be a pointer to an object type, or a pointer to a function type
14220   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14221     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14222       << OpTy << Op->getSourceRange();
14223 
14224   // Dereferences are usually l-values...
14225   VK = VK_LValue;
14226 
14227   // ...except that certain expressions are never l-values in C.
14228   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14229     VK = VK_PRValue;
14230 
14231   return Result;
14232 }
14233 
14234 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14235   BinaryOperatorKind Opc;
14236   switch (Kind) {
14237   default: llvm_unreachable("Unknown binop!");
14238   case tok::periodstar:           Opc = BO_PtrMemD; break;
14239   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14240   case tok::star:                 Opc = BO_Mul; break;
14241   case tok::slash:                Opc = BO_Div; break;
14242   case tok::percent:              Opc = BO_Rem; break;
14243   case tok::plus:                 Opc = BO_Add; break;
14244   case tok::minus:                Opc = BO_Sub; break;
14245   case tok::lessless:             Opc = BO_Shl; break;
14246   case tok::greatergreater:       Opc = BO_Shr; break;
14247   case tok::lessequal:            Opc = BO_LE; break;
14248   case tok::less:                 Opc = BO_LT; break;
14249   case tok::greaterequal:         Opc = BO_GE; break;
14250   case tok::greater:              Opc = BO_GT; break;
14251   case tok::exclaimequal:         Opc = BO_NE; break;
14252   case tok::equalequal:           Opc = BO_EQ; break;
14253   case tok::spaceship:            Opc = BO_Cmp; break;
14254   case tok::amp:                  Opc = BO_And; break;
14255   case tok::caret:                Opc = BO_Xor; break;
14256   case tok::pipe:                 Opc = BO_Or; break;
14257   case tok::ampamp:               Opc = BO_LAnd; break;
14258   case tok::pipepipe:             Opc = BO_LOr; break;
14259   case tok::equal:                Opc = BO_Assign; break;
14260   case tok::starequal:            Opc = BO_MulAssign; break;
14261   case tok::slashequal:           Opc = BO_DivAssign; break;
14262   case tok::percentequal:         Opc = BO_RemAssign; break;
14263   case tok::plusequal:            Opc = BO_AddAssign; break;
14264   case tok::minusequal:           Opc = BO_SubAssign; break;
14265   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14266   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14267   case tok::ampequal:             Opc = BO_AndAssign; break;
14268   case tok::caretequal:           Opc = BO_XorAssign; break;
14269   case tok::pipeequal:            Opc = BO_OrAssign; break;
14270   case tok::comma:                Opc = BO_Comma; break;
14271   }
14272   return Opc;
14273 }
14274 
14275 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14276   tok::TokenKind Kind) {
14277   UnaryOperatorKind Opc;
14278   switch (Kind) {
14279   default: llvm_unreachable("Unknown unary op!");
14280   case tok::plusplus:     Opc = UO_PreInc; break;
14281   case tok::minusminus:   Opc = UO_PreDec; break;
14282   case tok::amp:          Opc = UO_AddrOf; break;
14283   case tok::star:         Opc = UO_Deref; break;
14284   case tok::plus:         Opc = UO_Plus; break;
14285   case tok::minus:        Opc = UO_Minus; break;
14286   case tok::tilde:        Opc = UO_Not; break;
14287   case tok::exclaim:      Opc = UO_LNot; break;
14288   case tok::kw___real:    Opc = UO_Real; break;
14289   case tok::kw___imag:    Opc = UO_Imag; break;
14290   case tok::kw___extension__: Opc = UO_Extension; break;
14291   }
14292   return Opc;
14293 }
14294 
14295 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14296 /// This warning suppressed in the event of macro expansions.
14297 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14298                                    SourceLocation OpLoc, bool IsBuiltin) {
14299   if (S.inTemplateInstantiation())
14300     return;
14301   if (S.isUnevaluatedContext())
14302     return;
14303   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14304     return;
14305   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14306   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14307   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14308   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14309   if (!LHSDeclRef || !RHSDeclRef ||
14310       LHSDeclRef->getLocation().isMacroID() ||
14311       RHSDeclRef->getLocation().isMacroID())
14312     return;
14313   const ValueDecl *LHSDecl =
14314     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14315   const ValueDecl *RHSDecl =
14316     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14317   if (LHSDecl != RHSDecl)
14318     return;
14319   if (LHSDecl->getType().isVolatileQualified())
14320     return;
14321   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14322     if (RefTy->getPointeeType().isVolatileQualified())
14323       return;
14324 
14325   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14326                           : diag::warn_self_assignment_overloaded)
14327       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14328       << RHSExpr->getSourceRange();
14329 }
14330 
14331 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14332 /// is usually indicative of introspection within the Objective-C pointer.
14333 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14334                                           SourceLocation OpLoc) {
14335   if (!S.getLangOpts().ObjC)
14336     return;
14337 
14338   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14339   const Expr *LHS = L.get();
14340   const Expr *RHS = R.get();
14341 
14342   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14343     ObjCPointerExpr = LHS;
14344     OtherExpr = RHS;
14345   }
14346   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14347     ObjCPointerExpr = RHS;
14348     OtherExpr = LHS;
14349   }
14350 
14351   // This warning is deliberately made very specific to reduce false
14352   // positives with logic that uses '&' for hashing.  This logic mainly
14353   // looks for code trying to introspect into tagged pointers, which
14354   // code should generally never do.
14355   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14356     unsigned Diag = diag::warn_objc_pointer_masking;
14357     // Determine if we are introspecting the result of performSelectorXXX.
14358     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14359     // Special case messages to -performSelector and friends, which
14360     // can return non-pointer values boxed in a pointer value.
14361     // Some clients may wish to silence warnings in this subcase.
14362     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14363       Selector S = ME->getSelector();
14364       StringRef SelArg0 = S.getNameForSlot(0);
14365       if (SelArg0.startswith("performSelector"))
14366         Diag = diag::warn_objc_pointer_masking_performSelector;
14367     }
14368 
14369     S.Diag(OpLoc, Diag)
14370       << ObjCPointerExpr->getSourceRange();
14371   }
14372 }
14373 
14374 static NamedDecl *getDeclFromExpr(Expr *E) {
14375   if (!E)
14376     return nullptr;
14377   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14378     return DRE->getDecl();
14379   if (auto *ME = dyn_cast<MemberExpr>(E))
14380     return ME->getMemberDecl();
14381   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14382     return IRE->getDecl();
14383   return nullptr;
14384 }
14385 
14386 // This helper function promotes a binary operator's operands (which are of a
14387 // half vector type) to a vector of floats and then truncates the result to
14388 // a vector of either half or short.
14389 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14390                                       BinaryOperatorKind Opc, QualType ResultTy,
14391                                       ExprValueKind VK, ExprObjectKind OK,
14392                                       bool IsCompAssign, SourceLocation OpLoc,
14393                                       FPOptionsOverride FPFeatures) {
14394   auto &Context = S.getASTContext();
14395   assert((isVector(ResultTy, Context.HalfTy) ||
14396           isVector(ResultTy, Context.ShortTy)) &&
14397          "Result must be a vector of half or short");
14398   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14399          isVector(RHS.get()->getType(), Context.HalfTy) &&
14400          "both operands expected to be a half vector");
14401 
14402   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14403   QualType BinOpResTy = RHS.get()->getType();
14404 
14405   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14406   // change BinOpResTy to a vector of ints.
14407   if (isVector(ResultTy, Context.ShortTy))
14408     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14409 
14410   if (IsCompAssign)
14411     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14412                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14413                                           BinOpResTy, BinOpResTy);
14414 
14415   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14416   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14417                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14418   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14419 }
14420 
14421 static std::pair<ExprResult, ExprResult>
14422 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14423                            Expr *RHSExpr) {
14424   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14425   if (!S.Context.isDependenceAllowed()) {
14426     // C cannot handle TypoExpr nodes on either side of a binop because it
14427     // doesn't handle dependent types properly, so make sure any TypoExprs have
14428     // been dealt with before checking the operands.
14429     LHS = S.CorrectDelayedTyposInExpr(LHS);
14430     RHS = S.CorrectDelayedTyposInExpr(
14431         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14432         [Opc, LHS](Expr *E) {
14433           if (Opc != BO_Assign)
14434             return ExprResult(E);
14435           // Avoid correcting the RHS to the same Expr as the LHS.
14436           Decl *D = getDeclFromExpr(E);
14437           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14438         });
14439   }
14440   return std::make_pair(LHS, RHS);
14441 }
14442 
14443 /// Returns true if conversion between vectors of halfs and vectors of floats
14444 /// is needed.
14445 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14446                                      Expr *E0, Expr *E1 = nullptr) {
14447   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14448       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14449     return false;
14450 
14451   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14452     QualType Ty = E->IgnoreImplicit()->getType();
14453 
14454     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14455     // to vectors of floats. Although the element type of the vectors is __fp16,
14456     // the vectors shouldn't be treated as storage-only types. See the
14457     // discussion here: https://reviews.llvm.org/rG825235c140e7
14458     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14459       if (VT->getVectorKind() == VectorType::NeonVector)
14460         return false;
14461       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14462     }
14463     return false;
14464   };
14465 
14466   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14467 }
14468 
14469 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14470 /// operator @p Opc at location @c TokLoc. This routine only supports
14471 /// built-in operations; ActOnBinOp handles overloaded operators.
14472 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14473                                     BinaryOperatorKind Opc,
14474                                     Expr *LHSExpr, Expr *RHSExpr) {
14475   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14476     // The syntax only allows initializer lists on the RHS of assignment,
14477     // so we don't need to worry about accepting invalid code for
14478     // non-assignment operators.
14479     // C++11 5.17p9:
14480     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14481     //   of x = {} is x = T().
14482     InitializationKind Kind = InitializationKind::CreateDirectList(
14483         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14484     InitializedEntity Entity =
14485         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14486     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14487     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14488     if (Init.isInvalid())
14489       return Init;
14490     RHSExpr = Init.get();
14491   }
14492 
14493   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14494   QualType ResultTy;     // Result type of the binary operator.
14495   // The following two variables are used for compound assignment operators
14496   QualType CompLHSTy;    // Type of LHS after promotions for computation
14497   QualType CompResultTy; // Type of computation result
14498   ExprValueKind VK = VK_PRValue;
14499   ExprObjectKind OK = OK_Ordinary;
14500   bool ConvertHalfVec = false;
14501 
14502   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14503   if (!LHS.isUsable() || !RHS.isUsable())
14504     return ExprError();
14505 
14506   if (getLangOpts().OpenCL) {
14507     QualType LHSTy = LHSExpr->getType();
14508     QualType RHSTy = RHSExpr->getType();
14509     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14510     // the ATOMIC_VAR_INIT macro.
14511     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14512       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14513       if (BO_Assign == Opc)
14514         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14515       else
14516         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14517       return ExprError();
14518     }
14519 
14520     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14521     // only with a builtin functions and therefore should be disallowed here.
14522     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14523         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14524         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14525         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14526       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14527       return ExprError();
14528     }
14529   }
14530 
14531   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14532   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14533 
14534   switch (Opc) {
14535   case BO_Assign:
14536     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14537     if (getLangOpts().CPlusPlus &&
14538         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14539       VK = LHS.get()->getValueKind();
14540       OK = LHS.get()->getObjectKind();
14541     }
14542     if (!ResultTy.isNull()) {
14543       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14544       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14545 
14546       // Avoid copying a block to the heap if the block is assigned to a local
14547       // auto variable that is declared in the same scope as the block. This
14548       // optimization is unsafe if the local variable is declared in an outer
14549       // scope. For example:
14550       //
14551       // BlockTy b;
14552       // {
14553       //   b = ^{...};
14554       // }
14555       // // It is unsafe to invoke the block here if it wasn't copied to the
14556       // // heap.
14557       // b();
14558 
14559       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14560         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14561           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14562             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14563               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14564 
14565       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14566         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14567                               NTCUC_Assignment, NTCUK_Copy);
14568     }
14569     RecordModifiableNonNullParam(*this, LHS.get());
14570     break;
14571   case BO_PtrMemD:
14572   case BO_PtrMemI:
14573     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14574                                             Opc == BO_PtrMemI);
14575     break;
14576   case BO_Mul:
14577   case BO_Div:
14578     ConvertHalfVec = true;
14579     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14580                                            Opc == BO_Div);
14581     break;
14582   case BO_Rem:
14583     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14584     break;
14585   case BO_Add:
14586     ConvertHalfVec = true;
14587     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14588     break;
14589   case BO_Sub:
14590     ConvertHalfVec = true;
14591     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14592     break;
14593   case BO_Shl:
14594   case BO_Shr:
14595     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14596     break;
14597   case BO_LE:
14598   case BO_LT:
14599   case BO_GE:
14600   case BO_GT:
14601     ConvertHalfVec = true;
14602     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14603     break;
14604   case BO_EQ:
14605   case BO_NE:
14606     ConvertHalfVec = true;
14607     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14608     break;
14609   case BO_Cmp:
14610     ConvertHalfVec = true;
14611     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14612     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14613     break;
14614   case BO_And:
14615     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14616     LLVM_FALLTHROUGH;
14617   case BO_Xor:
14618   case BO_Or:
14619     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14620     break;
14621   case BO_LAnd:
14622   case BO_LOr:
14623     ConvertHalfVec = true;
14624     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14625     break;
14626   case BO_MulAssign:
14627   case BO_DivAssign:
14628     ConvertHalfVec = true;
14629     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14630                                                Opc == BO_DivAssign);
14631     CompLHSTy = CompResultTy;
14632     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14633       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14634     break;
14635   case BO_RemAssign:
14636     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14637     CompLHSTy = CompResultTy;
14638     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14639       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14640     break;
14641   case BO_AddAssign:
14642     ConvertHalfVec = true;
14643     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14644     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14645       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14646     break;
14647   case BO_SubAssign:
14648     ConvertHalfVec = true;
14649     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14650     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14651       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14652     break;
14653   case BO_ShlAssign:
14654   case BO_ShrAssign:
14655     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14656     CompLHSTy = CompResultTy;
14657     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14658       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14659     break;
14660   case BO_AndAssign:
14661   case BO_OrAssign: // fallthrough
14662     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14663     LLVM_FALLTHROUGH;
14664   case BO_XorAssign:
14665     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14666     CompLHSTy = CompResultTy;
14667     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14668       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14669     break;
14670   case BO_Comma:
14671     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14672     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14673       VK = RHS.get()->getValueKind();
14674       OK = RHS.get()->getObjectKind();
14675     }
14676     break;
14677   }
14678   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14679     return ExprError();
14680 
14681   // Some of the binary operations require promoting operands of half vector to
14682   // float vectors and truncating the result back to half vector. For now, we do
14683   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14684   // arm64).
14685   assert(
14686       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14687                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14688       "both sides are half vectors or neither sides are");
14689   ConvertHalfVec =
14690       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14691 
14692   // Check for array bounds violations for both sides of the BinaryOperator
14693   CheckArrayAccess(LHS.get());
14694   CheckArrayAccess(RHS.get());
14695 
14696   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14697     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14698                                                  &Context.Idents.get("object_setClass"),
14699                                                  SourceLocation(), LookupOrdinaryName);
14700     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14701       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14702       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14703           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14704                                         "object_setClass(")
14705           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14706                                           ",")
14707           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14708     }
14709     else
14710       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14711   }
14712   else if (const ObjCIvarRefExpr *OIRE =
14713            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14714     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14715 
14716   // Opc is not a compound assignment if CompResultTy is null.
14717   if (CompResultTy.isNull()) {
14718     if (ConvertHalfVec)
14719       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14720                                  OpLoc, CurFPFeatureOverrides());
14721     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14722                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14723   }
14724 
14725   // Handle compound assignments.
14726   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14727       OK_ObjCProperty) {
14728     VK = VK_LValue;
14729     OK = LHS.get()->getObjectKind();
14730   }
14731 
14732   // The LHS is not converted to the result type for fixed-point compound
14733   // assignment as the common type is computed on demand. Reset the CompLHSTy
14734   // to the LHS type we would have gotten after unary conversions.
14735   if (CompResultTy->isFixedPointType())
14736     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14737 
14738   if (ConvertHalfVec)
14739     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14740                                OpLoc, CurFPFeatureOverrides());
14741 
14742   return CompoundAssignOperator::Create(
14743       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14744       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14745 }
14746 
14747 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14748 /// operators are mixed in a way that suggests that the programmer forgot that
14749 /// comparison operators have higher precedence. The most typical example of
14750 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14751 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14752                                       SourceLocation OpLoc, Expr *LHSExpr,
14753                                       Expr *RHSExpr) {
14754   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14755   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14756 
14757   // Check that one of the sides is a comparison operator and the other isn't.
14758   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14759   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14760   if (isLeftComp == isRightComp)
14761     return;
14762 
14763   // Bitwise operations are sometimes used as eager logical ops.
14764   // Don't diagnose this.
14765   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14766   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14767   if (isLeftBitwise || isRightBitwise)
14768     return;
14769 
14770   SourceRange DiagRange = isLeftComp
14771                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14772                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14773   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14774   SourceRange ParensRange =
14775       isLeftComp
14776           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14777           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14778 
14779   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14780     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14781   SuggestParentheses(Self, OpLoc,
14782     Self.PDiag(diag::note_precedence_silence) << OpStr,
14783     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14784   SuggestParentheses(Self, OpLoc,
14785     Self.PDiag(diag::note_precedence_bitwise_first)
14786       << BinaryOperator::getOpcodeStr(Opc),
14787     ParensRange);
14788 }
14789 
14790 /// It accepts a '&&' expr that is inside a '||' one.
14791 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14792 /// in parentheses.
14793 static void
14794 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14795                                        BinaryOperator *Bop) {
14796   assert(Bop->getOpcode() == BO_LAnd);
14797   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14798       << Bop->getSourceRange() << OpLoc;
14799   SuggestParentheses(Self, Bop->getOperatorLoc(),
14800     Self.PDiag(diag::note_precedence_silence)
14801       << Bop->getOpcodeStr(),
14802     Bop->getSourceRange());
14803 }
14804 
14805 /// Returns true if the given expression can be evaluated as a constant
14806 /// 'true'.
14807 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14808   bool Res;
14809   return !E->isValueDependent() &&
14810          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14811 }
14812 
14813 /// Returns true if the given expression can be evaluated as a constant
14814 /// 'false'.
14815 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14816   bool Res;
14817   return !E->isValueDependent() &&
14818          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14819 }
14820 
14821 /// Look for '&&' in the left hand of a '||' expr.
14822 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14823                                              Expr *LHSExpr, Expr *RHSExpr) {
14824   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14825     if (Bop->getOpcode() == BO_LAnd) {
14826       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14827       if (EvaluatesAsFalse(S, RHSExpr))
14828         return;
14829       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14830       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14831         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14832     } else if (Bop->getOpcode() == BO_LOr) {
14833       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14834         // If it's "a || b && 1 || c" we didn't warn earlier for
14835         // "a || b && 1", but warn now.
14836         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14837           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14838       }
14839     }
14840   }
14841 }
14842 
14843 /// Look for '&&' in the right hand of a '||' expr.
14844 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14845                                              Expr *LHSExpr, Expr *RHSExpr) {
14846   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14847     if (Bop->getOpcode() == BO_LAnd) {
14848       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14849       if (EvaluatesAsFalse(S, LHSExpr))
14850         return;
14851       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14852       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14853         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14854     }
14855   }
14856 }
14857 
14858 /// Look for bitwise op in the left or right hand of a bitwise op with
14859 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14860 /// the '&' expression in parentheses.
14861 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14862                                          SourceLocation OpLoc, Expr *SubExpr) {
14863   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14864     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14865       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14866         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14867         << Bop->getSourceRange() << OpLoc;
14868       SuggestParentheses(S, Bop->getOperatorLoc(),
14869         S.PDiag(diag::note_precedence_silence)
14870           << Bop->getOpcodeStr(),
14871         Bop->getSourceRange());
14872     }
14873   }
14874 }
14875 
14876 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14877                                     Expr *SubExpr, StringRef Shift) {
14878   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14879     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14880       StringRef Op = Bop->getOpcodeStr();
14881       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14882           << Bop->getSourceRange() << OpLoc << Shift << Op;
14883       SuggestParentheses(S, Bop->getOperatorLoc(),
14884           S.PDiag(diag::note_precedence_silence) << Op,
14885           Bop->getSourceRange());
14886     }
14887   }
14888 }
14889 
14890 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14891                                  Expr *LHSExpr, Expr *RHSExpr) {
14892   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14893   if (!OCE)
14894     return;
14895 
14896   FunctionDecl *FD = OCE->getDirectCallee();
14897   if (!FD || !FD->isOverloadedOperator())
14898     return;
14899 
14900   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14901   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14902     return;
14903 
14904   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14905       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14906       << (Kind == OO_LessLess);
14907   SuggestParentheses(S, OCE->getOperatorLoc(),
14908                      S.PDiag(diag::note_precedence_silence)
14909                          << (Kind == OO_LessLess ? "<<" : ">>"),
14910                      OCE->getSourceRange());
14911   SuggestParentheses(
14912       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14913       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14914 }
14915 
14916 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14917 /// precedence.
14918 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14919                                     SourceLocation OpLoc, Expr *LHSExpr,
14920                                     Expr *RHSExpr){
14921   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14922   if (BinaryOperator::isBitwiseOp(Opc))
14923     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14924 
14925   // Diagnose "arg1 & arg2 | arg3"
14926   if ((Opc == BO_Or || Opc == BO_Xor) &&
14927       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14928     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14929     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14930   }
14931 
14932   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14933   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14934   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14935     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14936     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14937   }
14938 
14939   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14940       || Opc == BO_Shr) {
14941     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14942     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14943     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14944   }
14945 
14946   // Warn on overloaded shift operators and comparisons, such as:
14947   // cout << 5 == 4;
14948   if (BinaryOperator::isComparisonOp(Opc))
14949     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14950 }
14951 
14952 // Binary Operators.  'Tok' is the token for the operator.
14953 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14954                             tok::TokenKind Kind,
14955                             Expr *LHSExpr, Expr *RHSExpr) {
14956   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14957   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14958   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14959 
14960   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14961   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14962 
14963   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14964 }
14965 
14966 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14967                        UnresolvedSetImpl &Functions) {
14968   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14969   if (OverOp != OO_None && OverOp != OO_Equal)
14970     LookupOverloadedOperatorName(OverOp, S, Functions);
14971 
14972   // In C++20 onwards, we may have a second operator to look up.
14973   if (getLangOpts().CPlusPlus20) {
14974     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14975       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14976   }
14977 }
14978 
14979 /// Build an overloaded binary operator expression in the given scope.
14980 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14981                                        BinaryOperatorKind Opc,
14982                                        Expr *LHS, Expr *RHS) {
14983   switch (Opc) {
14984   case BO_Assign:
14985   case BO_DivAssign:
14986   case BO_RemAssign:
14987   case BO_SubAssign:
14988   case BO_AndAssign:
14989   case BO_OrAssign:
14990   case BO_XorAssign:
14991     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14992     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14993     break;
14994   default:
14995     break;
14996   }
14997 
14998   // Find all of the overloaded operators visible from this point.
14999   UnresolvedSet<16> Functions;
15000   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15001 
15002   // Build the (potentially-overloaded, potentially-dependent)
15003   // binary operation.
15004   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15005 }
15006 
15007 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15008                             BinaryOperatorKind Opc,
15009                             Expr *LHSExpr, Expr *RHSExpr) {
15010   ExprResult LHS, RHS;
15011   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15012   if (!LHS.isUsable() || !RHS.isUsable())
15013     return ExprError();
15014   LHSExpr = LHS.get();
15015   RHSExpr = RHS.get();
15016 
15017   // We want to end up calling one of checkPseudoObjectAssignment
15018   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15019   // both expressions are overloadable or either is type-dependent),
15020   // or CreateBuiltinBinOp (in any other case).  We also want to get
15021   // any placeholder types out of the way.
15022 
15023   // Handle pseudo-objects in the LHS.
15024   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15025     // Assignments with a pseudo-object l-value need special analysis.
15026     if (pty->getKind() == BuiltinType::PseudoObject &&
15027         BinaryOperator::isAssignmentOp(Opc))
15028       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15029 
15030     // Don't resolve overloads if the other type is overloadable.
15031     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15032       // We can't actually test that if we still have a placeholder,
15033       // though.  Fortunately, none of the exceptions we see in that
15034       // code below are valid when the LHS is an overload set.  Note
15035       // that an overload set can be dependently-typed, but it never
15036       // instantiates to having an overloadable type.
15037       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15038       if (resolvedRHS.isInvalid()) return ExprError();
15039       RHSExpr = resolvedRHS.get();
15040 
15041       if (RHSExpr->isTypeDependent() ||
15042           RHSExpr->getType()->isOverloadableType())
15043         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15044     }
15045 
15046     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15047     // template, diagnose the missing 'template' keyword instead of diagnosing
15048     // an invalid use of a bound member function.
15049     //
15050     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15051     // to C++1z [over.over]/1.4, but we already checked for that case above.
15052     if (Opc == BO_LT && inTemplateInstantiation() &&
15053         (pty->getKind() == BuiltinType::BoundMember ||
15054          pty->getKind() == BuiltinType::Overload)) {
15055       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15056       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15057           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15058             return isa<FunctionTemplateDecl>(ND);
15059           })) {
15060         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15061                                 : OE->getNameLoc(),
15062              diag::err_template_kw_missing)
15063           << OE->getName().getAsString() << "";
15064         return ExprError();
15065       }
15066     }
15067 
15068     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15069     if (LHS.isInvalid()) return ExprError();
15070     LHSExpr = LHS.get();
15071   }
15072 
15073   // Handle pseudo-objects in the RHS.
15074   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15075     // An overload in the RHS can potentially be resolved by the type
15076     // being assigned to.
15077     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15078       if (getLangOpts().CPlusPlus &&
15079           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15080            LHSExpr->getType()->isOverloadableType()))
15081         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15082 
15083       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15084     }
15085 
15086     // Don't resolve overloads if the other type is overloadable.
15087     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15088         LHSExpr->getType()->isOverloadableType())
15089       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15090 
15091     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15092     if (!resolvedRHS.isUsable()) return ExprError();
15093     RHSExpr = resolvedRHS.get();
15094   }
15095 
15096   if (getLangOpts().CPlusPlus) {
15097     // If either expression is type-dependent, always build an
15098     // overloaded op.
15099     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15100       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15101 
15102     // Otherwise, build an overloaded op if either expression has an
15103     // overloadable type.
15104     if (LHSExpr->getType()->isOverloadableType() ||
15105         RHSExpr->getType()->isOverloadableType())
15106       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15107   }
15108 
15109   if (getLangOpts().RecoveryAST &&
15110       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15111     assert(!getLangOpts().CPlusPlus);
15112     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15113            "Should only occur in error-recovery path.");
15114     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15115       // C [6.15.16] p3:
15116       // An assignment expression has the value of the left operand after the
15117       // assignment, but is not an lvalue.
15118       return CompoundAssignOperator::Create(
15119           Context, LHSExpr, RHSExpr, Opc,
15120           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15121           OpLoc, CurFPFeatureOverrides());
15122     QualType ResultType;
15123     switch (Opc) {
15124     case BO_Assign:
15125       ResultType = LHSExpr->getType().getUnqualifiedType();
15126       break;
15127     case BO_LT:
15128     case BO_GT:
15129     case BO_LE:
15130     case BO_GE:
15131     case BO_EQ:
15132     case BO_NE:
15133     case BO_LAnd:
15134     case BO_LOr:
15135       // These operators have a fixed result type regardless of operands.
15136       ResultType = Context.IntTy;
15137       break;
15138     case BO_Comma:
15139       ResultType = RHSExpr->getType();
15140       break;
15141     default:
15142       ResultType = Context.DependentTy;
15143       break;
15144     }
15145     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15146                                   VK_PRValue, OK_Ordinary, OpLoc,
15147                                   CurFPFeatureOverrides());
15148   }
15149 
15150   // Build a built-in binary operation.
15151   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15152 }
15153 
15154 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15155   if (T.isNull() || T->isDependentType())
15156     return false;
15157 
15158   if (!T->isPromotableIntegerType())
15159     return true;
15160 
15161   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15162 }
15163 
15164 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15165                                       UnaryOperatorKind Opc,
15166                                       Expr *InputExpr) {
15167   ExprResult Input = InputExpr;
15168   ExprValueKind VK = VK_PRValue;
15169   ExprObjectKind OK = OK_Ordinary;
15170   QualType resultType;
15171   bool CanOverflow = false;
15172 
15173   bool ConvertHalfVec = false;
15174   if (getLangOpts().OpenCL) {
15175     QualType Ty = InputExpr->getType();
15176     // The only legal unary operation for atomics is '&'.
15177     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15178     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15179     // only with a builtin functions and therefore should be disallowed here.
15180         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15181         || Ty->isBlockPointerType())) {
15182       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15183                        << InputExpr->getType()
15184                        << Input.get()->getSourceRange());
15185     }
15186   }
15187 
15188   switch (Opc) {
15189   case UO_PreInc:
15190   case UO_PreDec:
15191   case UO_PostInc:
15192   case UO_PostDec:
15193     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15194                                                 OpLoc,
15195                                                 Opc == UO_PreInc ||
15196                                                 Opc == UO_PostInc,
15197                                                 Opc == UO_PreInc ||
15198                                                 Opc == UO_PreDec);
15199     CanOverflow = isOverflowingIntegerType(Context, resultType);
15200     break;
15201   case UO_AddrOf:
15202     resultType = CheckAddressOfOperand(Input, OpLoc);
15203     CheckAddressOfNoDeref(InputExpr);
15204     RecordModifiableNonNullParam(*this, InputExpr);
15205     break;
15206   case UO_Deref: {
15207     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15208     if (Input.isInvalid()) return ExprError();
15209     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15210     break;
15211   }
15212   case UO_Plus:
15213   case UO_Minus:
15214     CanOverflow = Opc == UO_Minus &&
15215                   isOverflowingIntegerType(Context, Input.get()->getType());
15216     Input = UsualUnaryConversions(Input.get());
15217     if (Input.isInvalid()) return ExprError();
15218     // Unary plus and minus require promoting an operand of half vector to a
15219     // float vector and truncating the result back to a half vector. For now, we
15220     // do this only when HalfArgsAndReturns is set (that is, when the target is
15221     // arm or arm64).
15222     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15223 
15224     // If the operand is a half vector, promote it to a float vector.
15225     if (ConvertHalfVec)
15226       Input = convertVector(Input.get(), Context.FloatTy, *this);
15227     resultType = Input.get()->getType();
15228     if (resultType->isDependentType())
15229       break;
15230     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15231       break;
15232     else if (resultType->isVectorType() &&
15233              // The z vector extensions don't allow + or - with bool vectors.
15234              (!Context.getLangOpts().ZVector ||
15235               resultType->castAs<VectorType>()->getVectorKind() !=
15236               VectorType::AltiVecBool))
15237       break;
15238     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15239              Opc == UO_Plus &&
15240              resultType->isPointerType())
15241       break;
15242 
15243     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15244       << resultType << Input.get()->getSourceRange());
15245 
15246   case UO_Not: // bitwise complement
15247     Input = UsualUnaryConversions(Input.get());
15248     if (Input.isInvalid())
15249       return ExprError();
15250     resultType = Input.get()->getType();
15251     if (resultType->isDependentType())
15252       break;
15253     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15254     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15255       // C99 does not support '~' for complex conjugation.
15256       Diag(OpLoc, diag::ext_integer_complement_complex)
15257           << resultType << Input.get()->getSourceRange();
15258     else if (resultType->hasIntegerRepresentation())
15259       break;
15260     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15261       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15262       // on vector float types.
15263       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15264       if (!T->isIntegerType())
15265         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15266                           << resultType << Input.get()->getSourceRange());
15267     } else {
15268       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15269                        << resultType << Input.get()->getSourceRange());
15270     }
15271     break;
15272 
15273   case UO_LNot: // logical negation
15274     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15275     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15276     if (Input.isInvalid()) return ExprError();
15277     resultType = Input.get()->getType();
15278 
15279     // Though we still have to promote half FP to float...
15280     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15281       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15282       resultType = Context.FloatTy;
15283     }
15284 
15285     if (resultType->isDependentType())
15286       break;
15287     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15288       // C99 6.5.3.3p1: ok, fallthrough;
15289       if (Context.getLangOpts().CPlusPlus) {
15290         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15291         // operand contextually converted to bool.
15292         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15293                                   ScalarTypeToBooleanCastKind(resultType));
15294       } else if (Context.getLangOpts().OpenCL &&
15295                  Context.getLangOpts().OpenCLVersion < 120) {
15296         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15297         // operate on scalar float types.
15298         if (!resultType->isIntegerType() && !resultType->isPointerType())
15299           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15300                            << resultType << Input.get()->getSourceRange());
15301       }
15302     } else if (resultType->isExtVectorType()) {
15303       if (Context.getLangOpts().OpenCL &&
15304           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15305         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15306         // operate on vector float types.
15307         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15308         if (!T->isIntegerType())
15309           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15310                            << resultType << Input.get()->getSourceRange());
15311       }
15312       // Vector logical not returns the signed variant of the operand type.
15313       resultType = GetSignedVectorType(resultType);
15314       break;
15315     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15316       const VectorType *VTy = resultType->castAs<VectorType>();
15317       if (VTy->getVectorKind() != VectorType::GenericVector)
15318         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15319                          << resultType << Input.get()->getSourceRange());
15320 
15321       // Vector logical not returns the signed variant of the operand type.
15322       resultType = GetSignedVectorType(resultType);
15323       break;
15324     } else {
15325       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15326         << resultType << Input.get()->getSourceRange());
15327     }
15328 
15329     // LNot always has type int. C99 6.5.3.3p5.
15330     // In C++, it's bool. C++ 5.3.1p8
15331     resultType = Context.getLogicalOperationType();
15332     break;
15333   case UO_Real:
15334   case UO_Imag:
15335     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15336     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15337     // complex l-values to ordinary l-values and all other values to r-values.
15338     if (Input.isInvalid()) return ExprError();
15339     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15340       if (Input.get()->isGLValue() &&
15341           Input.get()->getObjectKind() == OK_Ordinary)
15342         VK = Input.get()->getValueKind();
15343     } else if (!getLangOpts().CPlusPlus) {
15344       // In C, a volatile scalar is read by __imag. In C++, it is not.
15345       Input = DefaultLvalueConversion(Input.get());
15346     }
15347     break;
15348   case UO_Extension:
15349     resultType = Input.get()->getType();
15350     VK = Input.get()->getValueKind();
15351     OK = Input.get()->getObjectKind();
15352     break;
15353   case UO_Coawait:
15354     // It's unnecessary to represent the pass-through operator co_await in the
15355     // AST; just return the input expression instead.
15356     assert(!Input.get()->getType()->isDependentType() &&
15357                    "the co_await expression must be non-dependant before "
15358                    "building operator co_await");
15359     return Input;
15360   }
15361   if (resultType.isNull() || Input.isInvalid())
15362     return ExprError();
15363 
15364   // Check for array bounds violations in the operand of the UnaryOperator,
15365   // except for the '*' and '&' operators that have to be handled specially
15366   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15367   // that are explicitly defined as valid by the standard).
15368   if (Opc != UO_AddrOf && Opc != UO_Deref)
15369     CheckArrayAccess(Input.get());
15370 
15371   auto *UO =
15372       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15373                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15374 
15375   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15376       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15377       !isUnevaluatedContext())
15378     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15379 
15380   // Convert the result back to a half vector.
15381   if (ConvertHalfVec)
15382     return convertVector(UO, Context.HalfTy, *this);
15383   return UO;
15384 }
15385 
15386 /// Determine whether the given expression is a qualified member
15387 /// access expression, of a form that could be turned into a pointer to member
15388 /// with the address-of operator.
15389 bool Sema::isQualifiedMemberAccess(Expr *E) {
15390   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15391     if (!DRE->getQualifier())
15392       return false;
15393 
15394     ValueDecl *VD = DRE->getDecl();
15395     if (!VD->isCXXClassMember())
15396       return false;
15397 
15398     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15399       return true;
15400     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15401       return Method->isInstance();
15402 
15403     return false;
15404   }
15405 
15406   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15407     if (!ULE->getQualifier())
15408       return false;
15409 
15410     for (NamedDecl *D : ULE->decls()) {
15411       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15412         if (Method->isInstance())
15413           return true;
15414       } else {
15415         // Overload set does not contain methods.
15416         break;
15417       }
15418     }
15419 
15420     return false;
15421   }
15422 
15423   return false;
15424 }
15425 
15426 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15427                               UnaryOperatorKind Opc, Expr *Input) {
15428   // First things first: handle placeholders so that the
15429   // overloaded-operator check considers the right type.
15430   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15431     // Increment and decrement of pseudo-object references.
15432     if (pty->getKind() == BuiltinType::PseudoObject &&
15433         UnaryOperator::isIncrementDecrementOp(Opc))
15434       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15435 
15436     // extension is always a builtin operator.
15437     if (Opc == UO_Extension)
15438       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15439 
15440     // & gets special logic for several kinds of placeholder.
15441     // The builtin code knows what to do.
15442     if (Opc == UO_AddrOf &&
15443         (pty->getKind() == BuiltinType::Overload ||
15444          pty->getKind() == BuiltinType::UnknownAny ||
15445          pty->getKind() == BuiltinType::BoundMember))
15446       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15447 
15448     // Anything else needs to be handled now.
15449     ExprResult Result = CheckPlaceholderExpr(Input);
15450     if (Result.isInvalid()) return ExprError();
15451     Input = Result.get();
15452   }
15453 
15454   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15455       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15456       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15457     // Find all of the overloaded operators visible from this point.
15458     UnresolvedSet<16> Functions;
15459     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15460     if (S && OverOp != OO_None)
15461       LookupOverloadedOperatorName(OverOp, S, Functions);
15462 
15463     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15464   }
15465 
15466   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15467 }
15468 
15469 // Unary Operators.  'Tok' is the token for the operator.
15470 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15471                               tok::TokenKind Op, Expr *Input) {
15472   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15473 }
15474 
15475 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15476 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15477                                 LabelDecl *TheDecl) {
15478   TheDecl->markUsed(Context);
15479   // Create the AST node.  The address of a label always has type 'void*'.
15480   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15481                                      Context.getPointerType(Context.VoidTy));
15482 }
15483 
15484 void Sema::ActOnStartStmtExpr() {
15485   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15486 }
15487 
15488 void Sema::ActOnStmtExprError() {
15489   // Note that function is also called by TreeTransform when leaving a
15490   // StmtExpr scope without rebuilding anything.
15491 
15492   DiscardCleanupsInEvaluationContext();
15493   PopExpressionEvaluationContext();
15494 }
15495 
15496 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15497                                SourceLocation RPLoc) {
15498   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15499 }
15500 
15501 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15502                                SourceLocation RPLoc, unsigned TemplateDepth) {
15503   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15504   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15505 
15506   if (hasAnyUnrecoverableErrorsInThisFunction())
15507     DiscardCleanupsInEvaluationContext();
15508   assert(!Cleanup.exprNeedsCleanups() &&
15509          "cleanups within StmtExpr not correctly bound!");
15510   PopExpressionEvaluationContext();
15511 
15512   // FIXME: there are a variety of strange constraints to enforce here, for
15513   // example, it is not possible to goto into a stmt expression apparently.
15514   // More semantic analysis is needed.
15515 
15516   // If there are sub-stmts in the compound stmt, take the type of the last one
15517   // as the type of the stmtexpr.
15518   QualType Ty = Context.VoidTy;
15519   bool StmtExprMayBindToTemp = false;
15520   if (!Compound->body_empty()) {
15521     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15522     if (const auto *LastStmt =
15523             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15524       if (const Expr *Value = LastStmt->getExprStmt()) {
15525         StmtExprMayBindToTemp = true;
15526         Ty = Value->getType();
15527       }
15528     }
15529   }
15530 
15531   // FIXME: Check that expression type is complete/non-abstract; statement
15532   // expressions are not lvalues.
15533   Expr *ResStmtExpr =
15534       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15535   if (StmtExprMayBindToTemp)
15536     return MaybeBindToTemporary(ResStmtExpr);
15537   return ResStmtExpr;
15538 }
15539 
15540 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15541   if (ER.isInvalid())
15542     return ExprError();
15543 
15544   // Do function/array conversion on the last expression, but not
15545   // lvalue-to-rvalue.  However, initialize an unqualified type.
15546   ER = DefaultFunctionArrayConversion(ER.get());
15547   if (ER.isInvalid())
15548     return ExprError();
15549   Expr *E = ER.get();
15550 
15551   if (E->isTypeDependent())
15552     return E;
15553 
15554   // In ARC, if the final expression ends in a consume, splice
15555   // the consume out and bind it later.  In the alternate case
15556   // (when dealing with a retainable type), the result
15557   // initialization will create a produce.  In both cases the
15558   // result will be +1, and we'll need to balance that out with
15559   // a bind.
15560   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15561   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15562     return Cast->getSubExpr();
15563 
15564   // FIXME: Provide a better location for the initialization.
15565   return PerformCopyInitialization(
15566       InitializedEntity::InitializeStmtExprResult(
15567           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15568       SourceLocation(), E);
15569 }
15570 
15571 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15572                                       TypeSourceInfo *TInfo,
15573                                       ArrayRef<OffsetOfComponent> Components,
15574                                       SourceLocation RParenLoc) {
15575   QualType ArgTy = TInfo->getType();
15576   bool Dependent = ArgTy->isDependentType();
15577   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15578 
15579   // We must have at least one component that refers to the type, and the first
15580   // one is known to be a field designator.  Verify that the ArgTy represents
15581   // a struct/union/class.
15582   if (!Dependent && !ArgTy->isRecordType())
15583     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15584                        << ArgTy << TypeRange);
15585 
15586   // Type must be complete per C99 7.17p3 because a declaring a variable
15587   // with an incomplete type would be ill-formed.
15588   if (!Dependent
15589       && RequireCompleteType(BuiltinLoc, ArgTy,
15590                              diag::err_offsetof_incomplete_type, TypeRange))
15591     return ExprError();
15592 
15593   bool DidWarnAboutNonPOD = false;
15594   QualType CurrentType = ArgTy;
15595   SmallVector<OffsetOfNode, 4> Comps;
15596   SmallVector<Expr*, 4> Exprs;
15597   for (const OffsetOfComponent &OC : Components) {
15598     if (OC.isBrackets) {
15599       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15600       if (!CurrentType->isDependentType()) {
15601         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15602         if(!AT)
15603           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15604                            << CurrentType);
15605         CurrentType = AT->getElementType();
15606       } else
15607         CurrentType = Context.DependentTy;
15608 
15609       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15610       if (IdxRval.isInvalid())
15611         return ExprError();
15612       Expr *Idx = IdxRval.get();
15613 
15614       // The expression must be an integral expression.
15615       // FIXME: An integral constant expression?
15616       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15617           !Idx->getType()->isIntegerType())
15618         return ExprError(
15619             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15620             << Idx->getSourceRange());
15621 
15622       // Record this array index.
15623       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15624       Exprs.push_back(Idx);
15625       continue;
15626     }
15627 
15628     // Offset of a field.
15629     if (CurrentType->isDependentType()) {
15630       // We have the offset of a field, but we can't look into the dependent
15631       // type. Just record the identifier of the field.
15632       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15633       CurrentType = Context.DependentTy;
15634       continue;
15635     }
15636 
15637     // We need to have a complete type to look into.
15638     if (RequireCompleteType(OC.LocStart, CurrentType,
15639                             diag::err_offsetof_incomplete_type))
15640       return ExprError();
15641 
15642     // Look for the designated field.
15643     const RecordType *RC = CurrentType->getAs<RecordType>();
15644     if (!RC)
15645       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15646                        << CurrentType);
15647     RecordDecl *RD = RC->getDecl();
15648 
15649     // C++ [lib.support.types]p5:
15650     //   The macro offsetof accepts a restricted set of type arguments in this
15651     //   International Standard. type shall be a POD structure or a POD union
15652     //   (clause 9).
15653     // C++11 [support.types]p4:
15654     //   If type is not a standard-layout class (Clause 9), the results are
15655     //   undefined.
15656     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15657       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15658       unsigned DiagID =
15659         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15660                             : diag::ext_offsetof_non_pod_type;
15661 
15662       if (!IsSafe && !DidWarnAboutNonPOD &&
15663           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15664                               PDiag(DiagID)
15665                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15666                               << CurrentType))
15667         DidWarnAboutNonPOD = true;
15668     }
15669 
15670     // Look for the field.
15671     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15672     LookupQualifiedName(R, RD);
15673     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15674     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15675     if (!MemberDecl) {
15676       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15677         MemberDecl = IndirectMemberDecl->getAnonField();
15678     }
15679 
15680     if (!MemberDecl)
15681       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15682                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15683                                                               OC.LocEnd));
15684 
15685     // C99 7.17p3:
15686     //   (If the specified member is a bit-field, the behavior is undefined.)
15687     //
15688     // We diagnose this as an error.
15689     if (MemberDecl->isBitField()) {
15690       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15691         << MemberDecl->getDeclName()
15692         << SourceRange(BuiltinLoc, RParenLoc);
15693       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15694       return ExprError();
15695     }
15696 
15697     RecordDecl *Parent = MemberDecl->getParent();
15698     if (IndirectMemberDecl)
15699       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15700 
15701     // If the member was found in a base class, introduce OffsetOfNodes for
15702     // the base class indirections.
15703     CXXBasePaths Paths;
15704     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15705                       Paths)) {
15706       if (Paths.getDetectedVirtual()) {
15707         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15708           << MemberDecl->getDeclName()
15709           << SourceRange(BuiltinLoc, RParenLoc);
15710         return ExprError();
15711       }
15712 
15713       CXXBasePath &Path = Paths.front();
15714       for (const CXXBasePathElement &B : Path)
15715         Comps.push_back(OffsetOfNode(B.Base));
15716     }
15717 
15718     if (IndirectMemberDecl) {
15719       for (auto *FI : IndirectMemberDecl->chain()) {
15720         assert(isa<FieldDecl>(FI));
15721         Comps.push_back(OffsetOfNode(OC.LocStart,
15722                                      cast<FieldDecl>(FI), OC.LocEnd));
15723       }
15724     } else
15725       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15726 
15727     CurrentType = MemberDecl->getType().getNonReferenceType();
15728   }
15729 
15730   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15731                               Comps, Exprs, RParenLoc);
15732 }
15733 
15734 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15735                                       SourceLocation BuiltinLoc,
15736                                       SourceLocation TypeLoc,
15737                                       ParsedType ParsedArgTy,
15738                                       ArrayRef<OffsetOfComponent> Components,
15739                                       SourceLocation RParenLoc) {
15740 
15741   TypeSourceInfo *ArgTInfo;
15742   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15743   if (ArgTy.isNull())
15744     return ExprError();
15745 
15746   if (!ArgTInfo)
15747     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15748 
15749   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15750 }
15751 
15752 
15753 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15754                                  Expr *CondExpr,
15755                                  Expr *LHSExpr, Expr *RHSExpr,
15756                                  SourceLocation RPLoc) {
15757   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15758 
15759   ExprValueKind VK = VK_PRValue;
15760   ExprObjectKind OK = OK_Ordinary;
15761   QualType resType;
15762   bool CondIsTrue = false;
15763   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15764     resType = Context.DependentTy;
15765   } else {
15766     // The conditional expression is required to be a constant expression.
15767     llvm::APSInt condEval(32);
15768     ExprResult CondICE = VerifyIntegerConstantExpression(
15769         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15770     if (CondICE.isInvalid())
15771       return ExprError();
15772     CondExpr = CondICE.get();
15773     CondIsTrue = condEval.getZExtValue();
15774 
15775     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15776     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15777 
15778     resType = ActiveExpr->getType();
15779     VK = ActiveExpr->getValueKind();
15780     OK = ActiveExpr->getObjectKind();
15781   }
15782 
15783   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15784                                   resType, VK, OK, RPLoc, CondIsTrue);
15785 }
15786 
15787 //===----------------------------------------------------------------------===//
15788 // Clang Extensions.
15789 //===----------------------------------------------------------------------===//
15790 
15791 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15792 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15793   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15794 
15795   if (LangOpts.CPlusPlus) {
15796     MangleNumberingContext *MCtx;
15797     Decl *ManglingContextDecl;
15798     std::tie(MCtx, ManglingContextDecl) =
15799         getCurrentMangleNumberContext(Block->getDeclContext());
15800     if (MCtx) {
15801       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15802       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15803     }
15804   }
15805 
15806   PushBlockScope(CurScope, Block);
15807   CurContext->addDecl(Block);
15808   if (CurScope)
15809     PushDeclContext(CurScope, Block);
15810   else
15811     CurContext = Block;
15812 
15813   getCurBlock()->HasImplicitReturnType = true;
15814 
15815   // Enter a new evaluation context to insulate the block from any
15816   // cleanups from the enclosing full-expression.
15817   PushExpressionEvaluationContext(
15818       ExpressionEvaluationContext::PotentiallyEvaluated);
15819 }
15820 
15821 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15822                                Scope *CurScope) {
15823   assert(ParamInfo.getIdentifier() == nullptr &&
15824          "block-id should have no identifier!");
15825   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15826   BlockScopeInfo *CurBlock = getCurBlock();
15827 
15828   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15829   QualType T = Sig->getType();
15830 
15831   // FIXME: We should allow unexpanded parameter packs here, but that would,
15832   // in turn, make the block expression contain unexpanded parameter packs.
15833   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15834     // Drop the parameters.
15835     FunctionProtoType::ExtProtoInfo EPI;
15836     EPI.HasTrailingReturn = false;
15837     EPI.TypeQuals.addConst();
15838     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15839     Sig = Context.getTrivialTypeSourceInfo(T);
15840   }
15841 
15842   // GetTypeForDeclarator always produces a function type for a block
15843   // literal signature.  Furthermore, it is always a FunctionProtoType
15844   // unless the function was written with a typedef.
15845   assert(T->isFunctionType() &&
15846          "GetTypeForDeclarator made a non-function block signature");
15847 
15848   // Look for an explicit signature in that function type.
15849   FunctionProtoTypeLoc ExplicitSignature;
15850 
15851   if ((ExplicitSignature = Sig->getTypeLoc()
15852                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15853 
15854     // Check whether that explicit signature was synthesized by
15855     // GetTypeForDeclarator.  If so, don't save that as part of the
15856     // written signature.
15857     if (ExplicitSignature.getLocalRangeBegin() ==
15858         ExplicitSignature.getLocalRangeEnd()) {
15859       // This would be much cheaper if we stored TypeLocs instead of
15860       // TypeSourceInfos.
15861       TypeLoc Result = ExplicitSignature.getReturnLoc();
15862       unsigned Size = Result.getFullDataSize();
15863       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15864       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15865 
15866       ExplicitSignature = FunctionProtoTypeLoc();
15867     }
15868   }
15869 
15870   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15871   CurBlock->FunctionType = T;
15872 
15873   const auto *Fn = T->castAs<FunctionType>();
15874   QualType RetTy = Fn->getReturnType();
15875   bool isVariadic =
15876       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15877 
15878   CurBlock->TheDecl->setIsVariadic(isVariadic);
15879 
15880   // Context.DependentTy is used as a placeholder for a missing block
15881   // return type.  TODO:  what should we do with declarators like:
15882   //   ^ * { ... }
15883   // If the answer is "apply template argument deduction"....
15884   if (RetTy != Context.DependentTy) {
15885     CurBlock->ReturnType = RetTy;
15886     CurBlock->TheDecl->setBlockMissingReturnType(false);
15887     CurBlock->HasImplicitReturnType = false;
15888   }
15889 
15890   // Push block parameters from the declarator if we had them.
15891   SmallVector<ParmVarDecl*, 8> Params;
15892   if (ExplicitSignature) {
15893     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15894       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15895       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15896           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15897         // Diagnose this as an extension in C17 and earlier.
15898         if (!getLangOpts().C2x)
15899           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15900       }
15901       Params.push_back(Param);
15902     }
15903 
15904   // Fake up parameter variables if we have a typedef, like
15905   //   ^ fntype { ... }
15906   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15907     for (const auto &I : Fn->param_types()) {
15908       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15909           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15910       Params.push_back(Param);
15911     }
15912   }
15913 
15914   // Set the parameters on the block decl.
15915   if (!Params.empty()) {
15916     CurBlock->TheDecl->setParams(Params);
15917     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15918                              /*CheckParameterNames=*/false);
15919   }
15920 
15921   // Finally we can process decl attributes.
15922   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15923 
15924   // Put the parameter variables in scope.
15925   for (auto AI : CurBlock->TheDecl->parameters()) {
15926     AI->setOwningFunction(CurBlock->TheDecl);
15927 
15928     // If this has an identifier, add it to the scope stack.
15929     if (AI->getIdentifier()) {
15930       CheckShadow(CurBlock->TheScope, AI);
15931 
15932       PushOnScopeChains(AI, CurBlock->TheScope);
15933     }
15934   }
15935 }
15936 
15937 /// ActOnBlockError - If there is an error parsing a block, this callback
15938 /// is invoked to pop the information about the block from the action impl.
15939 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15940   // Leave the expression-evaluation context.
15941   DiscardCleanupsInEvaluationContext();
15942   PopExpressionEvaluationContext();
15943 
15944   // Pop off CurBlock, handle nested blocks.
15945   PopDeclContext();
15946   PopFunctionScopeInfo();
15947 }
15948 
15949 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15950 /// literal was successfully completed.  ^(int x){...}
15951 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15952                                     Stmt *Body, Scope *CurScope) {
15953   // If blocks are disabled, emit an error.
15954   if (!LangOpts.Blocks)
15955     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15956 
15957   // Leave the expression-evaluation context.
15958   if (hasAnyUnrecoverableErrorsInThisFunction())
15959     DiscardCleanupsInEvaluationContext();
15960   assert(!Cleanup.exprNeedsCleanups() &&
15961          "cleanups within block not correctly bound!");
15962   PopExpressionEvaluationContext();
15963 
15964   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15965   BlockDecl *BD = BSI->TheDecl;
15966 
15967   if (BSI->HasImplicitReturnType)
15968     deduceClosureReturnType(*BSI);
15969 
15970   QualType RetTy = Context.VoidTy;
15971   if (!BSI->ReturnType.isNull())
15972     RetTy = BSI->ReturnType;
15973 
15974   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15975   QualType BlockTy;
15976 
15977   // If the user wrote a function type in some form, try to use that.
15978   if (!BSI->FunctionType.isNull()) {
15979     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15980 
15981     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15982     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15983 
15984     // Turn protoless block types into nullary block types.
15985     if (isa<FunctionNoProtoType>(FTy)) {
15986       FunctionProtoType::ExtProtoInfo EPI;
15987       EPI.ExtInfo = Ext;
15988       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15989 
15990     // Otherwise, if we don't need to change anything about the function type,
15991     // preserve its sugar structure.
15992     } else if (FTy->getReturnType() == RetTy &&
15993                (!NoReturn || FTy->getNoReturnAttr())) {
15994       BlockTy = BSI->FunctionType;
15995 
15996     // Otherwise, make the minimal modifications to the function type.
15997     } else {
15998       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15999       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16000       EPI.TypeQuals = Qualifiers();
16001       EPI.ExtInfo = Ext;
16002       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16003     }
16004 
16005   // If we don't have a function type, just build one from nothing.
16006   } else {
16007     FunctionProtoType::ExtProtoInfo EPI;
16008     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16009     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16010   }
16011 
16012   DiagnoseUnusedParameters(BD->parameters());
16013   BlockTy = Context.getBlockPointerType(BlockTy);
16014 
16015   // If needed, diagnose invalid gotos and switches in the block.
16016   if (getCurFunction()->NeedsScopeChecking() &&
16017       !PP.isCodeCompletionEnabled())
16018     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16019 
16020   BD->setBody(cast<CompoundStmt>(Body));
16021 
16022   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16023     DiagnoseUnguardedAvailabilityViolations(BD);
16024 
16025   // Try to apply the named return value optimization. We have to check again
16026   // if we can do this, though, because blocks keep return statements around
16027   // to deduce an implicit return type.
16028   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16029       !BD->isDependentContext())
16030     computeNRVO(Body, BSI);
16031 
16032   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16033       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16034     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16035                           NTCUK_Destruct|NTCUK_Copy);
16036 
16037   PopDeclContext();
16038 
16039   // Set the captured variables on the block.
16040   SmallVector<BlockDecl::Capture, 4> Captures;
16041   for (Capture &Cap : BSI->Captures) {
16042     if (Cap.isInvalid() || Cap.isThisCapture())
16043       continue;
16044 
16045     VarDecl *Var = Cap.getVariable();
16046     Expr *CopyExpr = nullptr;
16047     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16048       if (const RecordType *Record =
16049               Cap.getCaptureType()->getAs<RecordType>()) {
16050         // The capture logic needs the destructor, so make sure we mark it.
16051         // Usually this is unnecessary because most local variables have
16052         // their destructors marked at declaration time, but parameters are
16053         // an exception because it's technically only the call site that
16054         // actually requires the destructor.
16055         if (isa<ParmVarDecl>(Var))
16056           FinalizeVarWithDestructor(Var, Record);
16057 
16058         // Enter a separate potentially-evaluated context while building block
16059         // initializers to isolate their cleanups from those of the block
16060         // itself.
16061         // FIXME: Is this appropriate even when the block itself occurs in an
16062         // unevaluated operand?
16063         EnterExpressionEvaluationContext EvalContext(
16064             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16065 
16066         SourceLocation Loc = Cap.getLocation();
16067 
16068         ExprResult Result = BuildDeclarationNameExpr(
16069             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16070 
16071         // According to the blocks spec, the capture of a variable from
16072         // the stack requires a const copy constructor.  This is not true
16073         // of the copy/move done to move a __block variable to the heap.
16074         if (!Result.isInvalid() &&
16075             !Result.get()->getType().isConstQualified()) {
16076           Result = ImpCastExprToType(Result.get(),
16077                                      Result.get()->getType().withConst(),
16078                                      CK_NoOp, VK_LValue);
16079         }
16080 
16081         if (!Result.isInvalid()) {
16082           Result = PerformCopyInitialization(
16083               InitializedEntity::InitializeBlock(Var->getLocation(),
16084                                                  Cap.getCaptureType()),
16085               Loc, Result.get());
16086         }
16087 
16088         // Build a full-expression copy expression if initialization
16089         // succeeded and used a non-trivial constructor.  Recover from
16090         // errors by pretending that the copy isn't necessary.
16091         if (!Result.isInvalid() &&
16092             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16093                 ->isTrivial()) {
16094           Result = MaybeCreateExprWithCleanups(Result);
16095           CopyExpr = Result.get();
16096         }
16097       }
16098     }
16099 
16100     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16101                               CopyExpr);
16102     Captures.push_back(NewCap);
16103   }
16104   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16105 
16106   // Pop the block scope now but keep it alive to the end of this function.
16107   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16108   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16109 
16110   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16111 
16112   // If the block isn't obviously global, i.e. it captures anything at
16113   // all, then we need to do a few things in the surrounding context:
16114   if (Result->getBlockDecl()->hasCaptures()) {
16115     // First, this expression has a new cleanup object.
16116     ExprCleanupObjects.push_back(Result->getBlockDecl());
16117     Cleanup.setExprNeedsCleanups(true);
16118 
16119     // It also gets a branch-protected scope if any of the captured
16120     // variables needs destruction.
16121     for (const auto &CI : Result->getBlockDecl()->captures()) {
16122       const VarDecl *var = CI.getVariable();
16123       if (var->getType().isDestructedType() != QualType::DK_none) {
16124         setFunctionHasBranchProtectedScope();
16125         break;
16126       }
16127     }
16128   }
16129 
16130   if (getCurFunction())
16131     getCurFunction()->addBlock(BD);
16132 
16133   return Result;
16134 }
16135 
16136 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16137                             SourceLocation RPLoc) {
16138   TypeSourceInfo *TInfo;
16139   GetTypeFromParser(Ty, &TInfo);
16140   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16141 }
16142 
16143 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16144                                 Expr *E, TypeSourceInfo *TInfo,
16145                                 SourceLocation RPLoc) {
16146   Expr *OrigExpr = E;
16147   bool IsMS = false;
16148 
16149   // CUDA device code does not support varargs.
16150   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16151     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16152       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16153       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16154         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16155     }
16156   }
16157 
16158   // NVPTX does not support va_arg expression.
16159   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16160       Context.getTargetInfo().getTriple().isNVPTX())
16161     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16162 
16163   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16164   // as Microsoft ABI on an actual Microsoft platform, where
16165   // __builtin_ms_va_list and __builtin_va_list are the same.)
16166   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16167       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16168     QualType MSVaListType = Context.getBuiltinMSVaListType();
16169     if (Context.hasSameType(MSVaListType, E->getType())) {
16170       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16171         return ExprError();
16172       IsMS = true;
16173     }
16174   }
16175 
16176   // Get the va_list type
16177   QualType VaListType = Context.getBuiltinVaListType();
16178   if (!IsMS) {
16179     if (VaListType->isArrayType()) {
16180       // Deal with implicit array decay; for example, on x86-64,
16181       // va_list is an array, but it's supposed to decay to
16182       // a pointer for va_arg.
16183       VaListType = Context.getArrayDecayedType(VaListType);
16184       // Make sure the input expression also decays appropriately.
16185       ExprResult Result = UsualUnaryConversions(E);
16186       if (Result.isInvalid())
16187         return ExprError();
16188       E = Result.get();
16189     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16190       // If va_list is a record type and we are compiling in C++ mode,
16191       // check the argument using reference binding.
16192       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16193           Context, Context.getLValueReferenceType(VaListType), false);
16194       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16195       if (Init.isInvalid())
16196         return ExprError();
16197       E = Init.getAs<Expr>();
16198     } else {
16199       // Otherwise, the va_list argument must be an l-value because
16200       // it is modified by va_arg.
16201       if (!E->isTypeDependent() &&
16202           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16203         return ExprError();
16204     }
16205   }
16206 
16207   if (!IsMS && !E->isTypeDependent() &&
16208       !Context.hasSameType(VaListType, E->getType()))
16209     return ExprError(
16210         Diag(E->getBeginLoc(),
16211              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16212         << OrigExpr->getType() << E->getSourceRange());
16213 
16214   if (!TInfo->getType()->isDependentType()) {
16215     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16216                             diag::err_second_parameter_to_va_arg_incomplete,
16217                             TInfo->getTypeLoc()))
16218       return ExprError();
16219 
16220     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16221                                TInfo->getType(),
16222                                diag::err_second_parameter_to_va_arg_abstract,
16223                                TInfo->getTypeLoc()))
16224       return ExprError();
16225 
16226     if (!TInfo->getType().isPODType(Context)) {
16227       Diag(TInfo->getTypeLoc().getBeginLoc(),
16228            TInfo->getType()->isObjCLifetimeType()
16229              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16230              : diag::warn_second_parameter_to_va_arg_not_pod)
16231         << TInfo->getType()
16232         << TInfo->getTypeLoc().getSourceRange();
16233     }
16234 
16235     // Check for va_arg where arguments of the given type will be promoted
16236     // (i.e. this va_arg is guaranteed to have undefined behavior).
16237     QualType PromoteType;
16238     if (TInfo->getType()->isPromotableIntegerType()) {
16239       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16240       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16241       // and C2x 7.16.1.1p2 says, in part:
16242       //   If type is not compatible with the type of the actual next argument
16243       //   (as promoted according to the default argument promotions), the
16244       //   behavior is undefined, except for the following cases:
16245       //     - both types are pointers to qualified or unqualified versions of
16246       //       compatible types;
16247       //     - one type is a signed integer type, the other type is the
16248       //       corresponding unsigned integer type, and the value is
16249       //       representable in both types;
16250       //     - one type is pointer to qualified or unqualified void and the
16251       //       other is a pointer to a qualified or unqualified character type.
16252       // Given that type compatibility is the primary requirement (ignoring
16253       // qualifications), you would think we could call typesAreCompatible()
16254       // directly to test this. However, in C++, that checks for *same type*,
16255       // which causes false positives when passing an enumeration type to
16256       // va_arg. Instead, get the underlying type of the enumeration and pass
16257       // that.
16258       QualType UnderlyingType = TInfo->getType();
16259       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16260         UnderlyingType = ET->getDecl()->getIntegerType();
16261       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16262                                      /*CompareUnqualified*/ true))
16263         PromoteType = QualType();
16264 
16265       // If the types are still not compatible, we need to test whether the
16266       // promoted type and the underlying type are the same except for
16267       // signedness. Ask the AST for the correctly corresponding type and see
16268       // if that's compatible.
16269       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16270           PromoteType->isUnsignedIntegerType() !=
16271               UnderlyingType->isUnsignedIntegerType()) {
16272         UnderlyingType =
16273             UnderlyingType->isUnsignedIntegerType()
16274                 ? Context.getCorrespondingSignedType(UnderlyingType)
16275                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16276         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16277                                        /*CompareUnqualified*/ true))
16278           PromoteType = QualType();
16279       }
16280     }
16281     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16282       PromoteType = Context.DoubleTy;
16283     if (!PromoteType.isNull())
16284       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16285                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16286                           << TInfo->getType()
16287                           << PromoteType
16288                           << TInfo->getTypeLoc().getSourceRange());
16289   }
16290 
16291   QualType T = TInfo->getType().getNonLValueExprType(Context);
16292   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16293 }
16294 
16295 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16296   // The type of __null will be int or long, depending on the size of
16297   // pointers on the target.
16298   QualType Ty;
16299   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16300   if (pw == Context.getTargetInfo().getIntWidth())
16301     Ty = Context.IntTy;
16302   else if (pw == Context.getTargetInfo().getLongWidth())
16303     Ty = Context.LongTy;
16304   else if (pw == Context.getTargetInfo().getLongLongWidth())
16305     Ty = Context.LongLongTy;
16306   else {
16307     llvm_unreachable("I don't know size of pointer!");
16308   }
16309 
16310   return new (Context) GNUNullExpr(Ty, TokenLoc);
16311 }
16312 
16313 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16314                                     SourceLocation BuiltinLoc,
16315                                     SourceLocation RPLoc) {
16316   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
16317 }
16318 
16319 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16320                                     SourceLocation BuiltinLoc,
16321                                     SourceLocation RPLoc,
16322                                     DeclContext *ParentContext) {
16323   return new (Context)
16324       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
16325 }
16326 
16327 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16328                                         bool Diagnose) {
16329   if (!getLangOpts().ObjC)
16330     return false;
16331 
16332   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16333   if (!PT)
16334     return false;
16335   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16336 
16337   // Ignore any parens, implicit casts (should only be
16338   // array-to-pointer decays), and not-so-opaque values.  The last is
16339   // important for making this trigger for property assignments.
16340   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16341   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16342     if (OV->getSourceExpr())
16343       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16344 
16345   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16346     if (!PT->isObjCIdType() &&
16347         !(ID && ID->getIdentifier()->isStr("NSString")))
16348       return false;
16349     if (!SL->isAscii())
16350       return false;
16351 
16352     if (Diagnose) {
16353       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16354           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16355       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16356     }
16357     return true;
16358   }
16359 
16360   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16361       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16362       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16363       !SrcExpr->isNullPointerConstant(
16364           getASTContext(), Expr::NPC_NeverValueDependent)) {
16365     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16366       return false;
16367     if (Diagnose) {
16368       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16369           << /*number*/1
16370           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16371       Expr *NumLit =
16372           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16373       if (NumLit)
16374         Exp = NumLit;
16375     }
16376     return true;
16377   }
16378 
16379   return false;
16380 }
16381 
16382 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16383                                               const Expr *SrcExpr) {
16384   if (!DstType->isFunctionPointerType() ||
16385       !SrcExpr->getType()->isFunctionType())
16386     return false;
16387 
16388   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16389   if (!DRE)
16390     return false;
16391 
16392   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16393   if (!FD)
16394     return false;
16395 
16396   return !S.checkAddressOfFunctionIsAvailable(FD,
16397                                               /*Complain=*/true,
16398                                               SrcExpr->getBeginLoc());
16399 }
16400 
16401 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16402                                     SourceLocation Loc,
16403                                     QualType DstType, QualType SrcType,
16404                                     Expr *SrcExpr, AssignmentAction Action,
16405                                     bool *Complained) {
16406   if (Complained)
16407     *Complained = false;
16408 
16409   // Decode the result (notice that AST's are still created for extensions).
16410   bool CheckInferredResultType = false;
16411   bool isInvalid = false;
16412   unsigned DiagKind = 0;
16413   ConversionFixItGenerator ConvHints;
16414   bool MayHaveConvFixit = false;
16415   bool MayHaveFunctionDiff = false;
16416   const ObjCInterfaceDecl *IFace = nullptr;
16417   const ObjCProtocolDecl *PDecl = nullptr;
16418 
16419   switch (ConvTy) {
16420   case Compatible:
16421       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16422       return false;
16423 
16424   case PointerToInt:
16425     if (getLangOpts().CPlusPlus) {
16426       DiagKind = diag::err_typecheck_convert_pointer_int;
16427       isInvalid = true;
16428     } else {
16429       DiagKind = diag::ext_typecheck_convert_pointer_int;
16430     }
16431     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16432     MayHaveConvFixit = true;
16433     break;
16434   case IntToPointer:
16435     if (getLangOpts().CPlusPlus) {
16436       DiagKind = diag::err_typecheck_convert_int_pointer;
16437       isInvalid = true;
16438     } else {
16439       DiagKind = diag::ext_typecheck_convert_int_pointer;
16440     }
16441     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16442     MayHaveConvFixit = true;
16443     break;
16444   case IncompatibleFunctionPointer:
16445     if (getLangOpts().CPlusPlus) {
16446       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16447       isInvalid = true;
16448     } else {
16449       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16450     }
16451     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16452     MayHaveConvFixit = true;
16453     break;
16454   case IncompatiblePointer:
16455     if (Action == AA_Passing_CFAudited) {
16456       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16457     } else if (getLangOpts().CPlusPlus) {
16458       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16459       isInvalid = true;
16460     } else {
16461       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16462     }
16463     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16464       SrcType->isObjCObjectPointerType();
16465     if (!CheckInferredResultType) {
16466       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16467     } else if (CheckInferredResultType) {
16468       SrcType = SrcType.getUnqualifiedType();
16469       DstType = DstType.getUnqualifiedType();
16470     }
16471     MayHaveConvFixit = true;
16472     break;
16473   case IncompatiblePointerSign:
16474     if (getLangOpts().CPlusPlus) {
16475       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16476       isInvalid = true;
16477     } else {
16478       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16479     }
16480     break;
16481   case FunctionVoidPointer:
16482     if (getLangOpts().CPlusPlus) {
16483       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16484       isInvalid = true;
16485     } else {
16486       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16487     }
16488     break;
16489   case IncompatiblePointerDiscardsQualifiers: {
16490     // Perform array-to-pointer decay if necessary.
16491     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16492 
16493     isInvalid = true;
16494 
16495     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16496     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16497     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16498       DiagKind = diag::err_typecheck_incompatible_address_space;
16499       break;
16500 
16501     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16502       DiagKind = diag::err_typecheck_incompatible_ownership;
16503       break;
16504     }
16505 
16506     llvm_unreachable("unknown error case for discarding qualifiers!");
16507     // fallthrough
16508   }
16509   case CompatiblePointerDiscardsQualifiers:
16510     // If the qualifiers lost were because we were applying the
16511     // (deprecated) C++ conversion from a string literal to a char*
16512     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16513     // Ideally, this check would be performed in
16514     // checkPointerTypesForAssignment. However, that would require a
16515     // bit of refactoring (so that the second argument is an
16516     // expression, rather than a type), which should be done as part
16517     // of a larger effort to fix checkPointerTypesForAssignment for
16518     // C++ semantics.
16519     if (getLangOpts().CPlusPlus &&
16520         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16521       return false;
16522     if (getLangOpts().CPlusPlus) {
16523       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16524       isInvalid = true;
16525     } else {
16526       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16527     }
16528 
16529     break;
16530   case IncompatibleNestedPointerQualifiers:
16531     if (getLangOpts().CPlusPlus) {
16532       isInvalid = true;
16533       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16534     } else {
16535       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16536     }
16537     break;
16538   case IncompatibleNestedPointerAddressSpaceMismatch:
16539     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16540     isInvalid = true;
16541     break;
16542   case IntToBlockPointer:
16543     DiagKind = diag::err_int_to_block_pointer;
16544     isInvalid = true;
16545     break;
16546   case IncompatibleBlockPointer:
16547     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16548     isInvalid = true;
16549     break;
16550   case IncompatibleObjCQualifiedId: {
16551     if (SrcType->isObjCQualifiedIdType()) {
16552       const ObjCObjectPointerType *srcOPT =
16553                 SrcType->castAs<ObjCObjectPointerType>();
16554       for (auto *srcProto : srcOPT->quals()) {
16555         PDecl = srcProto;
16556         break;
16557       }
16558       if (const ObjCInterfaceType *IFaceT =
16559             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16560         IFace = IFaceT->getDecl();
16561     }
16562     else if (DstType->isObjCQualifiedIdType()) {
16563       const ObjCObjectPointerType *dstOPT =
16564         DstType->castAs<ObjCObjectPointerType>();
16565       for (auto *dstProto : dstOPT->quals()) {
16566         PDecl = dstProto;
16567         break;
16568       }
16569       if (const ObjCInterfaceType *IFaceT =
16570             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16571         IFace = IFaceT->getDecl();
16572     }
16573     if (getLangOpts().CPlusPlus) {
16574       DiagKind = diag::err_incompatible_qualified_id;
16575       isInvalid = true;
16576     } else {
16577       DiagKind = diag::warn_incompatible_qualified_id;
16578     }
16579     break;
16580   }
16581   case IncompatibleVectors:
16582     if (getLangOpts().CPlusPlus) {
16583       DiagKind = diag::err_incompatible_vectors;
16584       isInvalid = true;
16585     } else {
16586       DiagKind = diag::warn_incompatible_vectors;
16587     }
16588     break;
16589   case IncompatibleObjCWeakRef:
16590     DiagKind = diag::err_arc_weak_unavailable_assign;
16591     isInvalid = true;
16592     break;
16593   case Incompatible:
16594     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16595       if (Complained)
16596         *Complained = true;
16597       return true;
16598     }
16599 
16600     DiagKind = diag::err_typecheck_convert_incompatible;
16601     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16602     MayHaveConvFixit = true;
16603     isInvalid = true;
16604     MayHaveFunctionDiff = true;
16605     break;
16606   }
16607 
16608   QualType FirstType, SecondType;
16609   switch (Action) {
16610   case AA_Assigning:
16611   case AA_Initializing:
16612     // The destination type comes first.
16613     FirstType = DstType;
16614     SecondType = SrcType;
16615     break;
16616 
16617   case AA_Returning:
16618   case AA_Passing:
16619   case AA_Passing_CFAudited:
16620   case AA_Converting:
16621   case AA_Sending:
16622   case AA_Casting:
16623     // The source type comes first.
16624     FirstType = SrcType;
16625     SecondType = DstType;
16626     break;
16627   }
16628 
16629   PartialDiagnostic FDiag = PDiag(DiagKind);
16630   if (Action == AA_Passing_CFAudited)
16631     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16632   else
16633     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16634 
16635   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16636       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16637     auto isPlainChar = [](const clang::Type *Type) {
16638       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16639              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16640     };
16641     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16642               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16643   }
16644 
16645   // If we can fix the conversion, suggest the FixIts.
16646   if (!ConvHints.isNull()) {
16647     for (FixItHint &H : ConvHints.Hints)
16648       FDiag << H;
16649   }
16650 
16651   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16652 
16653   if (MayHaveFunctionDiff)
16654     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16655 
16656   Diag(Loc, FDiag);
16657   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16658        DiagKind == diag::err_incompatible_qualified_id) &&
16659       PDecl && IFace && !IFace->hasDefinition())
16660     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16661         << IFace << PDecl;
16662 
16663   if (SecondType == Context.OverloadTy)
16664     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16665                               FirstType, /*TakingAddress=*/true);
16666 
16667   if (CheckInferredResultType)
16668     EmitRelatedResultTypeNote(SrcExpr);
16669 
16670   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16671     EmitRelatedResultTypeNoteForReturn(DstType);
16672 
16673   if (Complained)
16674     *Complained = true;
16675   return isInvalid;
16676 }
16677 
16678 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16679                                                  llvm::APSInt *Result,
16680                                                  AllowFoldKind CanFold) {
16681   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16682   public:
16683     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16684                                              QualType T) override {
16685       return S.Diag(Loc, diag::err_ice_not_integral)
16686              << T << S.LangOpts.CPlusPlus;
16687     }
16688     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16689       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16690     }
16691   } Diagnoser;
16692 
16693   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16694 }
16695 
16696 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16697                                                  llvm::APSInt *Result,
16698                                                  unsigned DiagID,
16699                                                  AllowFoldKind CanFold) {
16700   class IDDiagnoser : public VerifyICEDiagnoser {
16701     unsigned DiagID;
16702 
16703   public:
16704     IDDiagnoser(unsigned DiagID)
16705       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16706 
16707     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16708       return S.Diag(Loc, DiagID);
16709     }
16710   } Diagnoser(DiagID);
16711 
16712   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16713 }
16714 
16715 Sema::SemaDiagnosticBuilder
16716 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16717                                              QualType T) {
16718   return diagnoseNotICE(S, Loc);
16719 }
16720 
16721 Sema::SemaDiagnosticBuilder
16722 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16723   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16724 }
16725 
16726 ExprResult
16727 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16728                                       VerifyICEDiagnoser &Diagnoser,
16729                                       AllowFoldKind CanFold) {
16730   SourceLocation DiagLoc = E->getBeginLoc();
16731 
16732   if (getLangOpts().CPlusPlus11) {
16733     // C++11 [expr.const]p5:
16734     //   If an expression of literal class type is used in a context where an
16735     //   integral constant expression is required, then that class type shall
16736     //   have a single non-explicit conversion function to an integral or
16737     //   unscoped enumeration type
16738     ExprResult Converted;
16739     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16740       VerifyICEDiagnoser &BaseDiagnoser;
16741     public:
16742       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16743           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16744                                 BaseDiagnoser.Suppress, true),
16745             BaseDiagnoser(BaseDiagnoser) {}
16746 
16747       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16748                                            QualType T) override {
16749         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16750       }
16751 
16752       SemaDiagnosticBuilder diagnoseIncomplete(
16753           Sema &S, SourceLocation Loc, QualType T) override {
16754         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16755       }
16756 
16757       SemaDiagnosticBuilder diagnoseExplicitConv(
16758           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16759         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16760       }
16761 
16762       SemaDiagnosticBuilder noteExplicitConv(
16763           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16764         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16765                  << ConvTy->isEnumeralType() << ConvTy;
16766       }
16767 
16768       SemaDiagnosticBuilder diagnoseAmbiguous(
16769           Sema &S, SourceLocation Loc, QualType T) override {
16770         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16771       }
16772 
16773       SemaDiagnosticBuilder noteAmbiguous(
16774           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16775         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16776                  << ConvTy->isEnumeralType() << ConvTy;
16777       }
16778 
16779       SemaDiagnosticBuilder diagnoseConversion(
16780           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16781         llvm_unreachable("conversion functions are permitted");
16782       }
16783     } ConvertDiagnoser(Diagnoser);
16784 
16785     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16786                                                     ConvertDiagnoser);
16787     if (Converted.isInvalid())
16788       return Converted;
16789     E = Converted.get();
16790     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16791       return ExprError();
16792   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16793     // An ICE must be of integral or unscoped enumeration type.
16794     if (!Diagnoser.Suppress)
16795       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16796           << E->getSourceRange();
16797     return ExprError();
16798   }
16799 
16800   ExprResult RValueExpr = DefaultLvalueConversion(E);
16801   if (RValueExpr.isInvalid())
16802     return ExprError();
16803 
16804   E = RValueExpr.get();
16805 
16806   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16807   // in the non-ICE case.
16808   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16809     if (Result)
16810       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16811     if (!isa<ConstantExpr>(E))
16812       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16813                  : ConstantExpr::Create(Context, E);
16814     return E;
16815   }
16816 
16817   Expr::EvalResult EvalResult;
16818   SmallVector<PartialDiagnosticAt, 8> Notes;
16819   EvalResult.Diag = &Notes;
16820 
16821   // Try to evaluate the expression, and produce diagnostics explaining why it's
16822   // not a constant expression as a side-effect.
16823   bool Folded =
16824       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16825       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16826 
16827   if (!isa<ConstantExpr>(E))
16828     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16829 
16830   // In C++11, we can rely on diagnostics being produced for any expression
16831   // which is not a constant expression. If no diagnostics were produced, then
16832   // this is a constant expression.
16833   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16834     if (Result)
16835       *Result = EvalResult.Val.getInt();
16836     return E;
16837   }
16838 
16839   // If our only note is the usual "invalid subexpression" note, just point
16840   // the caret at its location rather than producing an essentially
16841   // redundant note.
16842   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16843         diag::note_invalid_subexpr_in_const_expr) {
16844     DiagLoc = Notes[0].first;
16845     Notes.clear();
16846   }
16847 
16848   if (!Folded || !CanFold) {
16849     if (!Diagnoser.Suppress) {
16850       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16851       for (const PartialDiagnosticAt &Note : Notes)
16852         Diag(Note.first, Note.second);
16853     }
16854 
16855     return ExprError();
16856   }
16857 
16858   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16859   for (const PartialDiagnosticAt &Note : Notes)
16860     Diag(Note.first, Note.second);
16861 
16862   if (Result)
16863     *Result = EvalResult.Val.getInt();
16864   return E;
16865 }
16866 
16867 namespace {
16868   // Handle the case where we conclude a expression which we speculatively
16869   // considered to be unevaluated is actually evaluated.
16870   class TransformToPE : public TreeTransform<TransformToPE> {
16871     typedef TreeTransform<TransformToPE> BaseTransform;
16872 
16873   public:
16874     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16875 
16876     // Make sure we redo semantic analysis
16877     bool AlwaysRebuild() { return true; }
16878     bool ReplacingOriginal() { return true; }
16879 
16880     // We need to special-case DeclRefExprs referring to FieldDecls which
16881     // are not part of a member pointer formation; normal TreeTransforming
16882     // doesn't catch this case because of the way we represent them in the AST.
16883     // FIXME: This is a bit ugly; is it really the best way to handle this
16884     // case?
16885     //
16886     // Error on DeclRefExprs referring to FieldDecls.
16887     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16888       if (isa<FieldDecl>(E->getDecl()) &&
16889           !SemaRef.isUnevaluatedContext())
16890         return SemaRef.Diag(E->getLocation(),
16891                             diag::err_invalid_non_static_member_use)
16892             << E->getDecl() << E->getSourceRange();
16893 
16894       return BaseTransform::TransformDeclRefExpr(E);
16895     }
16896 
16897     // Exception: filter out member pointer formation
16898     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16899       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16900         return E;
16901 
16902       return BaseTransform::TransformUnaryOperator(E);
16903     }
16904 
16905     // The body of a lambda-expression is in a separate expression evaluation
16906     // context so never needs to be transformed.
16907     // FIXME: Ideally we wouldn't transform the closure type either, and would
16908     // just recreate the capture expressions and lambda expression.
16909     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16910       return SkipLambdaBody(E, Body);
16911     }
16912   };
16913 }
16914 
16915 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16916   assert(isUnevaluatedContext() &&
16917          "Should only transform unevaluated expressions");
16918   ExprEvalContexts.back().Context =
16919       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16920   if (isUnevaluatedContext())
16921     return E;
16922   return TransformToPE(*this).TransformExpr(E);
16923 }
16924 
16925 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
16926   assert(isUnevaluatedContext() &&
16927          "Should only transform unevaluated expressions");
16928   ExprEvalContexts.back().Context =
16929       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
16930   if (isUnevaluatedContext())
16931     return TInfo;
16932   return TransformToPE(*this).TransformType(TInfo);
16933 }
16934 
16935 void
16936 Sema::PushExpressionEvaluationContext(
16937     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16938     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16939   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16940                                 LambdaContextDecl, ExprContext);
16941 
16942   // Discarded statements and immediate contexts nested in other
16943   // discarded statements or immediate context are themselves
16944   // a discarded statement or an immediate context, respectively.
16945   ExprEvalContexts.back().InDiscardedStatement =
16946       ExprEvalContexts[ExprEvalContexts.size() - 2]
16947           .isDiscardedStatementContext();
16948   ExprEvalContexts.back().InImmediateFunctionContext =
16949       ExprEvalContexts[ExprEvalContexts.size() - 2]
16950           .isImmediateFunctionContext();
16951 
16952   Cleanup.reset();
16953   if (!MaybeODRUseExprs.empty())
16954     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16955 }
16956 
16957 void
16958 Sema::PushExpressionEvaluationContext(
16959     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16960     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16961   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16962   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16963 }
16964 
16965 namespace {
16966 
16967 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16968   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16969   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16970     if (E->getOpcode() == UO_Deref)
16971       return CheckPossibleDeref(S, E->getSubExpr());
16972   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16973     return CheckPossibleDeref(S, E->getBase());
16974   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16975     return CheckPossibleDeref(S, E->getBase());
16976   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16977     QualType Inner;
16978     QualType Ty = E->getType();
16979     if (const auto *Ptr = Ty->getAs<PointerType>())
16980       Inner = Ptr->getPointeeType();
16981     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16982       Inner = Arr->getElementType();
16983     else
16984       return nullptr;
16985 
16986     if (Inner->hasAttr(attr::NoDeref))
16987       return E;
16988   }
16989   return nullptr;
16990 }
16991 
16992 } // namespace
16993 
16994 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16995   for (const Expr *E : Rec.PossibleDerefs) {
16996     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16997     if (DeclRef) {
16998       const ValueDecl *Decl = DeclRef->getDecl();
16999       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17000           << Decl->getName() << E->getSourceRange();
17001       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17002     } else {
17003       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17004           << E->getSourceRange();
17005     }
17006   }
17007   Rec.PossibleDerefs.clear();
17008 }
17009 
17010 /// Check whether E, which is either a discarded-value expression or an
17011 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17012 /// and if so, remove it from the list of volatile-qualified assignments that
17013 /// we are going to warn are deprecated.
17014 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17015   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17016     return;
17017 
17018   // Note: ignoring parens here is not justified by the standard rules, but
17019   // ignoring parentheses seems like a more reasonable approach, and this only
17020   // drives a deprecation warning so doesn't affect conformance.
17021   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17022     if (BO->getOpcode() == BO_Assign) {
17023       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17024       llvm::erase_value(LHSs, BO->getLHS());
17025     }
17026   }
17027 }
17028 
17029 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17030   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17031       !Decl->isConsteval() || isConstantEvaluated() ||
17032       RebuildingImmediateInvocation || isImmediateFunctionContext())
17033     return E;
17034 
17035   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17036   /// It's OK if this fails; we'll also remove this in
17037   /// HandleImmediateInvocations, but catching it here allows us to avoid
17038   /// walking the AST looking for it in simple cases.
17039   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17040     if (auto *DeclRef =
17041             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17042       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17043 
17044   E = MaybeCreateExprWithCleanups(E);
17045 
17046   ConstantExpr *Res = ConstantExpr::Create(
17047       getASTContext(), E.get(),
17048       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17049                                    getASTContext()),
17050       /*IsImmediateInvocation*/ true);
17051   /// Value-dependent constant expressions should not be immediately
17052   /// evaluated until they are instantiated.
17053   if (!Res->isValueDependent())
17054     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17055   return Res;
17056 }
17057 
17058 static void EvaluateAndDiagnoseImmediateInvocation(
17059     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17060   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17061   Expr::EvalResult Eval;
17062   Eval.Diag = &Notes;
17063   ConstantExpr *CE = Candidate.getPointer();
17064   bool Result = CE->EvaluateAsConstantExpr(
17065       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17066   if (!Result || !Notes.empty()) {
17067     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17068     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17069       InnerExpr = FunctionalCast->getSubExpr();
17070     FunctionDecl *FD = nullptr;
17071     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17072       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17073     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17074       FD = Call->getConstructor();
17075     else
17076       llvm_unreachable("unhandled decl kind");
17077     assert(FD->isConsteval());
17078     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17079     for (auto &Note : Notes)
17080       SemaRef.Diag(Note.first, Note.second);
17081     return;
17082   }
17083   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17084 }
17085 
17086 static void RemoveNestedImmediateInvocation(
17087     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17088     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17089   struct ComplexRemove : TreeTransform<ComplexRemove> {
17090     using Base = TreeTransform<ComplexRemove>;
17091     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17092     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17093     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17094         CurrentII;
17095     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17096                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17097                   SmallVector<Sema::ImmediateInvocationCandidate,
17098                               4>::reverse_iterator Current)
17099         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17100     void RemoveImmediateInvocation(ConstantExpr* E) {
17101       auto It = std::find_if(CurrentII, IISet.rend(),
17102                              [E](Sema::ImmediateInvocationCandidate Elem) {
17103                                return Elem.getPointer() == E;
17104                              });
17105       assert(It != IISet.rend() &&
17106              "ConstantExpr marked IsImmediateInvocation should "
17107              "be present");
17108       It->setInt(1); // Mark as deleted
17109     }
17110     ExprResult TransformConstantExpr(ConstantExpr *E) {
17111       if (!E->isImmediateInvocation())
17112         return Base::TransformConstantExpr(E);
17113       RemoveImmediateInvocation(E);
17114       return Base::TransformExpr(E->getSubExpr());
17115     }
17116     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17117     /// we need to remove its DeclRefExpr from the DRSet.
17118     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17119       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17120       return Base::TransformCXXOperatorCallExpr(E);
17121     }
17122     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17123     /// here.
17124     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17125       if (!Init)
17126         return Init;
17127       /// ConstantExpr are the first layer of implicit node to be removed so if
17128       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17129       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17130         if (CE->isImmediateInvocation())
17131           RemoveImmediateInvocation(CE);
17132       return Base::TransformInitializer(Init, NotCopyInit);
17133     }
17134     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17135       DRSet.erase(E);
17136       return E;
17137     }
17138     bool AlwaysRebuild() { return false; }
17139     bool ReplacingOriginal() { return true; }
17140     bool AllowSkippingCXXConstructExpr() {
17141       bool Res = AllowSkippingFirstCXXConstructExpr;
17142       AllowSkippingFirstCXXConstructExpr = true;
17143       return Res;
17144     }
17145     bool AllowSkippingFirstCXXConstructExpr = true;
17146   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17147                 Rec.ImmediateInvocationCandidates, It);
17148 
17149   /// CXXConstructExpr with a single argument are getting skipped by
17150   /// TreeTransform in some situtation because they could be implicit. This
17151   /// can only occur for the top-level CXXConstructExpr because it is used
17152   /// nowhere in the expression being transformed therefore will not be rebuilt.
17153   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17154   /// skipping the first CXXConstructExpr.
17155   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17156     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17157 
17158   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17159   assert(Res.isUsable());
17160   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17161   It->getPointer()->setSubExpr(Res.get());
17162 }
17163 
17164 static void
17165 HandleImmediateInvocations(Sema &SemaRef,
17166                            Sema::ExpressionEvaluationContextRecord &Rec) {
17167   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17168        Rec.ReferenceToConsteval.size() == 0) ||
17169       SemaRef.RebuildingImmediateInvocation)
17170     return;
17171 
17172   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17173   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17174   /// need to remove ReferenceToConsteval in the immediate invocation.
17175   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17176 
17177     /// Prevent sema calls during the tree transform from adding pointers that
17178     /// are already in the sets.
17179     llvm::SaveAndRestore<bool> DisableIITracking(
17180         SemaRef.RebuildingImmediateInvocation, true);
17181 
17182     /// Prevent diagnostic during tree transfrom as they are duplicates
17183     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17184 
17185     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17186          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17187       if (!It->getInt())
17188         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17189   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17190              Rec.ReferenceToConsteval.size()) {
17191     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17192       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17193       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17194       bool VisitDeclRefExpr(DeclRefExpr *E) {
17195         DRSet.erase(E);
17196         return DRSet.size();
17197       }
17198     } Visitor(Rec.ReferenceToConsteval);
17199     Visitor.TraverseStmt(
17200         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17201   }
17202   for (auto CE : Rec.ImmediateInvocationCandidates)
17203     if (!CE.getInt())
17204       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17205   for (auto DR : Rec.ReferenceToConsteval) {
17206     auto *FD = cast<FunctionDecl>(DR->getDecl());
17207     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17208         << FD;
17209     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17210   }
17211 }
17212 
17213 void Sema::PopExpressionEvaluationContext() {
17214   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17215   unsigned NumTypos = Rec.NumTypos;
17216 
17217   if (!Rec.Lambdas.empty()) {
17218     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17219     if (!getLangOpts().CPlusPlus20 &&
17220         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17221          Rec.isUnevaluated() ||
17222          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17223       unsigned D;
17224       if (Rec.isUnevaluated()) {
17225         // C++11 [expr.prim.lambda]p2:
17226         //   A lambda-expression shall not appear in an unevaluated operand
17227         //   (Clause 5).
17228         D = diag::err_lambda_unevaluated_operand;
17229       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17230         // C++1y [expr.const]p2:
17231         //   A conditional-expression e is a core constant expression unless the
17232         //   evaluation of e, following the rules of the abstract machine, would
17233         //   evaluate [...] a lambda-expression.
17234         D = diag::err_lambda_in_constant_expression;
17235       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17236         // C++17 [expr.prim.lamda]p2:
17237         // A lambda-expression shall not appear [...] in a template-argument.
17238         D = diag::err_lambda_in_invalid_context;
17239       } else
17240         llvm_unreachable("Couldn't infer lambda error message.");
17241 
17242       for (const auto *L : Rec.Lambdas)
17243         Diag(L->getBeginLoc(), D);
17244     }
17245   }
17246 
17247   WarnOnPendingNoDerefs(Rec);
17248   HandleImmediateInvocations(*this, Rec);
17249 
17250   // Warn on any volatile-qualified simple-assignments that are not discarded-
17251   // value expressions nor unevaluated operands (those cases get removed from
17252   // this list by CheckUnusedVolatileAssignment).
17253   for (auto *BO : Rec.VolatileAssignmentLHSs)
17254     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17255         << BO->getType();
17256 
17257   // When are coming out of an unevaluated context, clear out any
17258   // temporaries that we may have created as part of the evaluation of
17259   // the expression in that context: they aren't relevant because they
17260   // will never be constructed.
17261   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17262     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17263                              ExprCleanupObjects.end());
17264     Cleanup = Rec.ParentCleanup;
17265     CleanupVarDeclMarking();
17266     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17267   // Otherwise, merge the contexts together.
17268   } else {
17269     Cleanup.mergeFrom(Rec.ParentCleanup);
17270     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17271                             Rec.SavedMaybeODRUseExprs.end());
17272   }
17273 
17274   // Pop the current expression evaluation context off the stack.
17275   ExprEvalContexts.pop_back();
17276 
17277   // The global expression evaluation context record is never popped.
17278   ExprEvalContexts.back().NumTypos += NumTypos;
17279 }
17280 
17281 void Sema::DiscardCleanupsInEvaluationContext() {
17282   ExprCleanupObjects.erase(
17283          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17284          ExprCleanupObjects.end());
17285   Cleanup.reset();
17286   MaybeODRUseExprs.clear();
17287 }
17288 
17289 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17290   ExprResult Result = CheckPlaceholderExpr(E);
17291   if (Result.isInvalid())
17292     return ExprError();
17293   E = Result.get();
17294   if (!E->getType()->isVariablyModifiedType())
17295     return E;
17296   return TransformToPotentiallyEvaluated(E);
17297 }
17298 
17299 /// Are we in a context that is potentially constant evaluated per C++20
17300 /// [expr.const]p12?
17301 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17302   /// C++2a [expr.const]p12:
17303   //   An expression or conversion is potentially constant evaluated if it is
17304   switch (SemaRef.ExprEvalContexts.back().Context) {
17305     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17306     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17307 
17308       // -- a manifestly constant-evaluated expression,
17309     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17310     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17311     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17312       // -- a potentially-evaluated expression,
17313     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17314       // -- an immediate subexpression of a braced-init-list,
17315 
17316       // -- [FIXME] an expression of the form & cast-expression that occurs
17317       //    within a templated entity
17318       // -- a subexpression of one of the above that is not a subexpression of
17319       // a nested unevaluated operand.
17320       return true;
17321 
17322     case Sema::ExpressionEvaluationContext::Unevaluated:
17323     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17324       // Expressions in this context are never evaluated.
17325       return false;
17326   }
17327   llvm_unreachable("Invalid context");
17328 }
17329 
17330 /// Return true if this function has a calling convention that requires mangling
17331 /// in the size of the parameter pack.
17332 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17333   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17334   // we don't need parameter type sizes.
17335   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17336   if (!TT.isOSWindows() || !TT.isX86())
17337     return false;
17338 
17339   // If this is C++ and this isn't an extern "C" function, parameters do not
17340   // need to be complete. In this case, C++ mangling will apply, which doesn't
17341   // use the size of the parameters.
17342   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17343     return false;
17344 
17345   // Stdcall, fastcall, and vectorcall need this special treatment.
17346   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17347   switch (CC) {
17348   case CC_X86StdCall:
17349   case CC_X86FastCall:
17350   case CC_X86VectorCall:
17351     return true;
17352   default:
17353     break;
17354   }
17355   return false;
17356 }
17357 
17358 /// Require that all of the parameter types of function be complete. Normally,
17359 /// parameter types are only required to be complete when a function is called
17360 /// or defined, but to mangle functions with certain calling conventions, the
17361 /// mangler needs to know the size of the parameter list. In this situation,
17362 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17363 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17364 /// result in a linker error. Clang doesn't implement this behavior, and instead
17365 /// attempts to error at compile time.
17366 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17367                                                   SourceLocation Loc) {
17368   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17369     FunctionDecl *FD;
17370     ParmVarDecl *Param;
17371 
17372   public:
17373     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17374         : FD(FD), Param(Param) {}
17375 
17376     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17377       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17378       StringRef CCName;
17379       switch (CC) {
17380       case CC_X86StdCall:
17381         CCName = "stdcall";
17382         break;
17383       case CC_X86FastCall:
17384         CCName = "fastcall";
17385         break;
17386       case CC_X86VectorCall:
17387         CCName = "vectorcall";
17388         break;
17389       default:
17390         llvm_unreachable("CC does not need mangling");
17391       }
17392 
17393       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17394           << Param->getDeclName() << FD->getDeclName() << CCName;
17395     }
17396   };
17397 
17398   for (ParmVarDecl *Param : FD->parameters()) {
17399     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17400     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17401   }
17402 }
17403 
17404 namespace {
17405 enum class OdrUseContext {
17406   /// Declarations in this context are not odr-used.
17407   None,
17408   /// Declarations in this context are formally odr-used, but this is a
17409   /// dependent context.
17410   Dependent,
17411   /// Declarations in this context are odr-used but not actually used (yet).
17412   FormallyOdrUsed,
17413   /// Declarations in this context are used.
17414   Used
17415 };
17416 }
17417 
17418 /// Are we within a context in which references to resolved functions or to
17419 /// variables result in odr-use?
17420 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17421   OdrUseContext Result;
17422 
17423   switch (SemaRef.ExprEvalContexts.back().Context) {
17424     case Sema::ExpressionEvaluationContext::Unevaluated:
17425     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17426     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17427       return OdrUseContext::None;
17428 
17429     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17430     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17431     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17432       Result = OdrUseContext::Used;
17433       break;
17434 
17435     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17436       Result = OdrUseContext::FormallyOdrUsed;
17437       break;
17438 
17439     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17440       // A default argument formally results in odr-use, but doesn't actually
17441       // result in a use in any real sense until it itself is used.
17442       Result = OdrUseContext::FormallyOdrUsed;
17443       break;
17444   }
17445 
17446   if (SemaRef.CurContext->isDependentContext())
17447     return OdrUseContext::Dependent;
17448 
17449   return Result;
17450 }
17451 
17452 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17453   if (!Func->isConstexpr())
17454     return false;
17455 
17456   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17457     return true;
17458   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17459   return CCD && CCD->getInheritedConstructor();
17460 }
17461 
17462 /// Mark a function referenced, and check whether it is odr-used
17463 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17464 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17465                                   bool MightBeOdrUse) {
17466   assert(Func && "No function?");
17467 
17468   Func->setReferenced();
17469 
17470   // Recursive functions aren't really used until they're used from some other
17471   // context.
17472   bool IsRecursiveCall = CurContext == Func;
17473 
17474   // C++11 [basic.def.odr]p3:
17475   //   A function whose name appears as a potentially-evaluated expression is
17476   //   odr-used if it is the unique lookup result or the selected member of a
17477   //   set of overloaded functions [...].
17478   //
17479   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17480   // can just check that here.
17481   OdrUseContext OdrUse =
17482       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17483   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17484     OdrUse = OdrUseContext::FormallyOdrUsed;
17485 
17486   // Trivial default constructors and destructors are never actually used.
17487   // FIXME: What about other special members?
17488   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17489       OdrUse == OdrUseContext::Used) {
17490     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17491       if (Constructor->isDefaultConstructor())
17492         OdrUse = OdrUseContext::FormallyOdrUsed;
17493     if (isa<CXXDestructorDecl>(Func))
17494       OdrUse = OdrUseContext::FormallyOdrUsed;
17495   }
17496 
17497   // C++20 [expr.const]p12:
17498   //   A function [...] is needed for constant evaluation if it is [...] a
17499   //   constexpr function that is named by an expression that is potentially
17500   //   constant evaluated
17501   bool NeededForConstantEvaluation =
17502       isPotentiallyConstantEvaluatedContext(*this) &&
17503       isImplicitlyDefinableConstexprFunction(Func);
17504 
17505   // Determine whether we require a function definition to exist, per
17506   // C++11 [temp.inst]p3:
17507   //   Unless a function template specialization has been explicitly
17508   //   instantiated or explicitly specialized, the function template
17509   //   specialization is implicitly instantiated when the specialization is
17510   //   referenced in a context that requires a function definition to exist.
17511   // C++20 [temp.inst]p7:
17512   //   The existence of a definition of a [...] function is considered to
17513   //   affect the semantics of the program if the [...] function is needed for
17514   //   constant evaluation by an expression
17515   // C++20 [basic.def.odr]p10:
17516   //   Every program shall contain exactly one definition of every non-inline
17517   //   function or variable that is odr-used in that program outside of a
17518   //   discarded statement
17519   // C++20 [special]p1:
17520   //   The implementation will implicitly define [defaulted special members]
17521   //   if they are odr-used or needed for constant evaluation.
17522   //
17523   // Note that we skip the implicit instantiation of templates that are only
17524   // used in unused default arguments or by recursive calls to themselves.
17525   // This is formally non-conforming, but seems reasonable in practice.
17526   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17527                                              NeededForConstantEvaluation);
17528 
17529   // C++14 [temp.expl.spec]p6:
17530   //   If a template [...] is explicitly specialized then that specialization
17531   //   shall be declared before the first use of that specialization that would
17532   //   cause an implicit instantiation to take place, in every translation unit
17533   //   in which such a use occurs
17534   if (NeedDefinition &&
17535       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17536        Func->getMemberSpecializationInfo()))
17537     checkSpecializationVisibility(Loc, Func);
17538 
17539   if (getLangOpts().CUDA)
17540     CheckCUDACall(Loc, Func);
17541 
17542   if (getLangOpts().SYCLIsDevice)
17543     checkSYCLDeviceFunction(Loc, Func);
17544 
17545   // If we need a definition, try to create one.
17546   if (NeedDefinition && !Func->getBody()) {
17547     runWithSufficientStackSpace(Loc, [&] {
17548       if (CXXConstructorDecl *Constructor =
17549               dyn_cast<CXXConstructorDecl>(Func)) {
17550         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17551         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17552           if (Constructor->isDefaultConstructor()) {
17553             if (Constructor->isTrivial() &&
17554                 !Constructor->hasAttr<DLLExportAttr>())
17555               return;
17556             DefineImplicitDefaultConstructor(Loc, Constructor);
17557           } else if (Constructor->isCopyConstructor()) {
17558             DefineImplicitCopyConstructor(Loc, Constructor);
17559           } else if (Constructor->isMoveConstructor()) {
17560             DefineImplicitMoveConstructor(Loc, Constructor);
17561           }
17562         } else if (Constructor->getInheritedConstructor()) {
17563           DefineInheritingConstructor(Loc, Constructor);
17564         }
17565       } else if (CXXDestructorDecl *Destructor =
17566                      dyn_cast<CXXDestructorDecl>(Func)) {
17567         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17568         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17569           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17570             return;
17571           DefineImplicitDestructor(Loc, Destructor);
17572         }
17573         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17574           MarkVTableUsed(Loc, Destructor->getParent());
17575       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17576         if (MethodDecl->isOverloadedOperator() &&
17577             MethodDecl->getOverloadedOperator() == OO_Equal) {
17578           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17579           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17580             if (MethodDecl->isCopyAssignmentOperator())
17581               DefineImplicitCopyAssignment(Loc, MethodDecl);
17582             else if (MethodDecl->isMoveAssignmentOperator())
17583               DefineImplicitMoveAssignment(Loc, MethodDecl);
17584           }
17585         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17586                    MethodDecl->getParent()->isLambda()) {
17587           CXXConversionDecl *Conversion =
17588               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17589           if (Conversion->isLambdaToBlockPointerConversion())
17590             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17591           else
17592             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17593         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17594           MarkVTableUsed(Loc, MethodDecl->getParent());
17595       }
17596 
17597       if (Func->isDefaulted() && !Func->isDeleted()) {
17598         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17599         if (DCK != DefaultedComparisonKind::None)
17600           DefineDefaultedComparison(Loc, Func, DCK);
17601       }
17602 
17603       // Implicit instantiation of function templates and member functions of
17604       // class templates.
17605       if (Func->isImplicitlyInstantiable()) {
17606         TemplateSpecializationKind TSK =
17607             Func->getTemplateSpecializationKindForInstantiation();
17608         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17609         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17610         if (FirstInstantiation) {
17611           PointOfInstantiation = Loc;
17612           if (auto *MSI = Func->getMemberSpecializationInfo())
17613             MSI->setPointOfInstantiation(Loc);
17614             // FIXME: Notify listener.
17615           else
17616             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17617         } else if (TSK != TSK_ImplicitInstantiation) {
17618           // Use the point of use as the point of instantiation, instead of the
17619           // point of explicit instantiation (which we track as the actual point
17620           // of instantiation). This gives better backtraces in diagnostics.
17621           PointOfInstantiation = Loc;
17622         }
17623 
17624         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17625             Func->isConstexpr()) {
17626           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17627               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17628               CodeSynthesisContexts.size())
17629             PendingLocalImplicitInstantiations.push_back(
17630                 std::make_pair(Func, PointOfInstantiation));
17631           else if (Func->isConstexpr())
17632             // Do not defer instantiations of constexpr functions, to avoid the
17633             // expression evaluator needing to call back into Sema if it sees a
17634             // call to such a function.
17635             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17636           else {
17637             Func->setInstantiationIsPending(true);
17638             PendingInstantiations.push_back(
17639                 std::make_pair(Func, PointOfInstantiation));
17640             // Notify the consumer that a function was implicitly instantiated.
17641             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17642           }
17643         }
17644       } else {
17645         // Walk redefinitions, as some of them may be instantiable.
17646         for (auto i : Func->redecls()) {
17647           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17648             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17649         }
17650       }
17651     });
17652   }
17653 
17654   // C++14 [except.spec]p17:
17655   //   An exception-specification is considered to be needed when:
17656   //   - the function is odr-used or, if it appears in an unevaluated operand,
17657   //     would be odr-used if the expression were potentially-evaluated;
17658   //
17659   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17660   // function is a pure virtual function we're calling, and in that case the
17661   // function was selected by overload resolution and we need to resolve its
17662   // exception specification for a different reason.
17663   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17664   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17665     ResolveExceptionSpec(Loc, FPT);
17666 
17667   // If this is the first "real" use, act on that.
17668   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17669     // Keep track of used but undefined functions.
17670     if (!Func->isDefined()) {
17671       if (mightHaveNonExternalLinkage(Func))
17672         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17673       else if (Func->getMostRecentDecl()->isInlined() &&
17674                !LangOpts.GNUInline &&
17675                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17676         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17677       else if (isExternalWithNoLinkageType(Func))
17678         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17679     }
17680 
17681     // Some x86 Windows calling conventions mangle the size of the parameter
17682     // pack into the name. Computing the size of the parameters requires the
17683     // parameter types to be complete. Check that now.
17684     if (funcHasParameterSizeMangling(*this, Func))
17685       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17686 
17687     // In the MS C++ ABI, the compiler emits destructor variants where they are
17688     // used. If the destructor is used here but defined elsewhere, mark the
17689     // virtual base destructors referenced. If those virtual base destructors
17690     // are inline, this will ensure they are defined when emitting the complete
17691     // destructor variant. This checking may be redundant if the destructor is
17692     // provided later in this TU.
17693     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17694       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17695         CXXRecordDecl *Parent = Dtor->getParent();
17696         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17697           CheckCompleteDestructorVariant(Loc, Dtor);
17698       }
17699     }
17700 
17701     Func->markUsed(Context);
17702   }
17703 }
17704 
17705 /// Directly mark a variable odr-used. Given a choice, prefer to use
17706 /// MarkVariableReferenced since it does additional checks and then
17707 /// calls MarkVarDeclODRUsed.
17708 /// If the variable must be captured:
17709 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17710 ///  - else capture it in the DeclContext that maps to the
17711 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17712 static void
17713 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17714                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17715   // Keep track of used but undefined variables.
17716   // FIXME: We shouldn't suppress this warning for static data members.
17717   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17718       (!Var->isExternallyVisible() || Var->isInline() ||
17719        SemaRef.isExternalWithNoLinkageType(Var)) &&
17720       !(Var->isStaticDataMember() && Var->hasInit())) {
17721     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17722     if (old.isInvalid())
17723       old = Loc;
17724   }
17725   QualType CaptureType, DeclRefType;
17726   if (SemaRef.LangOpts.OpenMP)
17727     SemaRef.tryCaptureOpenMPLambdas(Var);
17728   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17729     /*EllipsisLoc*/ SourceLocation(),
17730     /*BuildAndDiagnose*/ true,
17731     CaptureType, DeclRefType,
17732     FunctionScopeIndexToStopAt);
17733 
17734   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
17735     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17736     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17737     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17738     if (VarTarget == Sema::CVT_Host &&
17739         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17740          UserTarget == Sema::CFT_Global)) {
17741       // Diagnose ODR-use of host global variables in device functions.
17742       // Reference of device global variables in host functions is allowed
17743       // through shadow variables therefore it is not diagnosed.
17744       if (SemaRef.LangOpts.CUDAIsDevice) {
17745         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17746             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17747         SemaRef.targetDiag(Var->getLocation(),
17748                            Var->getType().isConstQualified()
17749                                ? diag::note_cuda_const_var_unpromoted
17750                                : diag::note_cuda_host_var);
17751       }
17752     } else if (VarTarget == Sema::CVT_Device &&
17753                (UserTarget == Sema::CFT_Host ||
17754                 UserTarget == Sema::CFT_HostDevice) &&
17755                !Var->hasExternalStorage()) {
17756       // Record a CUDA/HIP device side variable if it is ODR-used
17757       // by host code. This is done conservatively, when the variable is
17758       // referenced in any of the following contexts:
17759       //   - a non-function context
17760       //   - a host function
17761       //   - a host device function
17762       // This makes the ODR-use of the device side variable by host code to
17763       // be visible in the device compilation for the compiler to be able to
17764       // emit template variables instantiated by host code only and to
17765       // externalize the static device side variable ODR-used by host code.
17766       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17767     }
17768   }
17769 
17770   Var->markUsed(SemaRef.Context);
17771 }
17772 
17773 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17774                                              SourceLocation Loc,
17775                                              unsigned CapturingScopeIndex) {
17776   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17777 }
17778 
17779 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17780                                                ValueDecl *var) {
17781   DeclContext *VarDC = var->getDeclContext();
17782 
17783   //  If the parameter still belongs to the translation unit, then
17784   //  we're actually just using one parameter in the declaration of
17785   //  the next.
17786   if (isa<ParmVarDecl>(var) &&
17787       isa<TranslationUnitDecl>(VarDC))
17788     return;
17789 
17790   // For C code, don't diagnose about capture if we're not actually in code
17791   // right now; it's impossible to write a non-constant expression outside of
17792   // function context, so we'll get other (more useful) diagnostics later.
17793   //
17794   // For C++, things get a bit more nasty... it would be nice to suppress this
17795   // diagnostic for certain cases like using a local variable in an array bound
17796   // for a member of a local class, but the correct predicate is not obvious.
17797   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17798     return;
17799 
17800   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17801   unsigned ContextKind = 3; // unknown
17802   if (isa<CXXMethodDecl>(VarDC) &&
17803       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17804     ContextKind = 2;
17805   } else if (isa<FunctionDecl>(VarDC)) {
17806     ContextKind = 0;
17807   } else if (isa<BlockDecl>(VarDC)) {
17808     ContextKind = 1;
17809   }
17810 
17811   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17812     << var << ValueKind << ContextKind << VarDC;
17813   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17814       << var;
17815 
17816   // FIXME: Add additional diagnostic info about class etc. which prevents
17817   // capture.
17818 }
17819 
17820 
17821 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17822                                       bool &SubCapturesAreNested,
17823                                       QualType &CaptureType,
17824                                       QualType &DeclRefType) {
17825    // Check whether we've already captured it.
17826   if (CSI->CaptureMap.count(Var)) {
17827     // If we found a capture, any subcaptures are nested.
17828     SubCapturesAreNested = true;
17829 
17830     // Retrieve the capture type for this variable.
17831     CaptureType = CSI->getCapture(Var).getCaptureType();
17832 
17833     // Compute the type of an expression that refers to this variable.
17834     DeclRefType = CaptureType.getNonReferenceType();
17835 
17836     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17837     // are mutable in the sense that user can change their value - they are
17838     // private instances of the captured declarations.
17839     const Capture &Cap = CSI->getCapture(Var);
17840     if (Cap.isCopyCapture() &&
17841         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17842         !(isa<CapturedRegionScopeInfo>(CSI) &&
17843           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17844       DeclRefType.addConst();
17845     return true;
17846   }
17847   return false;
17848 }
17849 
17850 // Only block literals, captured statements, and lambda expressions can
17851 // capture; other scopes don't work.
17852 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17853                                  SourceLocation Loc,
17854                                  const bool Diagnose, Sema &S) {
17855   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17856     return getLambdaAwareParentOfDeclContext(DC);
17857   else if (Var->hasLocalStorage()) {
17858     if (Diagnose)
17859        diagnoseUncapturableValueReference(S, Loc, Var);
17860   }
17861   return nullptr;
17862 }
17863 
17864 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17865 // certain types of variables (unnamed, variably modified types etc.)
17866 // so check for eligibility.
17867 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17868                                  SourceLocation Loc,
17869                                  const bool Diagnose, Sema &S) {
17870 
17871   bool IsBlock = isa<BlockScopeInfo>(CSI);
17872   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17873 
17874   // Lambdas are not allowed to capture unnamed variables
17875   // (e.g. anonymous unions).
17876   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17877   // assuming that's the intent.
17878   if (IsLambda && !Var->getDeclName()) {
17879     if (Diagnose) {
17880       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17881       S.Diag(Var->getLocation(), diag::note_declared_at);
17882     }
17883     return false;
17884   }
17885 
17886   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17887   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17888     if (Diagnose) {
17889       S.Diag(Loc, diag::err_ref_vm_type);
17890       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17891     }
17892     return false;
17893   }
17894   // Prohibit structs with flexible array members too.
17895   // We cannot capture what is in the tail end of the struct.
17896   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17897     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17898       if (Diagnose) {
17899         if (IsBlock)
17900           S.Diag(Loc, diag::err_ref_flexarray_type);
17901         else
17902           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17903         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17904       }
17905       return false;
17906     }
17907   }
17908   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17909   // Lambdas and captured statements are not allowed to capture __block
17910   // variables; they don't support the expected semantics.
17911   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17912     if (Diagnose) {
17913       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17914       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17915     }
17916     return false;
17917   }
17918   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17919   if (S.getLangOpts().OpenCL && IsBlock &&
17920       Var->getType()->isBlockPointerType()) {
17921     if (Diagnose)
17922       S.Diag(Loc, diag::err_opencl_block_ref_block);
17923     return false;
17924   }
17925 
17926   return true;
17927 }
17928 
17929 // Returns true if the capture by block was successful.
17930 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17931                                  SourceLocation Loc,
17932                                  const bool BuildAndDiagnose,
17933                                  QualType &CaptureType,
17934                                  QualType &DeclRefType,
17935                                  const bool Nested,
17936                                  Sema &S, bool Invalid) {
17937   bool ByRef = false;
17938 
17939   // Blocks are not allowed to capture arrays, excepting OpenCL.
17940   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17941   // (decayed to pointers).
17942   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17943     if (BuildAndDiagnose) {
17944       S.Diag(Loc, diag::err_ref_array_type);
17945       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17946       Invalid = true;
17947     } else {
17948       return false;
17949     }
17950   }
17951 
17952   // Forbid the block-capture of autoreleasing variables.
17953   if (!Invalid &&
17954       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17955     if (BuildAndDiagnose) {
17956       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17957         << /*block*/ 0;
17958       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17959       Invalid = true;
17960     } else {
17961       return false;
17962     }
17963   }
17964 
17965   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17966   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17967     QualType PointeeTy = PT->getPointeeType();
17968 
17969     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17970         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17971         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17972       if (BuildAndDiagnose) {
17973         SourceLocation VarLoc = Var->getLocation();
17974         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17975         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17976       }
17977     }
17978   }
17979 
17980   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17981   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17982       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17983     // Block capture by reference does not change the capture or
17984     // declaration reference types.
17985     ByRef = true;
17986   } else {
17987     // Block capture by copy introduces 'const'.
17988     CaptureType = CaptureType.getNonReferenceType().withConst();
17989     DeclRefType = CaptureType;
17990   }
17991 
17992   // Actually capture the variable.
17993   if (BuildAndDiagnose)
17994     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17995                     CaptureType, Invalid);
17996 
17997   return !Invalid;
17998 }
17999 
18000 
18001 /// Capture the given variable in the captured region.
18002 static bool captureInCapturedRegion(
18003     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18004     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18005     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18006     bool IsTopScope, Sema &S, bool Invalid) {
18007   // By default, capture variables by reference.
18008   bool ByRef = true;
18009   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18010     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18011   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18012     // Using an LValue reference type is consistent with Lambdas (see below).
18013     if (S.isOpenMPCapturedDecl(Var)) {
18014       bool HasConst = DeclRefType.isConstQualified();
18015       DeclRefType = DeclRefType.getUnqualifiedType();
18016       // Don't lose diagnostics about assignments to const.
18017       if (HasConst)
18018         DeclRefType.addConst();
18019     }
18020     // Do not capture firstprivates in tasks.
18021     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18022         OMPC_unknown)
18023       return true;
18024     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18025                                     RSI->OpenMPCaptureLevel);
18026   }
18027 
18028   if (ByRef)
18029     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18030   else
18031     CaptureType = DeclRefType;
18032 
18033   // Actually capture the variable.
18034   if (BuildAndDiagnose)
18035     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18036                     Loc, SourceLocation(), CaptureType, Invalid);
18037 
18038   return !Invalid;
18039 }
18040 
18041 /// Capture the given variable in the lambda.
18042 static bool captureInLambda(LambdaScopeInfo *LSI,
18043                             VarDecl *Var,
18044                             SourceLocation Loc,
18045                             const bool BuildAndDiagnose,
18046                             QualType &CaptureType,
18047                             QualType &DeclRefType,
18048                             const bool RefersToCapturedVariable,
18049                             const Sema::TryCaptureKind Kind,
18050                             SourceLocation EllipsisLoc,
18051                             const bool IsTopScope,
18052                             Sema &S, bool Invalid) {
18053   // Determine whether we are capturing by reference or by value.
18054   bool ByRef = false;
18055   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18056     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18057   } else {
18058     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18059   }
18060 
18061   // Compute the type of the field that will capture this variable.
18062   if (ByRef) {
18063     // C++11 [expr.prim.lambda]p15:
18064     //   An entity is captured by reference if it is implicitly or
18065     //   explicitly captured but not captured by copy. It is
18066     //   unspecified whether additional unnamed non-static data
18067     //   members are declared in the closure type for entities
18068     //   captured by reference.
18069     //
18070     // FIXME: It is not clear whether we want to build an lvalue reference
18071     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18072     // to do the former, while EDG does the latter. Core issue 1249 will
18073     // clarify, but for now we follow GCC because it's a more permissive and
18074     // easily defensible position.
18075     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18076   } else {
18077     // C++11 [expr.prim.lambda]p14:
18078     //   For each entity captured by copy, an unnamed non-static
18079     //   data member is declared in the closure type. The
18080     //   declaration order of these members is unspecified. The type
18081     //   of such a data member is the type of the corresponding
18082     //   captured entity if the entity is not a reference to an
18083     //   object, or the referenced type otherwise. [Note: If the
18084     //   captured entity is a reference to a function, the
18085     //   corresponding data member is also a reference to a
18086     //   function. - end note ]
18087     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18088       if (!RefType->getPointeeType()->isFunctionType())
18089         CaptureType = RefType->getPointeeType();
18090     }
18091 
18092     // Forbid the lambda copy-capture of autoreleasing variables.
18093     if (!Invalid &&
18094         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18095       if (BuildAndDiagnose) {
18096         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18097         S.Diag(Var->getLocation(), diag::note_previous_decl)
18098           << Var->getDeclName();
18099         Invalid = true;
18100       } else {
18101         return false;
18102       }
18103     }
18104 
18105     // Make sure that by-copy captures are of a complete and non-abstract type.
18106     if (!Invalid && BuildAndDiagnose) {
18107       if (!CaptureType->isDependentType() &&
18108           S.RequireCompleteSizedType(
18109               Loc, CaptureType,
18110               diag::err_capture_of_incomplete_or_sizeless_type,
18111               Var->getDeclName()))
18112         Invalid = true;
18113       else if (S.RequireNonAbstractType(Loc, CaptureType,
18114                                         diag::err_capture_of_abstract_type))
18115         Invalid = true;
18116     }
18117   }
18118 
18119   // Compute the type of a reference to this captured variable.
18120   if (ByRef)
18121     DeclRefType = CaptureType.getNonReferenceType();
18122   else {
18123     // C++ [expr.prim.lambda]p5:
18124     //   The closure type for a lambda-expression has a public inline
18125     //   function call operator [...]. This function call operator is
18126     //   declared const (9.3.1) if and only if the lambda-expression's
18127     //   parameter-declaration-clause is not followed by mutable.
18128     DeclRefType = CaptureType.getNonReferenceType();
18129     if (!LSI->Mutable && !CaptureType->isReferenceType())
18130       DeclRefType.addConst();
18131   }
18132 
18133   // Add the capture.
18134   if (BuildAndDiagnose)
18135     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18136                     Loc, EllipsisLoc, CaptureType, Invalid);
18137 
18138   return !Invalid;
18139 }
18140 
18141 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18142   // Offer a Copy fix even if the type is dependent.
18143   if (Var->getType()->isDependentType())
18144     return true;
18145   QualType T = Var->getType().getNonReferenceType();
18146   if (T.isTriviallyCopyableType(Context))
18147     return true;
18148   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18149 
18150     if (!(RD = RD->getDefinition()))
18151       return false;
18152     if (RD->hasSimpleCopyConstructor())
18153       return true;
18154     if (RD->hasUserDeclaredCopyConstructor())
18155       for (CXXConstructorDecl *Ctor : RD->ctors())
18156         if (Ctor->isCopyConstructor())
18157           return !Ctor->isDeleted();
18158   }
18159   return false;
18160 }
18161 
18162 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18163 /// default capture. Fixes may be omitted if they aren't allowed by the
18164 /// standard, for example we can't emit a default copy capture fix-it if we
18165 /// already explicitly copy capture capture another variable.
18166 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18167                                     VarDecl *Var) {
18168   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18169   // Don't offer Capture by copy of default capture by copy fixes if Var is
18170   // known not to be copy constructible.
18171   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18172 
18173   SmallString<32> FixBuffer;
18174   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18175   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18176     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18177     if (ShouldOfferCopyFix) {
18178       // Offer fixes to insert an explicit capture for the variable.
18179       // [] -> [VarName]
18180       // [OtherCapture] -> [OtherCapture, VarName]
18181       FixBuffer.assign({Separator, Var->getName()});
18182       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18183           << Var << /*value*/ 0
18184           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18185     }
18186     // As above but capture by reference.
18187     FixBuffer.assign({Separator, "&", Var->getName()});
18188     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18189         << Var << /*reference*/ 1
18190         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18191   }
18192 
18193   // Only try to offer default capture if there are no captures excluding this
18194   // and init captures.
18195   // [this]: OK.
18196   // [X = Y]: OK.
18197   // [&A, &B]: Don't offer.
18198   // [A, B]: Don't offer.
18199   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18200         return !C.isThisCapture() && !C.isInitCapture();
18201       }))
18202     return;
18203 
18204   // The default capture specifiers, '=' or '&', must appear first in the
18205   // capture body.
18206   SourceLocation DefaultInsertLoc =
18207       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18208 
18209   if (ShouldOfferCopyFix) {
18210     bool CanDefaultCopyCapture = true;
18211     // [=, *this] OK since c++17
18212     // [=, this] OK since c++20
18213     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18214       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18215                                   ? LSI->getCXXThisCapture().isCopyCapture()
18216                                   : false;
18217     // We can't use default capture by copy if any captures already specified
18218     // capture by copy.
18219     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18220           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18221         })) {
18222       FixBuffer.assign({"=", Separator});
18223       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18224           << /*value*/ 0
18225           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18226     }
18227   }
18228 
18229   // We can't use default capture by reference if any captures already specified
18230   // capture by reference.
18231   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18232         return !C.isInitCapture() && C.isReferenceCapture() &&
18233                !C.isThisCapture();
18234       })) {
18235     FixBuffer.assign({"&", Separator});
18236     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18237         << /*reference*/ 1
18238         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18239   }
18240 }
18241 
18242 bool Sema::tryCaptureVariable(
18243     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18244     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18245     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18246   // An init-capture is notionally from the context surrounding its
18247   // declaration, but its parent DC is the lambda class.
18248   DeclContext *VarDC = Var->getDeclContext();
18249   if (Var->isInitCapture())
18250     VarDC = VarDC->getParent();
18251 
18252   DeclContext *DC = CurContext;
18253   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18254       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18255   // We need to sync up the Declaration Context with the
18256   // FunctionScopeIndexToStopAt
18257   if (FunctionScopeIndexToStopAt) {
18258     unsigned FSIndex = FunctionScopes.size() - 1;
18259     while (FSIndex != MaxFunctionScopesIndex) {
18260       DC = getLambdaAwareParentOfDeclContext(DC);
18261       --FSIndex;
18262     }
18263   }
18264 
18265 
18266   // If the variable is declared in the current context, there is no need to
18267   // capture it.
18268   if (VarDC == DC) return true;
18269 
18270   // Capture global variables if it is required to use private copy of this
18271   // variable.
18272   bool IsGlobal = !Var->hasLocalStorage();
18273   if (IsGlobal &&
18274       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18275                                                 MaxFunctionScopesIndex)))
18276     return true;
18277   Var = Var->getCanonicalDecl();
18278 
18279   // Walk up the stack to determine whether we can capture the variable,
18280   // performing the "simple" checks that don't depend on type. We stop when
18281   // we've either hit the declared scope of the variable or find an existing
18282   // capture of that variable.  We start from the innermost capturing-entity
18283   // (the DC) and ensure that all intervening capturing-entities
18284   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18285   // declcontext can either capture the variable or have already captured
18286   // the variable.
18287   CaptureType = Var->getType();
18288   DeclRefType = CaptureType.getNonReferenceType();
18289   bool Nested = false;
18290   bool Explicit = (Kind != TryCapture_Implicit);
18291   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18292   do {
18293     // Only block literals, captured statements, and lambda expressions can
18294     // capture; other scopes don't work.
18295     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18296                                                               ExprLoc,
18297                                                               BuildAndDiagnose,
18298                                                               *this);
18299     // We need to check for the parent *first* because, if we *have*
18300     // private-captured a global variable, we need to recursively capture it in
18301     // intermediate blocks, lambdas, etc.
18302     if (!ParentDC) {
18303       if (IsGlobal) {
18304         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18305         break;
18306       }
18307       return true;
18308     }
18309 
18310     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18311     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18312 
18313 
18314     // Check whether we've already captured it.
18315     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18316                                              DeclRefType)) {
18317       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18318       break;
18319     }
18320     // If we are instantiating a generic lambda call operator body,
18321     // we do not want to capture new variables.  What was captured
18322     // during either a lambdas transformation or initial parsing
18323     // should be used.
18324     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18325       if (BuildAndDiagnose) {
18326         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18327         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18328           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18329           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18330           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18331           buildLambdaCaptureFixit(*this, LSI, Var);
18332         } else
18333           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18334       }
18335       return true;
18336     }
18337 
18338     // Try to capture variable-length arrays types.
18339     if (Var->getType()->isVariablyModifiedType()) {
18340       // We're going to walk down into the type and look for VLA
18341       // expressions.
18342       QualType QTy = Var->getType();
18343       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18344         QTy = PVD->getOriginalType();
18345       captureVariablyModifiedType(Context, QTy, CSI);
18346     }
18347 
18348     if (getLangOpts().OpenMP) {
18349       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18350         // OpenMP private variables should not be captured in outer scope, so
18351         // just break here. Similarly, global variables that are captured in a
18352         // target region should not be captured outside the scope of the region.
18353         if (RSI->CapRegionKind == CR_OpenMP) {
18354           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18355               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18356           // If the variable is private (i.e. not captured) and has variably
18357           // modified type, we still need to capture the type for correct
18358           // codegen in all regions, associated with the construct. Currently,
18359           // it is captured in the innermost captured region only.
18360           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18361               Var->getType()->isVariablyModifiedType()) {
18362             QualType QTy = Var->getType();
18363             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18364               QTy = PVD->getOriginalType();
18365             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18366                  I < E; ++I) {
18367               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18368                   FunctionScopes[FunctionScopesIndex - I]);
18369               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18370                      "Wrong number of captured regions associated with the "
18371                      "OpenMP construct.");
18372               captureVariablyModifiedType(Context, QTy, OuterRSI);
18373             }
18374           }
18375           bool IsTargetCap =
18376               IsOpenMPPrivateDecl != OMPC_private &&
18377               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18378                                          RSI->OpenMPCaptureLevel);
18379           // Do not capture global if it is not privatized in outer regions.
18380           bool IsGlobalCap =
18381               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18382                                                      RSI->OpenMPCaptureLevel);
18383 
18384           // When we detect target captures we are looking from inside the
18385           // target region, therefore we need to propagate the capture from the
18386           // enclosing region. Therefore, the capture is not initially nested.
18387           if (IsTargetCap)
18388             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18389 
18390           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18391               (IsGlobal && !IsGlobalCap)) {
18392             Nested = !IsTargetCap;
18393             bool HasConst = DeclRefType.isConstQualified();
18394             DeclRefType = DeclRefType.getUnqualifiedType();
18395             // Don't lose diagnostics about assignments to const.
18396             if (HasConst)
18397               DeclRefType.addConst();
18398             CaptureType = Context.getLValueReferenceType(DeclRefType);
18399             break;
18400           }
18401         }
18402       }
18403     }
18404     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18405       // No capture-default, and this is not an explicit capture
18406       // so cannot capture this variable.
18407       if (BuildAndDiagnose) {
18408         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18409         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18410         auto *LSI = cast<LambdaScopeInfo>(CSI);
18411         if (LSI->Lambda) {
18412           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18413           buildLambdaCaptureFixit(*this, LSI, Var);
18414         }
18415         // FIXME: If we error out because an outer lambda can not implicitly
18416         // capture a variable that an inner lambda explicitly captures, we
18417         // should have the inner lambda do the explicit capture - because
18418         // it makes for cleaner diagnostics later.  This would purely be done
18419         // so that the diagnostic does not misleadingly claim that a variable
18420         // can not be captured by a lambda implicitly even though it is captured
18421         // explicitly.  Suggestion:
18422         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18423         //    at the function head
18424         //  - cache the StartingDeclContext - this must be a lambda
18425         //  - captureInLambda in the innermost lambda the variable.
18426       }
18427       return true;
18428     }
18429 
18430     FunctionScopesIndex--;
18431     DC = ParentDC;
18432     Explicit = false;
18433   } while (!VarDC->Equals(DC));
18434 
18435   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18436   // computing the type of the capture at each step, checking type-specific
18437   // requirements, and adding captures if requested.
18438   // If the variable had already been captured previously, we start capturing
18439   // at the lambda nested within that one.
18440   bool Invalid = false;
18441   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18442        ++I) {
18443     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18444 
18445     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18446     // certain types of variables (unnamed, variably modified types etc.)
18447     // so check for eligibility.
18448     if (!Invalid)
18449       Invalid =
18450           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18451 
18452     // After encountering an error, if we're actually supposed to capture, keep
18453     // capturing in nested contexts to suppress any follow-on diagnostics.
18454     if (Invalid && !BuildAndDiagnose)
18455       return true;
18456 
18457     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18458       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18459                                DeclRefType, Nested, *this, Invalid);
18460       Nested = true;
18461     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18462       Invalid = !captureInCapturedRegion(
18463           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18464           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18465       Nested = true;
18466     } else {
18467       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18468       Invalid =
18469           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18470                            DeclRefType, Nested, Kind, EllipsisLoc,
18471                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18472       Nested = true;
18473     }
18474 
18475     if (Invalid && !BuildAndDiagnose)
18476       return true;
18477   }
18478   return Invalid;
18479 }
18480 
18481 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18482                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18483   QualType CaptureType;
18484   QualType DeclRefType;
18485   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18486                             /*BuildAndDiagnose=*/true, CaptureType,
18487                             DeclRefType, nullptr);
18488 }
18489 
18490 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18491   QualType CaptureType;
18492   QualType DeclRefType;
18493   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18494                              /*BuildAndDiagnose=*/false, CaptureType,
18495                              DeclRefType, nullptr);
18496 }
18497 
18498 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18499   QualType CaptureType;
18500   QualType DeclRefType;
18501 
18502   // Determine whether we can capture this variable.
18503   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18504                          /*BuildAndDiagnose=*/false, CaptureType,
18505                          DeclRefType, nullptr))
18506     return QualType();
18507 
18508   return DeclRefType;
18509 }
18510 
18511 namespace {
18512 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18513 // The produced TemplateArgumentListInfo* points to data stored within this
18514 // object, so should only be used in contexts where the pointer will not be
18515 // used after the CopiedTemplateArgs object is destroyed.
18516 class CopiedTemplateArgs {
18517   bool HasArgs;
18518   TemplateArgumentListInfo TemplateArgStorage;
18519 public:
18520   template<typename RefExpr>
18521   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18522     if (HasArgs)
18523       E->copyTemplateArgumentsInto(TemplateArgStorage);
18524   }
18525   operator TemplateArgumentListInfo*()
18526 #ifdef __has_cpp_attribute
18527 #if __has_cpp_attribute(clang::lifetimebound)
18528   [[clang::lifetimebound]]
18529 #endif
18530 #endif
18531   {
18532     return HasArgs ? &TemplateArgStorage : nullptr;
18533   }
18534 };
18535 }
18536 
18537 /// Walk the set of potential results of an expression and mark them all as
18538 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18539 ///
18540 /// \return A new expression if we found any potential results, ExprEmpty() if
18541 ///         not, and ExprError() if we diagnosed an error.
18542 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18543                                                       NonOdrUseReason NOUR) {
18544   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18545   // an object that satisfies the requirements for appearing in a
18546   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18547   // is immediately applied."  This function handles the lvalue-to-rvalue
18548   // conversion part.
18549   //
18550   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18551   // transform it into the relevant kind of non-odr-use node and rebuild the
18552   // tree of nodes leading to it.
18553   //
18554   // This is a mini-TreeTransform that only transforms a restricted subset of
18555   // nodes (and only certain operands of them).
18556 
18557   // Rebuild a subexpression.
18558   auto Rebuild = [&](Expr *Sub) {
18559     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18560   };
18561 
18562   // Check whether a potential result satisfies the requirements of NOUR.
18563   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18564     // Any entity other than a VarDecl is always odr-used whenever it's named
18565     // in a potentially-evaluated expression.
18566     auto *VD = dyn_cast<VarDecl>(D);
18567     if (!VD)
18568       return true;
18569 
18570     // C++2a [basic.def.odr]p4:
18571     //   A variable x whose name appears as a potentially-evalauted expression
18572     //   e is odr-used by e unless
18573     //   -- x is a reference that is usable in constant expressions, or
18574     //   -- x is a variable of non-reference type that is usable in constant
18575     //      expressions and has no mutable subobjects, and e is an element of
18576     //      the set of potential results of an expression of
18577     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18578     //      conversion is applied, or
18579     //   -- x is a variable of non-reference type, and e is an element of the
18580     //      set of potential results of a discarded-value expression to which
18581     //      the lvalue-to-rvalue conversion is not applied
18582     //
18583     // We check the first bullet and the "potentially-evaluated" condition in
18584     // BuildDeclRefExpr. We check the type requirements in the second bullet
18585     // in CheckLValueToRValueConversionOperand below.
18586     switch (NOUR) {
18587     case NOUR_None:
18588     case NOUR_Unevaluated:
18589       llvm_unreachable("unexpected non-odr-use-reason");
18590 
18591     case NOUR_Constant:
18592       // Constant references were handled when they were built.
18593       if (VD->getType()->isReferenceType())
18594         return true;
18595       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18596         if (RD->hasMutableFields())
18597           return true;
18598       if (!VD->isUsableInConstantExpressions(S.Context))
18599         return true;
18600       break;
18601 
18602     case NOUR_Discarded:
18603       if (VD->getType()->isReferenceType())
18604         return true;
18605       break;
18606     }
18607     return false;
18608   };
18609 
18610   // Mark that this expression does not constitute an odr-use.
18611   auto MarkNotOdrUsed = [&] {
18612     S.MaybeODRUseExprs.remove(E);
18613     if (LambdaScopeInfo *LSI = S.getCurLambda())
18614       LSI->markVariableExprAsNonODRUsed(E);
18615   };
18616 
18617   // C++2a [basic.def.odr]p2:
18618   //   The set of potential results of an expression e is defined as follows:
18619   switch (E->getStmtClass()) {
18620   //   -- If e is an id-expression, ...
18621   case Expr::DeclRefExprClass: {
18622     auto *DRE = cast<DeclRefExpr>(E);
18623     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18624       break;
18625 
18626     // Rebuild as a non-odr-use DeclRefExpr.
18627     MarkNotOdrUsed();
18628     return DeclRefExpr::Create(
18629         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18630         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18631         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18632         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18633   }
18634 
18635   case Expr::FunctionParmPackExprClass: {
18636     auto *FPPE = cast<FunctionParmPackExpr>(E);
18637     // If any of the declarations in the pack is odr-used, then the expression
18638     // as a whole constitutes an odr-use.
18639     for (VarDecl *D : *FPPE)
18640       if (IsPotentialResultOdrUsed(D))
18641         return ExprEmpty();
18642 
18643     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18644     // nothing cares about whether we marked this as an odr-use, but it might
18645     // be useful for non-compiler tools.
18646     MarkNotOdrUsed();
18647     break;
18648   }
18649 
18650   //   -- If e is a subscripting operation with an array operand...
18651   case Expr::ArraySubscriptExprClass: {
18652     auto *ASE = cast<ArraySubscriptExpr>(E);
18653     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18654     if (!OldBase->getType()->isArrayType())
18655       break;
18656     ExprResult Base = Rebuild(OldBase);
18657     if (!Base.isUsable())
18658       return Base;
18659     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18660     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18661     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18662     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18663                                      ASE->getRBracketLoc());
18664   }
18665 
18666   case Expr::MemberExprClass: {
18667     auto *ME = cast<MemberExpr>(E);
18668     // -- If e is a class member access expression [...] naming a non-static
18669     //    data member...
18670     if (isa<FieldDecl>(ME->getMemberDecl())) {
18671       ExprResult Base = Rebuild(ME->getBase());
18672       if (!Base.isUsable())
18673         return Base;
18674       return MemberExpr::Create(
18675           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18676           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18677           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18678           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18679           ME->getObjectKind(), ME->isNonOdrUse());
18680     }
18681 
18682     if (ME->getMemberDecl()->isCXXInstanceMember())
18683       break;
18684 
18685     // -- If e is a class member access expression naming a static data member,
18686     //    ...
18687     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18688       break;
18689 
18690     // Rebuild as a non-odr-use MemberExpr.
18691     MarkNotOdrUsed();
18692     return MemberExpr::Create(
18693         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18694         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18695         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18696         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18697   }
18698 
18699   case Expr::BinaryOperatorClass: {
18700     auto *BO = cast<BinaryOperator>(E);
18701     Expr *LHS = BO->getLHS();
18702     Expr *RHS = BO->getRHS();
18703     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18704     if (BO->getOpcode() == BO_PtrMemD) {
18705       ExprResult Sub = Rebuild(LHS);
18706       if (!Sub.isUsable())
18707         return Sub;
18708       LHS = Sub.get();
18709     //   -- If e is a comma expression, ...
18710     } else if (BO->getOpcode() == BO_Comma) {
18711       ExprResult Sub = Rebuild(RHS);
18712       if (!Sub.isUsable())
18713         return Sub;
18714       RHS = Sub.get();
18715     } else {
18716       break;
18717     }
18718     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18719                         LHS, RHS);
18720   }
18721 
18722   //   -- If e has the form (e1)...
18723   case Expr::ParenExprClass: {
18724     auto *PE = cast<ParenExpr>(E);
18725     ExprResult Sub = Rebuild(PE->getSubExpr());
18726     if (!Sub.isUsable())
18727       return Sub;
18728     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18729   }
18730 
18731   //   -- If e is a glvalue conditional expression, ...
18732   // We don't apply this to a binary conditional operator. FIXME: Should we?
18733   case Expr::ConditionalOperatorClass: {
18734     auto *CO = cast<ConditionalOperator>(E);
18735     ExprResult LHS = Rebuild(CO->getLHS());
18736     if (LHS.isInvalid())
18737       return ExprError();
18738     ExprResult RHS = Rebuild(CO->getRHS());
18739     if (RHS.isInvalid())
18740       return ExprError();
18741     if (!LHS.isUsable() && !RHS.isUsable())
18742       return ExprEmpty();
18743     if (!LHS.isUsable())
18744       LHS = CO->getLHS();
18745     if (!RHS.isUsable())
18746       RHS = CO->getRHS();
18747     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18748                                 CO->getCond(), LHS.get(), RHS.get());
18749   }
18750 
18751   // [Clang extension]
18752   //   -- If e has the form __extension__ e1...
18753   case Expr::UnaryOperatorClass: {
18754     auto *UO = cast<UnaryOperator>(E);
18755     if (UO->getOpcode() != UO_Extension)
18756       break;
18757     ExprResult Sub = Rebuild(UO->getSubExpr());
18758     if (!Sub.isUsable())
18759       return Sub;
18760     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18761                           Sub.get());
18762   }
18763 
18764   // [Clang extension]
18765   //   -- If e has the form _Generic(...), the set of potential results is the
18766   //      union of the sets of potential results of the associated expressions.
18767   case Expr::GenericSelectionExprClass: {
18768     auto *GSE = cast<GenericSelectionExpr>(E);
18769 
18770     SmallVector<Expr *, 4> AssocExprs;
18771     bool AnyChanged = false;
18772     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18773       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18774       if (AssocExpr.isInvalid())
18775         return ExprError();
18776       if (AssocExpr.isUsable()) {
18777         AssocExprs.push_back(AssocExpr.get());
18778         AnyChanged = true;
18779       } else {
18780         AssocExprs.push_back(OrigAssocExpr);
18781       }
18782     }
18783 
18784     return AnyChanged ? S.CreateGenericSelectionExpr(
18785                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18786                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18787                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18788                       : ExprEmpty();
18789   }
18790 
18791   // [Clang extension]
18792   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18793   //      results is the union of the sets of potential results of the
18794   //      second and third subexpressions.
18795   case Expr::ChooseExprClass: {
18796     auto *CE = cast<ChooseExpr>(E);
18797 
18798     ExprResult LHS = Rebuild(CE->getLHS());
18799     if (LHS.isInvalid())
18800       return ExprError();
18801 
18802     ExprResult RHS = Rebuild(CE->getLHS());
18803     if (RHS.isInvalid())
18804       return ExprError();
18805 
18806     if (!LHS.get() && !RHS.get())
18807       return ExprEmpty();
18808     if (!LHS.isUsable())
18809       LHS = CE->getLHS();
18810     if (!RHS.isUsable())
18811       RHS = CE->getRHS();
18812 
18813     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18814                              RHS.get(), CE->getRParenLoc());
18815   }
18816 
18817   // Step through non-syntactic nodes.
18818   case Expr::ConstantExprClass: {
18819     auto *CE = cast<ConstantExpr>(E);
18820     ExprResult Sub = Rebuild(CE->getSubExpr());
18821     if (!Sub.isUsable())
18822       return Sub;
18823     return ConstantExpr::Create(S.Context, Sub.get());
18824   }
18825 
18826   // We could mostly rely on the recursive rebuilding to rebuild implicit
18827   // casts, but not at the top level, so rebuild them here.
18828   case Expr::ImplicitCastExprClass: {
18829     auto *ICE = cast<ImplicitCastExpr>(E);
18830     // Only step through the narrow set of cast kinds we expect to encounter.
18831     // Anything else suggests we've left the region in which potential results
18832     // can be found.
18833     switch (ICE->getCastKind()) {
18834     case CK_NoOp:
18835     case CK_DerivedToBase:
18836     case CK_UncheckedDerivedToBase: {
18837       ExprResult Sub = Rebuild(ICE->getSubExpr());
18838       if (!Sub.isUsable())
18839         return Sub;
18840       CXXCastPath Path(ICE->path());
18841       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18842                                  ICE->getValueKind(), &Path);
18843     }
18844 
18845     default:
18846       break;
18847     }
18848     break;
18849   }
18850 
18851   default:
18852     break;
18853   }
18854 
18855   // Can't traverse through this node. Nothing to do.
18856   return ExprEmpty();
18857 }
18858 
18859 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18860   // Check whether the operand is or contains an object of non-trivial C union
18861   // type.
18862   if (E->getType().isVolatileQualified() &&
18863       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18864        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18865     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18866                           Sema::NTCUC_LValueToRValueVolatile,
18867                           NTCUK_Destruct|NTCUK_Copy);
18868 
18869   // C++2a [basic.def.odr]p4:
18870   //   [...] an expression of non-volatile-qualified non-class type to which
18871   //   the lvalue-to-rvalue conversion is applied [...]
18872   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18873     return E;
18874 
18875   ExprResult Result =
18876       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18877   if (Result.isInvalid())
18878     return ExprError();
18879   return Result.get() ? Result : E;
18880 }
18881 
18882 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18883   Res = CorrectDelayedTyposInExpr(Res);
18884 
18885   if (!Res.isUsable())
18886     return Res;
18887 
18888   // If a constant-expression is a reference to a variable where we delay
18889   // deciding whether it is an odr-use, just assume we will apply the
18890   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18891   // (a non-type template argument), we have special handling anyway.
18892   return CheckLValueToRValueConversionOperand(Res.get());
18893 }
18894 
18895 void Sema::CleanupVarDeclMarking() {
18896   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18897   // call.
18898   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18899   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18900 
18901   for (Expr *E : LocalMaybeODRUseExprs) {
18902     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18903       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18904                          DRE->getLocation(), *this);
18905     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18906       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18907                          *this);
18908     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18909       for (VarDecl *VD : *FP)
18910         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18911     } else {
18912       llvm_unreachable("Unexpected expression");
18913     }
18914   }
18915 
18916   assert(MaybeODRUseExprs.empty() &&
18917          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18918 }
18919 
18920 static void DoMarkVarDeclReferenced(
18921     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18922     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18923   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18924           isa<FunctionParmPackExpr>(E)) &&
18925          "Invalid Expr argument to DoMarkVarDeclReferenced");
18926   Var->setReferenced();
18927 
18928   if (Var->isInvalidDecl())
18929     return;
18930 
18931   auto *MSI = Var->getMemberSpecializationInfo();
18932   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18933                                        : Var->getTemplateSpecializationKind();
18934 
18935   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18936   bool UsableInConstantExpr =
18937       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18938 
18939   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18940     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18941   }
18942 
18943   // C++20 [expr.const]p12:
18944   //   A variable [...] is needed for constant evaluation if it is [...] a
18945   //   variable whose name appears as a potentially constant evaluated
18946   //   expression that is either a contexpr variable or is of non-volatile
18947   //   const-qualified integral type or of reference type
18948   bool NeededForConstantEvaluation =
18949       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18950 
18951   bool NeedDefinition =
18952       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18953 
18954   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18955          "Can't instantiate a partial template specialization.");
18956 
18957   // If this might be a member specialization of a static data member, check
18958   // the specialization is visible. We already did the checks for variable
18959   // template specializations when we created them.
18960   if (NeedDefinition && TSK != TSK_Undeclared &&
18961       !isa<VarTemplateSpecializationDecl>(Var))
18962     SemaRef.checkSpecializationVisibility(Loc, Var);
18963 
18964   // Perform implicit instantiation of static data members, static data member
18965   // templates of class templates, and variable template specializations. Delay
18966   // instantiations of variable templates, except for those that could be used
18967   // in a constant expression.
18968   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18969     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18970     // instantiation declaration if a variable is usable in a constant
18971     // expression (among other cases).
18972     bool TryInstantiating =
18973         TSK == TSK_ImplicitInstantiation ||
18974         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18975 
18976     if (TryInstantiating) {
18977       SourceLocation PointOfInstantiation =
18978           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18979       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18980       if (FirstInstantiation) {
18981         PointOfInstantiation = Loc;
18982         if (MSI)
18983           MSI->setPointOfInstantiation(PointOfInstantiation);
18984           // FIXME: Notify listener.
18985         else
18986           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18987       }
18988 
18989       if (UsableInConstantExpr) {
18990         // Do not defer instantiations of variables that could be used in a
18991         // constant expression.
18992         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18993           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18994         });
18995 
18996         // Re-set the member to trigger a recomputation of the dependence bits
18997         // for the expression.
18998         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18999           DRE->setDecl(DRE->getDecl());
19000         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19001           ME->setMemberDecl(ME->getMemberDecl());
19002       } else if (FirstInstantiation ||
19003                  isa<VarTemplateSpecializationDecl>(Var)) {
19004         // FIXME: For a specialization of a variable template, we don't
19005         // distinguish between "declaration and type implicitly instantiated"
19006         // and "implicit instantiation of definition requested", so we have
19007         // no direct way to avoid enqueueing the pending instantiation
19008         // multiple times.
19009         SemaRef.PendingInstantiations
19010             .push_back(std::make_pair(Var, PointOfInstantiation));
19011       }
19012     }
19013   }
19014 
19015   // C++2a [basic.def.odr]p4:
19016   //   A variable x whose name appears as a potentially-evaluated expression e
19017   //   is odr-used by e unless
19018   //   -- x is a reference that is usable in constant expressions
19019   //   -- x is a variable of non-reference type that is usable in constant
19020   //      expressions and has no mutable subobjects [FIXME], and e is an
19021   //      element of the set of potential results of an expression of
19022   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19023   //      conversion is applied
19024   //   -- x is a variable of non-reference type, and e is an element of the set
19025   //      of potential results of a discarded-value expression to which the
19026   //      lvalue-to-rvalue conversion is not applied [FIXME]
19027   //
19028   // We check the first part of the second bullet here, and
19029   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19030   // FIXME: To get the third bullet right, we need to delay this even for
19031   // variables that are not usable in constant expressions.
19032 
19033   // If we already know this isn't an odr-use, there's nothing more to do.
19034   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19035     if (DRE->isNonOdrUse())
19036       return;
19037   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19038     if (ME->isNonOdrUse())
19039       return;
19040 
19041   switch (OdrUse) {
19042   case OdrUseContext::None:
19043     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19044            "missing non-odr-use marking for unevaluated decl ref");
19045     break;
19046 
19047   case OdrUseContext::FormallyOdrUsed:
19048     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19049     // behavior.
19050     break;
19051 
19052   case OdrUseContext::Used:
19053     // If we might later find that this expression isn't actually an odr-use,
19054     // delay the marking.
19055     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19056       SemaRef.MaybeODRUseExprs.insert(E);
19057     else
19058       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19059     break;
19060 
19061   case OdrUseContext::Dependent:
19062     // If this is a dependent context, we don't need to mark variables as
19063     // odr-used, but we may still need to track them for lambda capture.
19064     // FIXME: Do we also need to do this inside dependent typeid expressions
19065     // (which are modeled as unevaluated at this point)?
19066     const bool RefersToEnclosingScope =
19067         (SemaRef.CurContext != Var->getDeclContext() &&
19068          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19069     if (RefersToEnclosingScope) {
19070       LambdaScopeInfo *const LSI =
19071           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19072       if (LSI && (!LSI->CallOperator ||
19073                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19074         // If a variable could potentially be odr-used, defer marking it so
19075         // until we finish analyzing the full expression for any
19076         // lvalue-to-rvalue
19077         // or discarded value conversions that would obviate odr-use.
19078         // Add it to the list of potential captures that will be analyzed
19079         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19080         // unless the variable is a reference that was initialized by a constant
19081         // expression (this will never need to be captured or odr-used).
19082         //
19083         // FIXME: We can simplify this a lot after implementing P0588R1.
19084         assert(E && "Capture variable should be used in an expression.");
19085         if (!Var->getType()->isReferenceType() ||
19086             !Var->isUsableInConstantExpressions(SemaRef.Context))
19087           LSI->addPotentialCapture(E->IgnoreParens());
19088       }
19089     }
19090     break;
19091   }
19092 }
19093 
19094 /// Mark a variable referenced, and check whether it is odr-used
19095 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19096 /// used directly for normal expressions referring to VarDecl.
19097 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19098   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19099 }
19100 
19101 static void
19102 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19103                    bool MightBeOdrUse,
19104                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19105   if (SemaRef.isInOpenMPDeclareTargetContext())
19106     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19107 
19108   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19109     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19110     return;
19111   }
19112 
19113   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19114 
19115   // If this is a call to a method via a cast, also mark the method in the
19116   // derived class used in case codegen can devirtualize the call.
19117   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19118   if (!ME)
19119     return;
19120   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19121   if (!MD)
19122     return;
19123   // Only attempt to devirtualize if this is truly a virtual call.
19124   bool IsVirtualCall = MD->isVirtual() &&
19125                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19126   if (!IsVirtualCall)
19127     return;
19128 
19129   // If it's possible to devirtualize the call, mark the called function
19130   // referenced.
19131   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19132       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19133   if (DM)
19134     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19135 }
19136 
19137 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19138 ///
19139 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19140 /// handled with care if the DeclRefExpr is not newly-created.
19141 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19142   // TODO: update this with DR# once a defect report is filed.
19143   // C++11 defect. The address of a pure member should not be an ODR use, even
19144   // if it's a qualified reference.
19145   bool OdrUse = true;
19146   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19147     if (Method->isVirtual() &&
19148         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19149       OdrUse = false;
19150 
19151   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19152     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19153         FD->isConsteval() && !RebuildingImmediateInvocation)
19154       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19155   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19156                      RefsMinusAssignments);
19157 }
19158 
19159 /// Perform reference-marking and odr-use handling for a MemberExpr.
19160 void Sema::MarkMemberReferenced(MemberExpr *E) {
19161   // C++11 [basic.def.odr]p2:
19162   //   A non-overloaded function whose name appears as a potentially-evaluated
19163   //   expression or a member of a set of candidate functions, if selected by
19164   //   overload resolution when referred to from a potentially-evaluated
19165   //   expression, is odr-used, unless it is a pure virtual function and its
19166   //   name is not explicitly qualified.
19167   bool MightBeOdrUse = true;
19168   if (E->performsVirtualDispatch(getLangOpts())) {
19169     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19170       if (Method->isPure())
19171         MightBeOdrUse = false;
19172   }
19173   SourceLocation Loc =
19174       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19175   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19176                      RefsMinusAssignments);
19177 }
19178 
19179 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19180 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19181   for (VarDecl *VD : *E)
19182     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19183                        RefsMinusAssignments);
19184 }
19185 
19186 /// Perform marking for a reference to an arbitrary declaration.  It
19187 /// marks the declaration referenced, and performs odr-use checking for
19188 /// functions and variables. This method should not be used when building a
19189 /// normal expression which refers to a variable.
19190 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19191                                  bool MightBeOdrUse) {
19192   if (MightBeOdrUse) {
19193     if (auto *VD = dyn_cast<VarDecl>(D)) {
19194       MarkVariableReferenced(Loc, VD);
19195       return;
19196     }
19197   }
19198   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19199     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19200     return;
19201   }
19202   D->setReferenced();
19203 }
19204 
19205 namespace {
19206   // Mark all of the declarations used by a type as referenced.
19207   // FIXME: Not fully implemented yet! We need to have a better understanding
19208   // of when we're entering a context we should not recurse into.
19209   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19210   // TreeTransforms rebuilding the type in a new context. Rather than
19211   // duplicating the TreeTransform logic, we should consider reusing it here.
19212   // Currently that causes problems when rebuilding LambdaExprs.
19213   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19214     Sema &S;
19215     SourceLocation Loc;
19216 
19217   public:
19218     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19219 
19220     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19221 
19222     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19223   };
19224 }
19225 
19226 bool MarkReferencedDecls::TraverseTemplateArgument(
19227     const TemplateArgument &Arg) {
19228   {
19229     // A non-type template argument is a constant-evaluated context.
19230     EnterExpressionEvaluationContext Evaluated(
19231         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19232     if (Arg.getKind() == TemplateArgument::Declaration) {
19233       if (Decl *D = Arg.getAsDecl())
19234         S.MarkAnyDeclReferenced(Loc, D, true);
19235     } else if (Arg.getKind() == TemplateArgument::Expression) {
19236       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19237     }
19238   }
19239 
19240   return Inherited::TraverseTemplateArgument(Arg);
19241 }
19242 
19243 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19244   MarkReferencedDecls Marker(*this, Loc);
19245   Marker.TraverseType(T);
19246 }
19247 
19248 namespace {
19249 /// Helper class that marks all of the declarations referenced by
19250 /// potentially-evaluated subexpressions as "referenced".
19251 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19252 public:
19253   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19254   bool SkipLocalVariables;
19255   ArrayRef<const Expr *> StopAt;
19256 
19257   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19258                       ArrayRef<const Expr *> StopAt)
19259       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19260 
19261   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19262     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19263   }
19264 
19265   void Visit(Expr *E) {
19266     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19267       return;
19268     Inherited::Visit(E);
19269   }
19270 
19271   void VisitDeclRefExpr(DeclRefExpr *E) {
19272     // If we were asked not to visit local variables, don't.
19273     if (SkipLocalVariables) {
19274       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19275         if (VD->hasLocalStorage())
19276           return;
19277     }
19278 
19279     // FIXME: This can trigger the instantiation of the initializer of a
19280     // variable, which can cause the expression to become value-dependent
19281     // or error-dependent. Do we need to propagate the new dependence bits?
19282     S.MarkDeclRefReferenced(E);
19283   }
19284 
19285   void VisitMemberExpr(MemberExpr *E) {
19286     S.MarkMemberReferenced(E);
19287     Visit(E->getBase());
19288   }
19289 };
19290 } // namespace
19291 
19292 /// Mark any declarations that appear within this expression or any
19293 /// potentially-evaluated subexpressions as "referenced".
19294 ///
19295 /// \param SkipLocalVariables If true, don't mark local variables as
19296 /// 'referenced'.
19297 /// \param StopAt Subexpressions that we shouldn't recurse into.
19298 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19299                                             bool SkipLocalVariables,
19300                                             ArrayRef<const Expr*> StopAt) {
19301   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19302 }
19303 
19304 /// Emit a diagnostic when statements are reachable.
19305 /// FIXME: check for reachability even in expressions for which we don't build a
19306 ///        CFG (eg, in the initializer of a global or in a constant expression).
19307 ///        For example,
19308 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19309 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19310                            const PartialDiagnostic &PD) {
19311   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19312     if (!FunctionScopes.empty())
19313       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19314           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19315     return true;
19316   }
19317 
19318   // The initializer of a constexpr variable or of the first declaration of a
19319   // static data member is not syntactically a constant evaluated constant,
19320   // but nonetheless is always required to be a constant expression, so we
19321   // can skip diagnosing.
19322   // FIXME: Using the mangling context here is a hack.
19323   if (auto *VD = dyn_cast_or_null<VarDecl>(
19324           ExprEvalContexts.back().ManglingContextDecl)) {
19325     if (VD->isConstexpr() ||
19326         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19327       return false;
19328     // FIXME: For any other kind of variable, we should build a CFG for its
19329     // initializer and check whether the context in question is reachable.
19330   }
19331 
19332   Diag(Loc, PD);
19333   return true;
19334 }
19335 
19336 /// Emit a diagnostic that describes an effect on the run-time behavior
19337 /// of the program being compiled.
19338 ///
19339 /// This routine emits the given diagnostic when the code currently being
19340 /// type-checked is "potentially evaluated", meaning that there is a
19341 /// possibility that the code will actually be executable. Code in sizeof()
19342 /// expressions, code used only during overload resolution, etc., are not
19343 /// potentially evaluated. This routine will suppress such diagnostics or,
19344 /// in the absolutely nutty case of potentially potentially evaluated
19345 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19346 /// later.
19347 ///
19348 /// This routine should be used for all diagnostics that describe the run-time
19349 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19350 /// Failure to do so will likely result in spurious diagnostics or failures
19351 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19352 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19353                                const PartialDiagnostic &PD) {
19354 
19355   if (ExprEvalContexts.back().isDiscardedStatementContext())
19356     return false;
19357 
19358   switch (ExprEvalContexts.back().Context) {
19359   case ExpressionEvaluationContext::Unevaluated:
19360   case ExpressionEvaluationContext::UnevaluatedList:
19361   case ExpressionEvaluationContext::UnevaluatedAbstract:
19362   case ExpressionEvaluationContext::DiscardedStatement:
19363     // The argument will never be evaluated, so don't complain.
19364     break;
19365 
19366   case ExpressionEvaluationContext::ConstantEvaluated:
19367   case ExpressionEvaluationContext::ImmediateFunctionContext:
19368     // Relevant diagnostics should be produced by constant evaluation.
19369     break;
19370 
19371   case ExpressionEvaluationContext::PotentiallyEvaluated:
19372   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19373     return DiagIfReachable(Loc, Stmts, PD);
19374   }
19375 
19376   return false;
19377 }
19378 
19379 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19380                                const PartialDiagnostic &PD) {
19381   return DiagRuntimeBehavior(
19382       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19383 }
19384 
19385 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19386                                CallExpr *CE, FunctionDecl *FD) {
19387   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19388     return false;
19389 
19390   // If we're inside a decltype's expression, don't check for a valid return
19391   // type or construct temporaries until we know whether this is the last call.
19392   if (ExprEvalContexts.back().ExprContext ==
19393       ExpressionEvaluationContextRecord::EK_Decltype) {
19394     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19395     return false;
19396   }
19397 
19398   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19399     FunctionDecl *FD;
19400     CallExpr *CE;
19401 
19402   public:
19403     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19404       : FD(FD), CE(CE) { }
19405 
19406     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19407       if (!FD) {
19408         S.Diag(Loc, diag::err_call_incomplete_return)
19409           << T << CE->getSourceRange();
19410         return;
19411       }
19412 
19413       S.Diag(Loc, diag::err_call_function_incomplete_return)
19414           << CE->getSourceRange() << FD << T;
19415       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19416           << FD->getDeclName();
19417     }
19418   } Diagnoser(FD, CE);
19419 
19420   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19421     return true;
19422 
19423   return false;
19424 }
19425 
19426 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19427 // will prevent this condition from triggering, which is what we want.
19428 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19429   SourceLocation Loc;
19430 
19431   unsigned diagnostic = diag::warn_condition_is_assignment;
19432   bool IsOrAssign = false;
19433 
19434   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19435     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19436       return;
19437 
19438     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19439 
19440     // Greylist some idioms by putting them into a warning subcategory.
19441     if (ObjCMessageExpr *ME
19442           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19443       Selector Sel = ME->getSelector();
19444 
19445       // self = [<foo> init...]
19446       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19447         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19448 
19449       // <foo> = [<bar> nextObject]
19450       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19451         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19452     }
19453 
19454     Loc = Op->getOperatorLoc();
19455   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19456     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19457       return;
19458 
19459     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19460     Loc = Op->getOperatorLoc();
19461   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19462     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19463   else {
19464     // Not an assignment.
19465     return;
19466   }
19467 
19468   Diag(Loc, diagnostic) << E->getSourceRange();
19469 
19470   SourceLocation Open = E->getBeginLoc();
19471   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19472   Diag(Loc, diag::note_condition_assign_silence)
19473         << FixItHint::CreateInsertion(Open, "(")
19474         << FixItHint::CreateInsertion(Close, ")");
19475 
19476   if (IsOrAssign)
19477     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19478       << FixItHint::CreateReplacement(Loc, "!=");
19479   else
19480     Diag(Loc, diag::note_condition_assign_to_comparison)
19481       << FixItHint::CreateReplacement(Loc, "==");
19482 }
19483 
19484 /// Redundant parentheses over an equality comparison can indicate
19485 /// that the user intended an assignment used as condition.
19486 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19487   // Don't warn if the parens came from a macro.
19488   SourceLocation parenLoc = ParenE->getBeginLoc();
19489   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19490     return;
19491   // Don't warn for dependent expressions.
19492   if (ParenE->isTypeDependent())
19493     return;
19494 
19495   Expr *E = ParenE->IgnoreParens();
19496 
19497   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19498     if (opE->getOpcode() == BO_EQ &&
19499         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19500                                                            == Expr::MLV_Valid) {
19501       SourceLocation Loc = opE->getOperatorLoc();
19502 
19503       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19504       SourceRange ParenERange = ParenE->getSourceRange();
19505       Diag(Loc, diag::note_equality_comparison_silence)
19506         << FixItHint::CreateRemoval(ParenERange.getBegin())
19507         << FixItHint::CreateRemoval(ParenERange.getEnd());
19508       Diag(Loc, diag::note_equality_comparison_to_assign)
19509         << FixItHint::CreateReplacement(Loc, "=");
19510     }
19511 }
19512 
19513 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19514                                        bool IsConstexpr) {
19515   DiagnoseAssignmentAsCondition(E);
19516   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19517     DiagnoseEqualityWithExtraParens(parenE);
19518 
19519   ExprResult result = CheckPlaceholderExpr(E);
19520   if (result.isInvalid()) return ExprError();
19521   E = result.get();
19522 
19523   if (!E->isTypeDependent()) {
19524     if (getLangOpts().CPlusPlus)
19525       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19526 
19527     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19528     if (ERes.isInvalid())
19529       return ExprError();
19530     E = ERes.get();
19531 
19532     QualType T = E->getType();
19533     if (!T->isScalarType()) { // C99 6.8.4.1p1
19534       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19535         << T << E->getSourceRange();
19536       return ExprError();
19537     }
19538     CheckBoolLikeConversion(E, Loc);
19539   }
19540 
19541   return E;
19542 }
19543 
19544 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19545                                            Expr *SubExpr, ConditionKind CK,
19546                                            bool MissingOK) {
19547   // MissingOK indicates whether having no condition expression is valid
19548   // (for loop) or invalid (e.g. while loop).
19549   if (!SubExpr)
19550     return MissingOK ? ConditionResult() : ConditionError();
19551 
19552   ExprResult Cond;
19553   switch (CK) {
19554   case ConditionKind::Boolean:
19555     Cond = CheckBooleanCondition(Loc, SubExpr);
19556     break;
19557 
19558   case ConditionKind::ConstexprIf:
19559     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19560     break;
19561 
19562   case ConditionKind::Switch:
19563     Cond = CheckSwitchCondition(Loc, SubExpr);
19564     break;
19565   }
19566   if (Cond.isInvalid()) {
19567     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19568                               {SubExpr}, PreferredConditionType(CK));
19569     if (!Cond.get())
19570       return ConditionError();
19571   }
19572   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19573   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19574   if (!FullExpr.get())
19575     return ConditionError();
19576 
19577   return ConditionResult(*this, nullptr, FullExpr,
19578                          CK == ConditionKind::ConstexprIf);
19579 }
19580 
19581 namespace {
19582   /// A visitor for rebuilding a call to an __unknown_any expression
19583   /// to have an appropriate type.
19584   struct RebuildUnknownAnyFunction
19585     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19586 
19587     Sema &S;
19588 
19589     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19590 
19591     ExprResult VisitStmt(Stmt *S) {
19592       llvm_unreachable("unexpected statement!");
19593     }
19594 
19595     ExprResult VisitExpr(Expr *E) {
19596       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19597         << E->getSourceRange();
19598       return ExprError();
19599     }
19600 
19601     /// Rebuild an expression which simply semantically wraps another
19602     /// expression which it shares the type and value kind of.
19603     template <class T> ExprResult rebuildSugarExpr(T *E) {
19604       ExprResult SubResult = Visit(E->getSubExpr());
19605       if (SubResult.isInvalid()) return ExprError();
19606 
19607       Expr *SubExpr = SubResult.get();
19608       E->setSubExpr(SubExpr);
19609       E->setType(SubExpr->getType());
19610       E->setValueKind(SubExpr->getValueKind());
19611       assert(E->getObjectKind() == OK_Ordinary);
19612       return E;
19613     }
19614 
19615     ExprResult VisitParenExpr(ParenExpr *E) {
19616       return rebuildSugarExpr(E);
19617     }
19618 
19619     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19620       return rebuildSugarExpr(E);
19621     }
19622 
19623     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19624       ExprResult SubResult = Visit(E->getSubExpr());
19625       if (SubResult.isInvalid()) return ExprError();
19626 
19627       Expr *SubExpr = SubResult.get();
19628       E->setSubExpr(SubExpr);
19629       E->setType(S.Context.getPointerType(SubExpr->getType()));
19630       assert(E->isPRValue());
19631       assert(E->getObjectKind() == OK_Ordinary);
19632       return E;
19633     }
19634 
19635     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19636       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19637 
19638       E->setType(VD->getType());
19639 
19640       assert(E->isPRValue());
19641       if (S.getLangOpts().CPlusPlus &&
19642           !(isa<CXXMethodDecl>(VD) &&
19643             cast<CXXMethodDecl>(VD)->isInstance()))
19644         E->setValueKind(VK_LValue);
19645 
19646       return E;
19647     }
19648 
19649     ExprResult VisitMemberExpr(MemberExpr *E) {
19650       return resolveDecl(E, E->getMemberDecl());
19651     }
19652 
19653     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19654       return resolveDecl(E, E->getDecl());
19655     }
19656   };
19657 }
19658 
19659 /// Given a function expression of unknown-any type, try to rebuild it
19660 /// to have a function type.
19661 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19662   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19663   if (Result.isInvalid()) return ExprError();
19664   return S.DefaultFunctionArrayConversion(Result.get());
19665 }
19666 
19667 namespace {
19668   /// A visitor for rebuilding an expression of type __unknown_anytype
19669   /// into one which resolves the type directly on the referring
19670   /// expression.  Strict preservation of the original source
19671   /// structure is not a goal.
19672   struct RebuildUnknownAnyExpr
19673     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19674 
19675     Sema &S;
19676 
19677     /// The current destination type.
19678     QualType DestType;
19679 
19680     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19681       : S(S), DestType(CastType) {}
19682 
19683     ExprResult VisitStmt(Stmt *S) {
19684       llvm_unreachable("unexpected statement!");
19685     }
19686 
19687     ExprResult VisitExpr(Expr *E) {
19688       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19689         << E->getSourceRange();
19690       return ExprError();
19691     }
19692 
19693     ExprResult VisitCallExpr(CallExpr *E);
19694     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19695 
19696     /// Rebuild an expression which simply semantically wraps another
19697     /// expression which it shares the type and value kind of.
19698     template <class T> ExprResult rebuildSugarExpr(T *E) {
19699       ExprResult SubResult = Visit(E->getSubExpr());
19700       if (SubResult.isInvalid()) return ExprError();
19701       Expr *SubExpr = SubResult.get();
19702       E->setSubExpr(SubExpr);
19703       E->setType(SubExpr->getType());
19704       E->setValueKind(SubExpr->getValueKind());
19705       assert(E->getObjectKind() == OK_Ordinary);
19706       return E;
19707     }
19708 
19709     ExprResult VisitParenExpr(ParenExpr *E) {
19710       return rebuildSugarExpr(E);
19711     }
19712 
19713     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19714       return rebuildSugarExpr(E);
19715     }
19716 
19717     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19718       const PointerType *Ptr = DestType->getAs<PointerType>();
19719       if (!Ptr) {
19720         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19721           << E->getSourceRange();
19722         return ExprError();
19723       }
19724 
19725       if (isa<CallExpr>(E->getSubExpr())) {
19726         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19727           << E->getSourceRange();
19728         return ExprError();
19729       }
19730 
19731       assert(E->isPRValue());
19732       assert(E->getObjectKind() == OK_Ordinary);
19733       E->setType(DestType);
19734 
19735       // Build the sub-expression as if it were an object of the pointee type.
19736       DestType = Ptr->getPointeeType();
19737       ExprResult SubResult = Visit(E->getSubExpr());
19738       if (SubResult.isInvalid()) return ExprError();
19739       E->setSubExpr(SubResult.get());
19740       return E;
19741     }
19742 
19743     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19744 
19745     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19746 
19747     ExprResult VisitMemberExpr(MemberExpr *E) {
19748       return resolveDecl(E, E->getMemberDecl());
19749     }
19750 
19751     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19752       return resolveDecl(E, E->getDecl());
19753     }
19754   };
19755 }
19756 
19757 /// Rebuilds a call expression which yielded __unknown_anytype.
19758 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19759   Expr *CalleeExpr = E->getCallee();
19760 
19761   enum FnKind {
19762     FK_MemberFunction,
19763     FK_FunctionPointer,
19764     FK_BlockPointer
19765   };
19766 
19767   FnKind Kind;
19768   QualType CalleeType = CalleeExpr->getType();
19769   if (CalleeType == S.Context.BoundMemberTy) {
19770     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19771     Kind = FK_MemberFunction;
19772     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19773   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19774     CalleeType = Ptr->getPointeeType();
19775     Kind = FK_FunctionPointer;
19776   } else {
19777     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19778     Kind = FK_BlockPointer;
19779   }
19780   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19781 
19782   // Verify that this is a legal result type of a function.
19783   if (DestType->isArrayType() || DestType->isFunctionType()) {
19784     unsigned diagID = diag::err_func_returning_array_function;
19785     if (Kind == FK_BlockPointer)
19786       diagID = diag::err_block_returning_array_function;
19787 
19788     S.Diag(E->getExprLoc(), diagID)
19789       << DestType->isFunctionType() << DestType;
19790     return ExprError();
19791   }
19792 
19793   // Otherwise, go ahead and set DestType as the call's result.
19794   E->setType(DestType.getNonLValueExprType(S.Context));
19795   E->setValueKind(Expr::getValueKindForType(DestType));
19796   assert(E->getObjectKind() == OK_Ordinary);
19797 
19798   // Rebuild the function type, replacing the result type with DestType.
19799   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19800   if (Proto) {
19801     // __unknown_anytype(...) is a special case used by the debugger when
19802     // it has no idea what a function's signature is.
19803     //
19804     // We want to build this call essentially under the K&R
19805     // unprototyped rules, but making a FunctionNoProtoType in C++
19806     // would foul up all sorts of assumptions.  However, we cannot
19807     // simply pass all arguments as variadic arguments, nor can we
19808     // portably just call the function under a non-variadic type; see
19809     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19810     // However, it turns out that in practice it is generally safe to
19811     // call a function declared as "A foo(B,C,D);" under the prototype
19812     // "A foo(B,C,D,...);".  The only known exception is with the
19813     // Windows ABI, where any variadic function is implicitly cdecl
19814     // regardless of its normal CC.  Therefore we change the parameter
19815     // types to match the types of the arguments.
19816     //
19817     // This is a hack, but it is far superior to moving the
19818     // corresponding target-specific code from IR-gen to Sema/AST.
19819 
19820     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19821     SmallVector<QualType, 8> ArgTypes;
19822     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19823       ArgTypes.reserve(E->getNumArgs());
19824       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19825         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19826       }
19827       ParamTypes = ArgTypes;
19828     }
19829     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19830                                          Proto->getExtProtoInfo());
19831   } else {
19832     DestType = S.Context.getFunctionNoProtoType(DestType,
19833                                                 FnType->getExtInfo());
19834   }
19835 
19836   // Rebuild the appropriate pointer-to-function type.
19837   switch (Kind) {
19838   case FK_MemberFunction:
19839     // Nothing to do.
19840     break;
19841 
19842   case FK_FunctionPointer:
19843     DestType = S.Context.getPointerType(DestType);
19844     break;
19845 
19846   case FK_BlockPointer:
19847     DestType = S.Context.getBlockPointerType(DestType);
19848     break;
19849   }
19850 
19851   // Finally, we can recurse.
19852   ExprResult CalleeResult = Visit(CalleeExpr);
19853   if (!CalleeResult.isUsable()) return ExprError();
19854   E->setCallee(CalleeResult.get());
19855 
19856   // Bind a temporary if necessary.
19857   return S.MaybeBindToTemporary(E);
19858 }
19859 
19860 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19861   // Verify that this is a legal result type of a call.
19862   if (DestType->isArrayType() || DestType->isFunctionType()) {
19863     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19864       << DestType->isFunctionType() << DestType;
19865     return ExprError();
19866   }
19867 
19868   // Rewrite the method result type if available.
19869   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19870     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19871     Method->setReturnType(DestType);
19872   }
19873 
19874   // Change the type of the message.
19875   E->setType(DestType.getNonReferenceType());
19876   E->setValueKind(Expr::getValueKindForType(DestType));
19877 
19878   return S.MaybeBindToTemporary(E);
19879 }
19880 
19881 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19882   // The only case we should ever see here is a function-to-pointer decay.
19883   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19884     assert(E->isPRValue());
19885     assert(E->getObjectKind() == OK_Ordinary);
19886 
19887     E->setType(DestType);
19888 
19889     // Rebuild the sub-expression as the pointee (function) type.
19890     DestType = DestType->castAs<PointerType>()->getPointeeType();
19891 
19892     ExprResult Result = Visit(E->getSubExpr());
19893     if (!Result.isUsable()) return ExprError();
19894 
19895     E->setSubExpr(Result.get());
19896     return E;
19897   } else if (E->getCastKind() == CK_LValueToRValue) {
19898     assert(E->isPRValue());
19899     assert(E->getObjectKind() == OK_Ordinary);
19900 
19901     assert(isa<BlockPointerType>(E->getType()));
19902 
19903     E->setType(DestType);
19904 
19905     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19906     DestType = S.Context.getLValueReferenceType(DestType);
19907 
19908     ExprResult Result = Visit(E->getSubExpr());
19909     if (!Result.isUsable()) return ExprError();
19910 
19911     E->setSubExpr(Result.get());
19912     return E;
19913   } else {
19914     llvm_unreachable("Unhandled cast type!");
19915   }
19916 }
19917 
19918 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19919   ExprValueKind ValueKind = VK_LValue;
19920   QualType Type = DestType;
19921 
19922   // We know how to make this work for certain kinds of decls:
19923 
19924   //  - functions
19925   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19926     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19927       DestType = Ptr->getPointeeType();
19928       ExprResult Result = resolveDecl(E, VD);
19929       if (Result.isInvalid()) return ExprError();
19930       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19931                                  VK_PRValue);
19932     }
19933 
19934     if (!Type->isFunctionType()) {
19935       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19936         << VD << E->getSourceRange();
19937       return ExprError();
19938     }
19939     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19940       // We must match the FunctionDecl's type to the hack introduced in
19941       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19942       // type. See the lengthy commentary in that routine.
19943       QualType FDT = FD->getType();
19944       const FunctionType *FnType = FDT->castAs<FunctionType>();
19945       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19946       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19947       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19948         SourceLocation Loc = FD->getLocation();
19949         FunctionDecl *NewFD = FunctionDecl::Create(
19950             S.Context, FD->getDeclContext(), Loc, Loc,
19951             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19952             SC_None, S.getCurFPFeatures().isFPConstrained(),
19953             false /*isInlineSpecified*/, FD->hasPrototype(),
19954             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19955 
19956         if (FD->getQualifier())
19957           NewFD->setQualifierInfo(FD->getQualifierLoc());
19958 
19959         SmallVector<ParmVarDecl*, 16> Params;
19960         for (const auto &AI : FT->param_types()) {
19961           ParmVarDecl *Param =
19962             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19963           Param->setScopeInfo(0, Params.size());
19964           Params.push_back(Param);
19965         }
19966         NewFD->setParams(Params);
19967         DRE->setDecl(NewFD);
19968         VD = DRE->getDecl();
19969       }
19970     }
19971 
19972     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19973       if (MD->isInstance()) {
19974         ValueKind = VK_PRValue;
19975         Type = S.Context.BoundMemberTy;
19976       }
19977 
19978     // Function references aren't l-values in C.
19979     if (!S.getLangOpts().CPlusPlus)
19980       ValueKind = VK_PRValue;
19981 
19982   //  - variables
19983   } else if (isa<VarDecl>(VD)) {
19984     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19985       Type = RefTy->getPointeeType();
19986     } else if (Type->isFunctionType()) {
19987       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19988         << VD << E->getSourceRange();
19989       return ExprError();
19990     }
19991 
19992   //  - nothing else
19993   } else {
19994     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19995       << VD << E->getSourceRange();
19996     return ExprError();
19997   }
19998 
19999   // Modifying the declaration like this is friendly to IR-gen but
20000   // also really dangerous.
20001   VD->setType(DestType);
20002   E->setType(Type);
20003   E->setValueKind(ValueKind);
20004   return E;
20005 }
20006 
20007 /// Check a cast of an unknown-any type.  We intentionally only
20008 /// trigger this for C-style casts.
20009 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20010                                      Expr *CastExpr, CastKind &CastKind,
20011                                      ExprValueKind &VK, CXXCastPath &Path) {
20012   // The type we're casting to must be either void or complete.
20013   if (!CastType->isVoidType() &&
20014       RequireCompleteType(TypeRange.getBegin(), CastType,
20015                           diag::err_typecheck_cast_to_incomplete))
20016     return ExprError();
20017 
20018   // Rewrite the casted expression from scratch.
20019   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20020   if (!result.isUsable()) return ExprError();
20021 
20022   CastExpr = result.get();
20023   VK = CastExpr->getValueKind();
20024   CastKind = CK_NoOp;
20025 
20026   return CastExpr;
20027 }
20028 
20029 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20030   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20031 }
20032 
20033 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20034                                     Expr *arg, QualType &paramType) {
20035   // If the syntactic form of the argument is not an explicit cast of
20036   // any sort, just do default argument promotion.
20037   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20038   if (!castArg) {
20039     ExprResult result = DefaultArgumentPromotion(arg);
20040     if (result.isInvalid()) return ExprError();
20041     paramType = result.get()->getType();
20042     return result;
20043   }
20044 
20045   // Otherwise, use the type that was written in the explicit cast.
20046   assert(!arg->hasPlaceholderType());
20047   paramType = castArg->getTypeAsWritten();
20048 
20049   // Copy-initialize a parameter of that type.
20050   InitializedEntity entity =
20051     InitializedEntity::InitializeParameter(Context, paramType,
20052                                            /*consumed*/ false);
20053   return PerformCopyInitialization(entity, callLoc, arg);
20054 }
20055 
20056 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20057   Expr *orig = E;
20058   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20059   while (true) {
20060     E = E->IgnoreParenImpCasts();
20061     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20062       E = call->getCallee();
20063       diagID = diag::err_uncasted_call_of_unknown_any;
20064     } else {
20065       break;
20066     }
20067   }
20068 
20069   SourceLocation loc;
20070   NamedDecl *d;
20071   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20072     loc = ref->getLocation();
20073     d = ref->getDecl();
20074   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20075     loc = mem->getMemberLoc();
20076     d = mem->getMemberDecl();
20077   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20078     diagID = diag::err_uncasted_call_of_unknown_any;
20079     loc = msg->getSelectorStartLoc();
20080     d = msg->getMethodDecl();
20081     if (!d) {
20082       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20083         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20084         << orig->getSourceRange();
20085       return ExprError();
20086     }
20087   } else {
20088     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20089       << E->getSourceRange();
20090     return ExprError();
20091   }
20092 
20093   S.Diag(loc, diagID) << d << orig->getSourceRange();
20094 
20095   // Never recoverable.
20096   return ExprError();
20097 }
20098 
20099 /// Check for operands with placeholder types and complain if found.
20100 /// Returns ExprError() if there was an error and no recovery was possible.
20101 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20102   if (!Context.isDependenceAllowed()) {
20103     // C cannot handle TypoExpr nodes on either side of a binop because it
20104     // doesn't handle dependent types properly, so make sure any TypoExprs have
20105     // been dealt with before checking the operands.
20106     ExprResult Result = CorrectDelayedTyposInExpr(E);
20107     if (!Result.isUsable()) return ExprError();
20108     E = Result.get();
20109   }
20110 
20111   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20112   if (!placeholderType) return E;
20113 
20114   switch (placeholderType->getKind()) {
20115 
20116   // Overloaded expressions.
20117   case BuiltinType::Overload: {
20118     // Try to resolve a single function template specialization.
20119     // This is obligatory.
20120     ExprResult Result = E;
20121     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20122       return Result;
20123 
20124     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20125     // leaves Result unchanged on failure.
20126     Result = E;
20127     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20128       return Result;
20129 
20130     // If that failed, try to recover with a call.
20131     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20132                          /*complain*/ true);
20133     return Result;
20134   }
20135 
20136   // Bound member functions.
20137   case BuiltinType::BoundMember: {
20138     ExprResult result = E;
20139     const Expr *BME = E->IgnoreParens();
20140     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20141     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20142     if (isa<CXXPseudoDestructorExpr>(BME)) {
20143       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20144     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20145       if (ME->getMemberNameInfo().getName().getNameKind() ==
20146           DeclarationName::CXXDestructorName)
20147         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20148     }
20149     tryToRecoverWithCall(result, PD,
20150                          /*complain*/ true);
20151     return result;
20152   }
20153 
20154   // ARC unbridged casts.
20155   case BuiltinType::ARCUnbridgedCast: {
20156     Expr *realCast = stripARCUnbridgedCast(E);
20157     diagnoseARCUnbridgedCast(realCast);
20158     return realCast;
20159   }
20160 
20161   // Expressions of unknown type.
20162   case BuiltinType::UnknownAny:
20163     return diagnoseUnknownAnyExpr(*this, E);
20164 
20165   // Pseudo-objects.
20166   case BuiltinType::PseudoObject:
20167     return checkPseudoObjectRValue(E);
20168 
20169   case BuiltinType::BuiltinFn: {
20170     // Accept __noop without parens by implicitly converting it to a call expr.
20171     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20172     if (DRE) {
20173       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20174       if (FD->getBuiltinID() == Builtin::BI__noop) {
20175         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20176                               CK_BuiltinFnToFnPtr)
20177                 .get();
20178         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20179                                 VK_PRValue, SourceLocation(),
20180                                 FPOptionsOverride());
20181       }
20182     }
20183 
20184     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20185     return ExprError();
20186   }
20187 
20188   case BuiltinType::IncompleteMatrixIdx:
20189     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20190              ->getRowIdx()
20191              ->getBeginLoc(),
20192          diag::err_matrix_incomplete_index);
20193     return ExprError();
20194 
20195   // Expressions of unknown type.
20196   case BuiltinType::OMPArraySection:
20197     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20198     return ExprError();
20199 
20200   // Expressions of unknown type.
20201   case BuiltinType::OMPArrayShaping:
20202     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20203 
20204   case BuiltinType::OMPIterator:
20205     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20206 
20207   // Everything else should be impossible.
20208 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20209   case BuiltinType::Id:
20210 #include "clang/Basic/OpenCLImageTypes.def"
20211 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20212   case BuiltinType::Id:
20213 #include "clang/Basic/OpenCLExtensionTypes.def"
20214 #define SVE_TYPE(Name, Id, SingletonId) \
20215   case BuiltinType::Id:
20216 #include "clang/Basic/AArch64SVEACLETypes.def"
20217 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20218   case BuiltinType::Id:
20219 #include "clang/Basic/PPCTypes.def"
20220 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20221 #include "clang/Basic/RISCVVTypes.def"
20222 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20223 #define PLACEHOLDER_TYPE(Id, SingletonId)
20224 #include "clang/AST/BuiltinTypes.def"
20225     break;
20226   }
20227 
20228   llvm_unreachable("invalid placeholder type!");
20229 }
20230 
20231 bool Sema::CheckCaseExpression(Expr *E) {
20232   if (E->isTypeDependent())
20233     return true;
20234   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20235     return E->getType()->isIntegralOrEnumerationType();
20236   return false;
20237 }
20238 
20239 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20240 ExprResult
20241 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20242   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20243          "Unknown Objective-C Boolean value!");
20244   QualType BoolT = Context.ObjCBuiltinBoolTy;
20245   if (!Context.getBOOLDecl()) {
20246     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20247                         Sema::LookupOrdinaryName);
20248     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20249       NamedDecl *ND = Result.getFoundDecl();
20250       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20251         Context.setBOOLDecl(TD);
20252     }
20253   }
20254   if (Context.getBOOLDecl())
20255     BoolT = Context.getBOOLType();
20256   return new (Context)
20257       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20258 }
20259 
20260 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20261     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20262     SourceLocation RParen) {
20263   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20264     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20265       return Spec.getPlatform() == Platform;
20266     });
20267     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20268     // for "maccatalyst" if "maccatalyst" is not specified.
20269     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20270       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20271         return Spec.getPlatform() == "ios";
20272       });
20273     }
20274     if (Spec == AvailSpecs.end())
20275       return None;
20276     return Spec->getVersion();
20277   };
20278 
20279   VersionTuple Version;
20280   if (auto MaybeVersion =
20281           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20282     Version = *MaybeVersion;
20283 
20284   // The use of `@available` in the enclosing context should be analyzed to
20285   // warn when it's used inappropriately (i.e. not if(@available)).
20286   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20287     Context->HasPotentialAvailabilityViolations = true;
20288 
20289   return new (Context)
20290       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20291 }
20292 
20293 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20294                                     ArrayRef<Expr *> SubExprs, QualType T) {
20295   if (!Context.getLangOpts().RecoveryAST)
20296     return ExprError();
20297 
20298   if (isSFINAEContext())
20299     return ExprError();
20300 
20301   if (T.isNull() || T->isUndeducedType() ||
20302       !Context.getLangOpts().RecoveryASTType)
20303     // We don't know the concrete type, fallback to dependent type.
20304     T = Context.DependentTy;
20305 
20306   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20307 }
20308